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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.955   ! raeburn     4: # $Id: lonnet.pm,v 1.954 2008/04/04 16:56:11 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\:/) {
1.954     raeburn  1699:        ($output,$response)=&externalssi($filelink);
1.953     www      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.954     raeburn  1764:     if (wantarray) {
                   1765:         return ($response->content, $response);
                   1766:     } else {
                   1767:         return $response->content;
                   1768:     }
1.15      www      1769: }
1.254     www      1770: 
1.492     albertel 1771: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1772: 
                   1773: sub allowuploaded {
                   1774:     my ($srcurl,$url)=@_;
                   1775:     $url=&clutter(&declutter($url));
                   1776:     my $dir=$url;
                   1777:     $dir=~s/\/[^\/]+$//;
                   1778:     my %httpref=();
                   1779:     my $httpurl=&hreflocation('',$url);
                   1780:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1781:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1782: }
1.477     raeburn  1783: 
1.478     albertel 1784: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1785: # input: action, courseID, current domain, intended
1.637     raeburn  1786: #        path to file, source of file, instruction to parse file for objects,
                   1787: #        ref to hash for embedded objects,
                   1788: #        ref to hash for codebase of java objects.
                   1789: #
1.485     raeburn  1790: # output: url to file (if action was uploaddoc), 
                   1791: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1792: #
1.478     albertel 1793: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1794: # course.
1.477     raeburn  1795: #
1.478     albertel 1796: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1797: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1798: #          course's home server.
1.477     raeburn  1799: #
1.478     albertel 1800: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1801: #          be copied from $source (current location) to 
                   1802: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1803: #         and will then be copied to
                   1804: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1805: #         course's home server.
1.485     raeburn  1806: #
1.481     raeburn  1807: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1808: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1809: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1810: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1811: #         in course's home server.
1.637     raeburn  1812: #
1.477     raeburn  1813: 
                   1814: sub process_coursefile {
1.638     albertel 1815:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1816:     my $fetchresult;
1.638     albertel 1817:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1818:     if ($action eq 'propagate') {
1.638     albertel 1819:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1820: 			     $home);
1.481     raeburn  1821:     } else {
1.477     raeburn  1822:         my $fpath = '';
                   1823:         my $fname = $file;
1.478     albertel 1824:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1825:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1826:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1827:         if ($action eq 'copy') {
                   1828:             if ($source eq '') {
                   1829:                 $fetchresult = 'no source file';
                   1830:                 return $fetchresult;
                   1831:             } else {
                   1832:                 my $destination = $filepath.'/'.$fname;
                   1833:                 rename($source,$destination);
                   1834:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1835:                                  $home);
1.481     raeburn  1836:             }
                   1837:         } elsif ($action eq 'uploaddoc') {
                   1838:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1839:             print $fh $env{'form.'.$source};
1.481     raeburn  1840:             close($fh);
1.637     raeburn  1841:             if ($parser eq 'parse') {
                   1842:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1843:                 unless ($parse_result eq 'ok') {
                   1844:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1845:                 }
                   1846:             }
1.477     raeburn  1847:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1848:                                  $home);
1.481     raeburn  1849:             if ($fetchresult eq 'ok') {
                   1850:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1851:             } else {
                   1852:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1853:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1854:                 return '/adm/notfound.html';
                   1855:             }
1.477     raeburn  1856:         }
                   1857:     }
1.485     raeburn  1858:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1859:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1860:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1861:     }
                   1862:     return $fetchresult;
                   1863: }
                   1864: 
1.637     raeburn  1865: sub build_filepath {
                   1866:     my ($fpath) = @_;
                   1867:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1868:     unless ($fpath eq '') {
                   1869:         my @parts=split('/',$fpath);
                   1870:         foreach my $part (@parts) {
                   1871:             $filepath.= '/'.$part;
                   1872:             if ((-e $filepath)!=1) {
                   1873:                 mkdir($filepath,0777);
                   1874:             }
                   1875:         }
                   1876:     }
                   1877:     return $filepath;
                   1878: }
                   1879: 
                   1880: sub store_edited_file {
1.638     albertel 1881:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1882:     my $file = $primary_url;
                   1883:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1884:     my $fpath = '';
                   1885:     my $fname = $file;
                   1886:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1887:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1888:     my $filepath = &build_filepath($fpath);
                   1889:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1890:     print $fh $content;
                   1891:     close($fh);
1.638     albertel 1892:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1893:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1894: 			  $home);
1.637     raeburn  1895:     if ($$fetchresult eq 'ok') {
                   1896:         return '/uploaded/'.$fpath.'/'.$fname;
                   1897:     } else {
1.638     albertel 1898:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1899: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1900:         return '/adm/notfound.html';
                   1901:     }
                   1902: }
                   1903: 
1.531     albertel 1904: sub clean_filename {
1.831     albertel 1905:     my ($fname,$args)=@_;
1.315     www      1906: # Replace Windows backslashes by forward slashes
1.257     www      1907:     $fname=~s/\\/\//g;
1.831     albertel 1908:     if (!$args->{'keep_path'}) {
                   1909:         # Get rid of everything but the actual filename
                   1910: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1911:     }
1.315     www      1912: # Replace spaces by underscores
                   1913:     $fname=~s/\s+/\_/g;
                   1914: # Replace all other weird characters by nothing
1.831     albertel 1915:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1916: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1917: # numbers
                   1918:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1919:     return $fname;
                   1920: }
                   1921: 
1.608     albertel 1922: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1923: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1924: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1925: #        $coursedoc - if true up to the current course
                   1926: #                     if false
                   1927: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1928: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1929: #        $allfiles - reference to hash for embedded objects
                   1930: #        $codebase - reference to hash for codebase of java objects
                   1931: #        $desuname - username for permanent storage of uploaded file
                   1932: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1933: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1934: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1935: # 
1.686     albertel 1936: # output: url of file in userspace, or error: <message> 
                   1937: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1938: 
                   1939: 
1.531     albertel 1940: sub userfileupload {
1.860     raeburn  1941:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1942:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1943:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1944:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1945:     $fname=&clean_filename($fname);
1.315     www      1946: # See if there is anything left
1.257     www      1947:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1948:     chop($env{'form.'.$formname});
1.523     raeburn  1949:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1950:         my $now = time;
                   1951:         my $filepath = 'tmp/helprequests/'.$now;
                   1952:         my @parts=split(/\//,$filepath);
                   1953:         my $fullpath = $perlvar{'lonDaemons'};
                   1954:         for (my $i=0;$i<@parts;$i++) {
                   1955:             $fullpath .= '/'.$parts[$i];
                   1956:             if ((-e $fullpath)!=1) {
                   1957:                 mkdir($fullpath,0777);
                   1958:             }
                   1959:         }
                   1960:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1961:         print $fh $env{'form.'.$formname};
1.523     raeburn  1962:         close($fh);
1.741     raeburn  1963:         return $fullpath.'/'.$fname;
                   1964:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1965:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1966:                        '_'.$env{'user.domain'}.'/pending';
                   1967:         my @parts=split(/\//,$filepath);
                   1968:         my $fullpath = $perlvar{'lonDaemons'};
                   1969:         for (my $i=0;$i<@parts;$i++) {
                   1970:             $fullpath .= '/'.$parts[$i];
                   1971:             if ((-e $fullpath)!=1) {
                   1972:                 mkdir($fullpath,0777);
                   1973:             }
                   1974:         }
                   1975:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1976:         print $fh $env{'form.'.$formname};
                   1977:         close($fh);
                   1978:         return $fullpath.'/'.$fname;
1.523     raeburn  1979:     }
1.719     banghart 1980:     
1.258     www      1981: # Create the directory if not present
1.493     albertel 1982:     $fname="$subdir/$fname";
1.259     www      1983:     if ($coursedoc) {
1.638     albertel 1984: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1985: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1986:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1987:             return &finishuserfileupload($docuname,$docudom,
                   1988: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1989: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1990:         } else {
1.620     albertel 1991:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1992:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1993: 				       $fname,$formname,$parser,
                   1994: 				       $allfiles,$codebase);
1.481     raeburn  1995:         }
1.719     banghart 1996:     } elsif (defined($destuname)) {
                   1997:         my $docuname=$destuname;
                   1998:         my $docudom=$destudom;
1.860     raeburn  1999: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2000: 				     $parser,$allfiles,$codebase,
                   2001:                                      $thumbwidth,$thumbheight);
1.719     banghart 2002:         
1.259     www      2003:     } else {
1.638     albertel 2004:         my $docuname=$env{'user.name'};
                   2005:         my $docudom=$env{'user.domain'};
1.714     raeburn  2006:         if (exists($env{'form.group'})) {
                   2007:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2008:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2009:         }
1.860     raeburn  2010: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2011: 				     $parser,$allfiles,$codebase,
                   2012:                                      $thumbwidth,$thumbheight);
1.259     www      2013:     }
1.271     www      2014: }
                   2015: 
                   2016: sub finishuserfileupload {
1.860     raeburn  2017:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2018:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2019:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2020:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2021:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2022:     $file=$fname;
                   2023:     if ($fname=~m|/|) {
                   2024:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2025: 	$path.=$fnamepath.'/';
                   2026:     }
1.259     www      2027:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2028:     my $count;
                   2029:     for ($count=4;$count<=$#parts;$count++) {
                   2030:         $filepath.="/$parts[$count]";
                   2031:         if ((-e $filepath)!=1) {
                   2032: 	    mkdir($filepath,0777);
                   2033:         }
                   2034:     }
                   2035: # Save the file
                   2036:     {
1.701     albertel 2037: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2038: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2039: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2040: 	    return '/adm/notfound.html';
                   2041: 	}
                   2042: 	if (!print FH ($env{'form.'.$formname})) {
                   2043: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2044: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2045: 	    return '/adm/notfound.html';
                   2046: 	}
1.570     albertel 2047: 	close(FH);
1.258     www      2048:     }
1.637     raeburn  2049:     if ($parser eq 'parse') {
1.638     albertel 2050:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2051: 						   $codebase);
1.637     raeburn  2052:         unless ($parse_result eq 'ok') {
1.638     albertel 2053:             &logthis('Failed to parse '.$filepath.$file.
                   2054: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2055:         }
                   2056:     }
1.860     raeburn  2057:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2058:         my $input = $filepath.'/'.$file;
                   2059:         my $output = $filepath.'/'.'tn-'.$file;
                   2060:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2061:         system("convert -sample $thumbsize $input $output");
                   2062:         if (-e $filepath.'/'.'tn-'.$file) {
                   2063:             $fetchthumb  = 1; 
                   2064:         }
                   2065:     }
1.858     raeburn  2066:  
1.259     www      2067: # Notify homeserver to grep it
                   2068: #
1.638     albertel 2069:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2070:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2071:     if ($fetchresult eq 'ok') {
1.860     raeburn  2072:         if ($fetchthumb) {
                   2073:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2074:             if ($thumbresult ne 'ok') {
                   2075:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2076:                          $docuhome.': '.$thumbresult);
                   2077:             }
                   2078:         }
1.259     www      2079: #
1.258     www      2080: # Return the URL to it
1.494     albertel 2081:         return '/uploaded/'.$path.$file;
1.263     www      2082:     } else {
1.494     albertel 2083:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2084: 		 ': '.$fetchresult);
1.263     www      2085:         return '/adm/notfound.html';
1.858     raeburn  2086:     }
1.493     albertel 2087: }
                   2088: 
1.637     raeburn  2089: sub extract_embedded_items {
1.648     raeburn  2090:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2091:     my @state = ();
                   2092:     my %javafiles = (
                   2093:                       codebase => '',
                   2094:                       code => '',
                   2095:                       archive => ''
                   2096:                     );
                   2097:     my %mediafiles = (
                   2098:                       src => '',
                   2099:                       movie => '',
                   2100:                      );
1.648     raeburn  2101:     my $p;
                   2102:     if ($content) {
                   2103:         $p = HTML::LCParser->new($content);
                   2104:     } else {
                   2105:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2106:     }
1.641     albertel 2107:     while (my $t=$p->get_token()) {
1.640     albertel 2108: 	if ($t->[0] eq 'S') {
                   2109: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2110: 	    push(@state, $tagname);
1.648     raeburn  2111:             if (lc($tagname) eq 'allow') {
                   2112:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2113:             }
1.640     albertel 2114: 	    if (lc($tagname) eq 'img') {
                   2115: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2116: 	    }
1.886     albertel 2117: 	    if (lc($tagname) eq 'a') {
                   2118: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2119: 	    }
1.645     raeburn  2120:             if (lc($tagname) eq 'script') {
                   2121:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2122:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2123:                 } else {
                   2124:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2125:                 }
                   2126:             }
                   2127:             if (lc($tagname) eq 'link') {
                   2128:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2129:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2130:                 }
                   2131:             }
1.640     albertel 2132: 	    if (lc($tagname) eq 'object' ||
                   2133: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2134: 		foreach my $item (keys(%javafiles)) {
                   2135: 		    $javafiles{$item} = '';
                   2136: 		}
                   2137: 	    }
                   2138: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2139: 		my $name = lc($attr->{'name'});
                   2140: 		foreach my $item (keys(%javafiles)) {
                   2141: 		    if ($name eq $item) {
                   2142: 			$javafiles{$item} = $attr->{'value'};
                   2143: 			last;
                   2144: 		    }
                   2145: 		}
                   2146: 		foreach my $item (keys(%mediafiles)) {
                   2147: 		    if ($name eq $item) {
                   2148: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2149: 			last;
                   2150: 		    }
                   2151: 		}
                   2152: 	    }
                   2153: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2154: 		foreach my $item (keys(%javafiles)) {
                   2155: 		    if ($attr->{$item}) {
                   2156: 			$javafiles{$item} = $attr->{$item};
                   2157: 			last;
                   2158: 		    }
                   2159: 		}
                   2160: 		foreach my $item (keys(%mediafiles)) {
                   2161: 		    if ($attr->{$item}) {
                   2162: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2163: 			last;
                   2164: 		    }
                   2165: 		}
                   2166: 	    }
                   2167: 	} elsif ($t->[0] eq 'E') {
                   2168: 	    my ($tagname) = ($t->[1]);
                   2169: 	    if ($javafiles{'codebase'} ne '') {
                   2170: 		$javafiles{'codebase'} .= '/';
                   2171: 	    }  
                   2172: 	    if (lc($tagname) eq 'applet' ||
                   2173: 		lc($tagname) eq 'object' ||
                   2174: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2175: 		) {
                   2176: 		foreach my $item (keys(%javafiles)) {
                   2177: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2178: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2179: 			&add_filetype($allfiles,$file,$item);
                   2180: 		    }
                   2181: 		}
                   2182: 	    } 
                   2183: 	    pop @state;
                   2184: 	}
                   2185:     }
1.637     raeburn  2186:     return 'ok';
                   2187: }
                   2188: 
1.639     albertel 2189: sub add_filetype {
                   2190:     my ($allfiles,$file,$type)=@_;
                   2191:     if (exists($allfiles->{$file})) {
                   2192: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2193: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2194: 	}
                   2195:     } else {
                   2196: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2197:     }
                   2198: }
                   2199: 
1.493     albertel 2200: sub removeuploadedurl {
                   2201:     my ($url)=@_;
                   2202:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2203:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2204: }
                   2205: 
                   2206: sub removeuserfile {
                   2207:     my ($docuname,$docudom,$fname)=@_;
                   2208:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2209:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2210:     if ($result eq 'ok') {
                   2211:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2212:             my $metafile = $fname.'.meta';
                   2213:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2214: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2215:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2216:             my $sqlresult = 
1.823     albertel 2217:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2218:                                         'portfolio_metadata',$group,
                   2219:                                         'delete');
1.798     raeburn  2220:         }
                   2221:     }
                   2222:     return $result;
1.257     www      2223: }
1.15      www      2224: 
1.530     albertel 2225: sub mkdiruserfile {
                   2226:     my ($docuname,$docudom,$dir)=@_;
                   2227:     my $home=&homeserver($docuname,$docudom);
                   2228:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2229: }
                   2230: 
1.531     albertel 2231: sub renameuserfile {
                   2232:     my ($docuname,$docudom,$old,$new)=@_;
                   2233:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2234:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2235:                         &escape("$old").':'.&escape("$new"),$home);
                   2236:     if ($result eq 'ok') {
                   2237:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2238:             my $oldmeta = $old.'.meta';
                   2239:             my $newmeta = $new.'.meta';
                   2240:             my $metaresult = 
                   2241:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2242: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2243:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2244:             my $sqlresult = 
1.823     albertel 2245:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2246:                                         'portfolio_metadata',$group,
                   2247:                                         'delete');
1.798     raeburn  2248:         }
                   2249:     }
                   2250:     return $result;
1.531     albertel 2251: }
                   2252: 
1.14      www      2253: # ------------------------------------------------------------------------- Log
                   2254: 
                   2255: sub log {
                   2256:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2257:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2258: }
                   2259: 
                   2260: # ------------------------------------------------------------------ Course Log
1.352     www      2261: #
                   2262: # This routine flushes several buffers of non-mission-critical nature
                   2263: #
1.157     www      2264: 
                   2265: sub flushcourselogs {
1.352     www      2266:     &logthis('Flushing log buffers');
                   2267: #
                   2268: # course logs
                   2269: # This is a log of all transactions in a course, which can be used
                   2270: # for data mining purposes
                   2271: #
                   2272: # It also collects the courseid database, which lists last transaction
                   2273: # times and course titles for all courseids
                   2274: #
                   2275:     my %courseidbuffer=();
1.921     raeburn  2276:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2277:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2278: 		          &escape($courselogs{$crsid}),
                   2279: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2280: 	    delete $courselogs{$crsid};
                   2281:         } else {
                   2282:             &logthis('Failed to flush log buffer for '.$crsid);
                   2283:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2284:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2285:                         " exceeded maximum size, deleting.</font>");
                   2286:                delete $courselogs{$crsid};
                   2287:             }
1.352     www      2288:         }
1.920     raeburn  2289:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2290:             'description' => $coursedescrbuf{$crsid},
                   2291:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2292:             'type'        => $coursetypebuf{$crsid},
                   2293:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2294:         };
1.191     harris41 2295:     }
1.352     www      2296: #
                   2297: # Write course id database (reverse lookup) to homeserver of courses 
                   2298: # Is used in pickcourse
                   2299: #
1.840     albertel 2300:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2301:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2302:                                     $courseidbuffer{$crs_home},
                   2303:                                     $crs_home,'timeonly');
1.352     www      2304:     }
                   2305: #
                   2306: # File accesses
                   2307: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2308: #
1.449     matthew  2309:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2310:         if ($entry =~ /___count$/) {
                   2311:             my ($dom,$name);
1.807     albertel 2312:             ($dom,$name,undef)=
1.811     albertel 2313: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2314:             if (! defined($dom) || $dom eq '' || 
                   2315:                 ! defined($name) || $name eq '') {
1.620     albertel 2316:                 my $cid = $env{'request.course.id'};
                   2317:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2318:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2319:             }
1.450     matthew  2320:             my $value = $accesshash{$entry};
                   2321:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2322:             my %temphash=($url => $value);
1.449     matthew  2323:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2324:             if ($result eq 'ok') {
                   2325:                 delete $accesshash{$entry};
                   2326:             } elsif ($result eq 'unknown_cmd') {
                   2327:                 # Target server has old code running on it.
1.450     matthew  2328:                 my %temphash=($entry => $value);
1.449     matthew  2329:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2330:                     delete $accesshash{$entry};
                   2331:                 }
                   2332:             }
                   2333:         } else {
1.811     albertel 2334:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2335:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2336:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2337:                 delete $accesshash{$entry};
                   2338:             }
1.185     www      2339:         }
1.191     harris41 2340:     }
1.352     www      2341: #
                   2342: # Roles
                   2343: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2344: #
1.800     albertel 2345:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2346:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2347: 	    split(/\:/,$entry);
                   2348:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2349:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2350:                 $rudom,$runame) eq 'ok') {
                   2351: 	    delete $userrolehash{$entry};
                   2352:         }
                   2353:     }
1.662     raeburn  2354: #
                   2355: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2356: #
                   2357:     my %domrolebuffer = ();
                   2358:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2359:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2360:         if ($domrolebuffer{$rudom}) {
                   2361:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2362:                       '='.&escape($domainrolehash{$entry});
                   2363:         } else {
                   2364:             $domrolebuffer{$rudom}.=&escape($entry).
                   2365:                       '='.&escape($domainrolehash{$entry});
                   2366:         }
                   2367:         delete $domainrolehash{$entry};
                   2368:     }
                   2369:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2370: 	my %servers = &get_servers($dom,'library');
                   2371: 	foreach my $tryserver (keys(%servers)) {
                   2372: 	    unless (&reply('domroleput:'.$dom.':'.
                   2373: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2374: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2375: 	    }
1.662     raeburn  2376:         }
                   2377:     }
1.186     www      2378:     $dumpcount++;
1.157     www      2379: }
                   2380: 
                   2381: sub courselog {
                   2382:     my $what=shift;
1.158     www      2383:     $what=time.':'.$what;
1.620     albertel 2384:     unless ($env{'request.course.id'}) { return ''; }
                   2385:     $coursedombuf{$env{'request.course.id'}}=
                   2386:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2387:     $coursenumbuf{$env{'request.course.id'}}=
                   2388:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2389:     $coursehombuf{$env{'request.course.id'}}=
                   2390:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2391:     $coursedescrbuf{$env{'request.course.id'}}=
                   2392:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2393:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2394:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2395:     $courseownerbuf{$env{'request.course.id'}}=
                   2396:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2397:     $coursetypebuf{$env{'request.course.id'}}=
                   2398:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2399:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2400: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2401:     } else {
1.620     albertel 2402: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2403:     }
1.620     albertel 2404:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2405: 	&flushcourselogs();
                   2406:     }
1.158     www      2407: }
                   2408: 
                   2409: sub courseacclog {
                   2410:     my $fnsymb=shift;
1.620     albertel 2411:     unless ($env{'request.course.id'}) { return ''; }
                   2412:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2413:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2414:         $what.=':POST';
1.583     matthew  2415:         # FIXME: Probably ought to escape things....
1.800     albertel 2416: 	foreach my $key (keys(%env)) {
                   2417:             if ($key=~/^form\.(.*)/) {
                   2418: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2419:             }
1.191     harris41 2420:         }
1.583     matthew  2421:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2422:         # FIXME: We should not be depending on a form parameter that someone
                   2423:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2424:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2425:             $what.= ':POST';
                   2426:             # FIXME: Probably ought to escape things....
                   2427:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2428:                                  'crsdiscuss') {
1.620     albertel 2429:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2430:             }
                   2431:         }
1.158     www      2432:     }
                   2433:     &courselog($what);
1.149     www      2434: }
                   2435: 
1.185     www      2436: sub countacc {
                   2437:     my $url=&declutter(shift);
1.458     matthew  2438:     return if (! defined($url) || $url eq '');
1.620     albertel 2439:     unless ($env{'request.course.id'}) { return ''; }
                   2440:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2441:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2442:     $accesshash{$key}++;
1.185     www      2443: }
1.349     www      2444: 
1.361     www      2445: sub linklog {
                   2446:     my ($from,$to)=@_;
                   2447:     $from=&declutter($from);
                   2448:     $to=&declutter($to);
                   2449:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2450:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2451: }
                   2452:   
1.349     www      2453: sub userrolelog {
                   2454:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2455:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2456:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2457:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2458:         ($trole=~/^ta/)) {
1.350     www      2459:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2460:        $userrolehash
                   2461:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2462:                     =$tend.':'.$tstart;
1.662     raeburn  2463:     }
1.898     albertel 2464:     if (($env{'request.role'} =~ /dc\./) &&
                   2465: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2466: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2467: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2468:        $userrolehash
                   2469:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2470:                     =$tend.':'.$tstart;
                   2471:     }
1.662     raeburn  2472:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2473:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2474:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2475:         ($trole=~/^sc/)) {
                   2476:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2477:        $domainrolehash
                   2478:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2479:                     = $tend.':'.$tstart;
                   2480:     }
1.351     www      2481: }
                   2482: 
                   2483: sub get_course_adv_roles {
1.948     raeburn  2484:     my ($cid,$codes) = @_;
1.620     albertel 2485:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2486:     my %coursehash=&coursedescription($cid);
1.470     www      2487:     my %nothide=();
1.800     albertel 2488:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2489:         if ($user !~ /:/) {
                   2490: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2491:         } else {
                   2492:             $nothide{$user}=1;
                   2493:         }
1.470     www      2494:     }
1.351     www      2495:     my %returnhash=();
                   2496:     my %dumphash=
                   2497:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2498:     my $now=time;
1.800     albertel 2499:     foreach my $entry (keys %dumphash) {
                   2500: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2501:         if (($tstart) && ($tstart<0)) { next; }
                   2502:         if (($tend) && ($tend<$now)) { next; }
                   2503:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2504:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2505: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2506: 	if ((&privileged($username,$domain)) && 
                   2507: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2508: 	if ($role eq 'cr') { next; }
1.948     raeburn  2509:         if ($codes) {
                   2510:             if ($section) { $role .= ':'.$section; }
                   2511:             if ($returnhash{$role}) {
                   2512:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2513:             } else {
                   2514:                 $returnhash{$role}=$username.':'.$domain;
                   2515:             }
1.351     www      2516:         } else {
1.948     raeburn  2517:             my $key=&plaintext($role);
                   2518:             if ($section) { $key.=' (Section '.$section.')'; }
                   2519:             if ($returnhash{$key}) {
                   2520: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2521:             } else {
                   2522:                 $returnhash{$key}=$username.':'.$domain;
                   2523:             }
1.351     www      2524:         }
1.948     raeburn  2525:     }
1.400     www      2526:     return %returnhash;
                   2527: }
                   2528: 
                   2529: sub get_my_roles {
1.937     raeburn  2530:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2531:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2532:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2533:     my (%dumphash,%nothide);
1.858     raeburn  2534:     if ($context eq 'userroles') { 
                   2535:         %dumphash = &dump('roles',$udom,$uname);
                   2536:     } else {
                   2537:         %dumphash=
1.400     www      2538:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2539:         if ($hidepriv) {
                   2540:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2541:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2542:                 if ($user !~ /:/) {
                   2543:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2544:                 } else {
                   2545:                     $nothide{$user} = 1;
                   2546:                 }
                   2547:             }
                   2548:         }
1.858     raeburn  2549:     }
1.400     www      2550:     my %returnhash=();
                   2551:     my $now=time;
1.800     albertel 2552:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2553:         my ($role,$tend,$tstart);
                   2554:         if ($context eq 'userroles') {
                   2555: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2556:         } else {
                   2557:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2558:         }
1.400     www      2559:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2560:         my $status = 'active';
1.939     raeburn  2561:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2562:             $status = 'previous';
                   2563:         } 
                   2564:         if (($tstart) && ($now<$tstart)) {
                   2565:             $status = 'future';
                   2566:         }
                   2567:         if (ref($types) eq 'ARRAY') {
                   2568:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2569:                 next;
                   2570:             } 
                   2571:         } else {
                   2572:             if ($status ne 'active') {
                   2573:                 next;
                   2574:             }
                   2575:         }
1.867     raeburn  2576:         my ($rolecode,$username,$domain,$section,$area);
                   2577:         if ($context eq 'userroles') {
                   2578:             ($area,$rolecode) = split(/_/,$entry);
                   2579:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2580:         } else {
                   2581:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2582:         }
1.832     raeburn  2583:         if (ref($roledoms) eq 'ARRAY') {
                   2584:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2585:                 next;
                   2586:             }
                   2587:         }
                   2588:         if (ref($roles) eq 'ARRAY') {
                   2589:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2590:                 if ($role =~ /^cr\//) {
                   2591:                     if (!grep(/^cr$/,@{$roles})) {
                   2592:                         next;
                   2593:                     }
                   2594:                 } else {
                   2595:                     next;
                   2596:                 }
1.832     raeburn  2597:             }
1.867     raeburn  2598:         }
1.937     raeburn  2599:         if ($hidepriv) {
                   2600:             if ((&privileged($username,$domain)) &&
                   2601:                 (!$nothide{$username.':'.$domain})) { 
                   2602:                 next;
                   2603:             }
                   2604:         }
1.933     raeburn  2605:         if ($withsec) {
                   2606:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2607:                 $tstart.':'.$tend;
                   2608:         } else {
                   2609:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2610:         }
1.832     raeburn  2611:     }
1.373     www      2612:     return %returnhash;
1.399     www      2613: }
                   2614: 
                   2615: # ----------------------------------------------------- Frontpage Announcements
                   2616: #
                   2617: #
                   2618: 
                   2619: sub postannounce {
                   2620:     my ($server,$text)=@_;
1.844     albertel 2621:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2622:     unless ($text=~/\w/) { $text=''; }
                   2623:     return &reply('setannounce:'.&escape($text),$server);
                   2624: }
                   2625: 
                   2626: sub getannounce {
1.448     albertel 2627: 
                   2628:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2629: 	my $announcement='';
1.800     albertel 2630: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2631: 	close($fh);
1.399     www      2632: 	if ($announcement=~/\w/) { 
                   2633: 	    return 
                   2634:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2635:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2636: 	} else {
                   2637: 	    return '';
                   2638: 	}
                   2639:     } else {
                   2640: 	return '';
                   2641:     }
1.351     www      2642: }
1.353     www      2643: 
                   2644: # ---------------------------------------------------------- Course ID routines
                   2645: # Deal with domain's nohist_courseid.db files
                   2646: #
                   2647: 
                   2648: sub courseidput {
1.921     raeburn  2649:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2650:     my $outcome;
                   2651:     if ($caller eq 'timeonly') {
                   2652:         my $cids = '';
                   2653:         foreach my $item (keys(%$storehash)) {
                   2654:             $cids.=&escape($item).'&';
                   2655:         }
                   2656:         $cids=~s/\&$//;
                   2657:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2658:                           $coursehome);       
                   2659:     } else {
                   2660:         my $items = '';
                   2661:         foreach my $item (keys(%$storehash)) {
                   2662:             $items.= &escape($item).'='.
                   2663:                      &freeze_escape($$storehash{$item}).'&';
                   2664:         }
                   2665:         $items=~s/\&$//;
                   2666:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2667:                           $coursehome);
1.918     raeburn  2668:     }
                   2669:     if ($outcome eq 'unknown_cmd') {
                   2670:         my $what;
                   2671:         foreach my $cid (keys(%$storehash)) {
                   2672:             $what .= &escape($cid).'=';
1.921     raeburn  2673:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2674:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2675:             }
                   2676:             $what =~ s/\:$/&/;
                   2677:         }
                   2678:         $what =~ s/\&$//;  
                   2679:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2680:     } else {
                   2681:         return $outcome;
                   2682:     }
1.353     www      2683: }
                   2684: 
                   2685: sub courseiddump {
1.921     raeburn  2686:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2687:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
                   2688:         $selfenrollonly)=@_;
1.918     raeburn  2689:     my $as_hash = 1;
                   2690:     my %returnhash;
                   2691:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2692:     my %libserv = &all_library();
                   2693:     foreach my $tryserver (keys(%libserv)) {
                   2694:         if ( (  $hostidflag == 1 
                   2695: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2696: 	     || (!defined($hostidflag)) ) {
                   2697: 
1.918     raeburn  2698: 	    if (($domfilter eq '') ||
                   2699: 		(&host_domain($tryserver) eq $domfilter)) {
                   2700:                 my $rep = 
                   2701:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2702:                          $sincefilter.':'.&escape($descfilter).':'.
                   2703:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2704:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2705:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   2706:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2707:                 my @pairs=split(/\&/,$rep);
                   2708:                 foreach my $item (@pairs) {
                   2709:                     my ($key,$value)=split(/\=/,$item,2);
                   2710:                     $key = &unescape($key);
                   2711:                     next if ($key =~ /^error: 2 /);
                   2712:                     my $result = &thaw_unescape($value);
                   2713:                     if (ref($result) eq 'HASH') {
                   2714:                         $returnhash{$key}=$result;
                   2715:                     } else {
1.921     raeburn  2716:                         my @responses = split(/:/,$value);
                   2717:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2718:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2719:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2720:                         }
                   2721:                     } 
1.353     www      2722:                 }
                   2723:             }
                   2724:         }
                   2725:     }
                   2726:     return %returnhash;
                   2727: }
                   2728: 
1.658     raeburn  2729: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2730: 
                   2731: sub dcmailput {
1.685     raeburn  2732:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2733:     my $status = &Apache::lonnet::critical(
1.740     www      2734:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2735:        &escape($message),$server);
1.662     raeburn  2736:     return $status;
                   2737: }
                   2738: 
1.658     raeburn  2739: sub dcmaildump {
                   2740:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2741:     my %returnhash=();
1.846     albertel 2742: 
                   2743:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2744:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2745:                                                          &escape($enddate).':';
                   2746: 	my @esc_senders=map { &escape($_)} @$senders;
                   2747: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2748: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2749:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2750:             if (($key) && ($value)) {
                   2751:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2752:             }
                   2753:         }
                   2754:     }
                   2755:     return %returnhash;
                   2756: }
1.662     raeburn  2757: # ---------------------------------------------------------- Domain roles
                   2758: 
                   2759: sub get_domain_roles {
                   2760:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2761:     if (undef($startdate) || $startdate eq '') {
                   2762:         $startdate = '.';
                   2763:     }
                   2764:     if (undef($enddate) || $enddate eq '') {
                   2765:         $enddate = '.';
                   2766:     }
1.922     raeburn  2767:     my $rolelist;
                   2768:     if (ref($roles) eq 'ARRAY') {
                   2769:         $rolelist = join(':',@{$roles});
                   2770:     }
1.662     raeburn  2771:     my %personnel = ();
1.841     albertel 2772: 
                   2773:     my %servers = &get_servers($dom,'library');
                   2774:     foreach my $tryserver (keys(%servers)) {
                   2775: 	%{$personnel{$tryserver}}=();
                   2776: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2777: 					    &escape($startdate).':'.
                   2778: 					    &escape($enddate).':'.
                   2779: 					    &escape($rolelist), $tryserver))) {
                   2780: 	    my ($key,$value) = split(/\=/,$line,2);
                   2781: 	    if (($key) && ($value)) {
                   2782: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2783: 	    }
                   2784: 	}
1.662     raeburn  2785:     }
                   2786:     return %personnel;
                   2787: }
1.658     raeburn  2788: 
1.149     www      2789: # ----------------------------------------------------------- Check out an item
                   2790: 
1.504     albertel 2791: sub get_first_access {
                   2792:     my ($type,$argsymb)=@_;
1.790     albertel 2793:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2794:     if ($argsymb) { $symb=$argsymb; }
                   2795:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2796:     if ($type eq 'course') {
                   2797: 	$res='course';
                   2798:     } elsif ($type eq 'map') {
1.588     albertel 2799: 	$res=&symbread($map);
                   2800:     } else {
                   2801: 	$res=$symb;
                   2802:     }
                   2803:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2804:     return $times{"$courseid\0$res"};
1.504     albertel 2805: }
                   2806: 
                   2807: sub set_first_access {
                   2808:     my ($type)=@_;
1.790     albertel 2809:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2810:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2811:     if ($type eq 'course') {
                   2812: 	$res='course';
                   2813:     } elsif ($type eq 'map') {
1.588     albertel 2814: 	$res=&symbread($map);
                   2815:     } else {
                   2816: 	$res=$symb;
                   2817:     }
                   2818:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2819:     if (!$firstaccess) {
1.588     albertel 2820: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2821:     }
                   2822:     return 'already_set';
1.504     albertel 2823: }
                   2824: 
1.149     www      2825: sub checkout {
                   2826:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2827:     my $now=time;
                   2828:     my $lonhost=$perlvar{'lonHostID'};
                   2829:     my $infostr=&escape(
1.234     www      2830:                  'CHECKOUTTOKEN&'.
1.149     www      2831:                  $tuname.'&'.
                   2832:                  $tudom.'&'.
                   2833:                  $tcrsid.'&'.
                   2834:                  $symb.'&'.
                   2835: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2836:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2837:     if ($token=~/^error\:/) { 
1.672     albertel 2838:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2839:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2840:                  "</font>");
                   2841:         return ''; 
                   2842:     }
                   2843: 
1.149     www      2844:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2845:     $token=~tr/a-z/A-Z/;
                   2846: 
1.153     www      2847:     my %infohash=('resource.0.outtoken' => $token,
                   2848:                   'resource.0.checkouttime' => $now,
                   2849:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2850: 
                   2851:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2852:        return '';
1.151     www      2853:     } else {
1.672     albertel 2854:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2855:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2856:                  "</font>");
1.149     www      2857:     }    
                   2858: 
                   2859:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2860:                          &escape('Checkout '.$infostr.' - '.
                   2861:                                                  $token)) ne 'ok') {
                   2862: 	return '';
1.151     www      2863:     } else {
1.672     albertel 2864:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2865:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2866:                  "</font>");
1.149     www      2867:     }
1.151     www      2868:     return $token;
1.149     www      2869: }
                   2870: 
                   2871: # ------------------------------------------------------------ Check in an item
                   2872: 
                   2873: sub checkin {
                   2874:     my $token=shift;
1.150     www      2875:     my $now=time;
                   2876:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2877:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2878:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2879:     $dtoken=~s/\W/\_/g;
1.234     www      2880:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2881:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2882: 
1.154     www      2883:     unless (($tuname) && ($tudom)) {
                   2884:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2885:         return '';
                   2886:     }
                   2887:     
                   2888:     unless (&allowed('mgr',$tcrsid)) {
                   2889:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2890:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2891:         return '';
                   2892:     }
                   2893: 
1.153     www      2894:     my %infohash=('resource.0.intoken' => $token,
                   2895:                   'resource.0.checkintime' => $now,
                   2896:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2897: 
                   2898:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2899:        return '';
                   2900:     }    
                   2901: 
                   2902:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2903:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2904: 	return '';
                   2905:     }
                   2906: 
                   2907:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2908: }
                   2909: 
                   2910: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2911: 
                   2912: sub expirespread {
                   2913:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2914:     my $cid=$env{'request.course.id'}; 
1.110     www      2915:     if ($cid) {
                   2916:        my $now=time;
                   2917:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2918:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2919:                             $env{'course.'.$cid.'.num'}.
1.110     www      2920: 	        	    ':nohist_expirationdates:'.
                   2921:                             &escape($key).'='.$now,
1.620     albertel 2922:                             $env{'course.'.$cid.'.home'})
1.110     www      2923:     }
                   2924:     return 'ok';
1.14      www      2925: }
                   2926: 
1.109     www      2927: # ----------------------------------------------------- Devalidate Spreadsheets
                   2928: 
                   2929: sub devalidate {
1.325     www      2930:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2931:     my $cid=$env{'request.course.id'}; 
1.109     www      2932:     if ($cid) {
1.391     matthew  2933:         # delete the stored spreadsheets for
                   2934:         # - the student level sheet of this user in course's homespace
                   2935:         # - the assessment level sheet for this resource 
                   2936:         #   for this user in user's homespace
1.553     albertel 2937: 	# - current conditional state info
1.325     www      2938: 	my $key=$uname.':'.$udom.':';
1.109     www      2939:         my $status=
1.299     matthew  2940: 	    &del('nohist_calculatedsheets',
1.391     matthew  2941: 		 [$key.'studentcalc:'],
1.620     albertel 2942: 		 $env{'course.'.$cid.'.domain'},
                   2943: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2944: 		.' '.
                   2945: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2946: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2947:         unless ($status eq 'ok ok') {
                   2948:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2949:                     $uname.' at '.$udom.' for '.
1.109     www      2950: 		    $symb.': '.$status);
1.133     albertel 2951:         }
1.553     albertel 2952: 	&delenv('user.state.'.$cid);
1.109     www      2953:     }
                   2954: }
                   2955: 
1.265     albertel 2956: sub get_scalar {
                   2957:     my ($string,$end) = @_;
                   2958:     my $value;
                   2959:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2960: 	$value = $1;
                   2961:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2962: 	$value = $1;
                   2963:     }
                   2964:     return &unescape($value);
                   2965: }
                   2966: 
                   2967: sub array2str {
                   2968:   my (@array) = @_;
                   2969:   my $result=&arrayref2str(\@array);
                   2970:   $result=~s/^__ARRAY_REF__//;
                   2971:   $result=~s/__END_ARRAY_REF__$//;
                   2972:   return $result;
                   2973: }
                   2974: 
1.204     albertel 2975: sub arrayref2str {
                   2976:   my ($arrayref) = @_;
1.265     albertel 2977:   my $result='__ARRAY_REF__';
1.204     albertel 2978:   foreach my $elem (@$arrayref) {
1.265     albertel 2979:     if(ref($elem) eq 'ARRAY') {
                   2980:       $result.=&arrayref2str($elem).'&';
                   2981:     } elsif(ref($elem) eq 'HASH') {
                   2982:       $result.=&hashref2str($elem).'&';
                   2983:     } elsif(ref($elem)) {
                   2984:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2985:     } else {
                   2986:       $result.=&escape($elem).'&';
                   2987:     }
                   2988:   }
                   2989:   $result=~s/\&$//;
1.265     albertel 2990:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2991:   return $result;
                   2992: }
                   2993: 
1.168     albertel 2994: sub hash2str {
1.204     albertel 2995:   my (%hash) = @_;
                   2996:   my $result=&hashref2str(\%hash);
1.265     albertel 2997:   $result=~s/^__HASH_REF__//;
                   2998:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2999:   return $result;
                   3000: }
                   3001: 
                   3002: sub hashref2str {
                   3003:   my ($hashref)=@_;
1.265     albertel 3004:   my $result='__HASH_REF__';
1.800     albertel 3005:   foreach my $key (sort(keys(%$hashref))) {
                   3006:     if (ref($key) eq 'ARRAY') {
                   3007:       $result.=&arrayref2str($key).'=';
                   3008:     } elsif (ref($key) eq 'HASH') {
                   3009:       $result.=&hashref2str($key).'=';
                   3010:     } elsif (ref($key)) {
1.265     albertel 3011:       $result.='=';
1.800     albertel 3012:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3013:     } else {
1.800     albertel 3014: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3015:     }
                   3016: 
1.800     albertel 3017:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3018:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3019:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3020:       $result.=&hashref2str($hashref->{$key}).'&';
                   3021:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3022:        $result.='&';
1.800     albertel 3023:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3024:     } else {
1.800     albertel 3025:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3026:     }
                   3027:   }
1.168     albertel 3028:   $result=~s/\&$//;
1.265     albertel 3029:   $result .= '__END_HASH_REF__';
1.168     albertel 3030:   return $result;
                   3031: }
                   3032: 
                   3033: sub str2hash {
1.265     albertel 3034:     my ($string)=@_;
                   3035:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3036:     return %$hash;
                   3037: }
                   3038: 
                   3039: sub str2hashref {
1.168     albertel 3040:   my ($string) = @_;
1.265     albertel 3041: 
                   3042:   my %hash;
                   3043: 
                   3044:   if($string !~ /^__HASH_REF__/) {
                   3045:       if (! ($string eq '' || !defined($string))) {
                   3046: 	  $hash{'error'}='Not hash reference';
                   3047:       }
                   3048:       return (\%hash, $string);
                   3049:   }
                   3050: 
                   3051:   $string =~ s/^__HASH_REF__//;
                   3052: 
                   3053:   while($string !~ /^__END_HASH_REF__/) {
                   3054:       #key
                   3055:       my $key='';
                   3056:       if($string =~ /^__HASH_REF__/) {
                   3057:           ($key, $string)=&str2hashref($string);
                   3058:           if(defined($key->{'error'})) {
                   3059:               $hash{'error'}='Bad data';
                   3060:               return (\%hash, $string);
                   3061:           }
                   3062:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3063:           ($key, $string)=&str2arrayref($string);
                   3064:           if($key->[0] eq 'Array reference error') {
                   3065:               $hash{'error'}='Bad data';
                   3066:               return (\%hash, $string);
                   3067:           }
                   3068:       } else {
                   3069:           $string =~ s/^(.*?)=//;
1.267     albertel 3070: 	  $key=&unescape($1);
1.265     albertel 3071:       }
                   3072:       $string =~ s/^=//;
                   3073: 
                   3074:       #value
                   3075:       my $value='';
                   3076:       if($string =~ /^__HASH_REF__/) {
                   3077:           ($value, $string)=&str2hashref($string);
                   3078:           if(defined($value->{'error'})) {
                   3079:               $hash{'error'}='Bad data';
                   3080:               return (\%hash, $string);
                   3081:           }
                   3082:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3083:           ($value, $string)=&str2arrayref($string);
                   3084:           if($value->[0] eq 'Array reference error') {
                   3085:               $hash{'error'}='Bad data';
                   3086:               return (\%hash, $string);
                   3087:           }
                   3088:       } else {
                   3089: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3090:       }
                   3091:       $string =~ s/^&//;
                   3092: 
                   3093:       $hash{$key}=$value;
1.204     albertel 3094:   }
1.265     albertel 3095: 
                   3096:   $string =~ s/^__END_HASH_REF__//;
                   3097: 
                   3098:   return (\%hash, $string);
1.204     albertel 3099: }
                   3100: 
                   3101: sub str2array {
1.265     albertel 3102:     my ($string)=@_;
                   3103:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3104:     return @$array;
                   3105: }
                   3106: 
                   3107: sub str2arrayref {
1.204     albertel 3108:   my ($string) = @_;
1.265     albertel 3109:   my @array;
                   3110: 
                   3111:   if($string !~ /^__ARRAY_REF__/) {
                   3112:       if (! ($string eq '' || !defined($string))) {
                   3113: 	  $array[0]='Array reference error';
                   3114:       }
                   3115:       return (\@array, $string);
                   3116:   }
                   3117: 
                   3118:   $string =~ s/^__ARRAY_REF__//;
                   3119: 
                   3120:   while($string !~ /^__END_ARRAY_REF__/) {
                   3121:       my $value='';
                   3122:       if($string =~ /^__HASH_REF__/) {
                   3123:           ($value, $string)=&str2hashref($string);
                   3124:           if(defined($value->{'error'})) {
                   3125:               $array[0] ='Array reference error';
                   3126:               return (\@array, $string);
                   3127:           }
                   3128:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3129:           ($value, $string)=&str2arrayref($string);
                   3130:           if($value->[0] eq 'Array reference error') {
                   3131:               $array[0] ='Array reference error';
                   3132:               return (\@array, $string);
                   3133:           }
                   3134:       } else {
                   3135: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3136:       }
                   3137:       $string =~ s/^&//;
                   3138: 
                   3139:       push(@array, $value);
1.191     harris41 3140:   }
1.265     albertel 3141: 
                   3142:   $string =~ s/^__END_ARRAY_REF__//;
                   3143: 
                   3144:   return (\@array, $string);
1.168     albertel 3145: }
                   3146: 
1.167     albertel 3147: # -------------------------------------------------------------------Temp Store
                   3148: 
1.168     albertel 3149: sub tmpreset {
                   3150:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3151:   if (!$symb) {
                   3152:     $symb=&symbread();
1.620     albertel 3153:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3154:   }
                   3155:   $symb=escape($symb);
                   3156: 
1.620     albertel 3157:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3158:   $namespace=~s/\//\_/g;
                   3159:   $namespace=~s/\W//g;
                   3160: 
1.620     albertel 3161:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3162:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3163:   if ($domain eq 'public' && $stuname eq 'public') {
                   3164:       $stuname=$ENV{'REMOTE_ADDR'};
                   3165:   }
1.168     albertel 3166:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3167:   my %hash;
                   3168:   if (tie(%hash,'GDBM_File',
                   3169: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3170: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3171:     foreach my $key (keys %hash) {
1.180     albertel 3172:       if ($key=~ /:$symb/) {
1.168     albertel 3173: 	delete($hash{$key});
                   3174:       }
                   3175:     }
                   3176:   }
                   3177: }
                   3178: 
1.167     albertel 3179: sub tmpstore {
1.168     albertel 3180:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3181: 
                   3182:   if (!$symb) {
                   3183:     $symb=&symbread();
1.620     albertel 3184:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3185:   }
                   3186:   $symb=escape($symb);
                   3187: 
                   3188:   if (!$namespace) {
                   3189:     # I don't think we would ever want to store this for a course.
                   3190:     # it seems this will only be used if we don't have a course.
1.620     albertel 3191:     #$namespace=$env{'request.course.id'};
1.168     albertel 3192:     #if (!$namespace) {
1.620     albertel 3193:       $namespace=$env{'request.state'};
1.168     albertel 3194:     #}
                   3195:   }
                   3196:   $namespace=~s/\//\_/g;
                   3197:   $namespace=~s/\W//g;
1.620     albertel 3198:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3199:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3200:   if ($domain eq 'public' && $stuname eq 'public') {
                   3201:       $stuname=$ENV{'REMOTE_ADDR'};
                   3202:   }
1.168     albertel 3203:   my $now=time;
                   3204:   my %hash;
                   3205:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3206:   if (tie(%hash,'GDBM_File',
                   3207: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3208: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3209:     $hash{"version:$symb"}++;
                   3210:     my $version=$hash{"version:$symb"};
                   3211:     my $allkeys=''; 
                   3212:     foreach my $key (keys(%$storehash)) {
                   3213:       $allkeys.=$key.':';
1.591     albertel 3214:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3215:     }
                   3216:     $hash{"$version:$symb:timestamp"}=$now;
                   3217:     $allkeys.='timestamp';
                   3218:     $hash{"$version:keys:$symb"}=$allkeys;
                   3219:     if (untie(%hash)) {
                   3220:       return 'ok';
                   3221:     } else {
                   3222:       return "error:$!";
                   3223:     }
                   3224:   } else {
                   3225:     return "error:$!";
                   3226:   }
                   3227: }
1.167     albertel 3228: 
1.168     albertel 3229: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3230: 
1.168     albertel 3231: sub tmprestore {
                   3232:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3233: 
1.168     albertel 3234:   if (!$symb) {
                   3235:     $symb=&symbread();
1.620     albertel 3236:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3237:   }
                   3238:   $symb=escape($symb);
                   3239: 
1.620     albertel 3240:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3241: 
1.620     albertel 3242:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3243:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3244:   if ($domain eq 'public' && $stuname eq 'public') {
                   3245:       $stuname=$ENV{'REMOTE_ADDR'};
                   3246:   }
1.168     albertel 3247:   my %returnhash;
                   3248:   $namespace=~s/\//\_/g;
                   3249:   $namespace=~s/\W//g;
                   3250:   my %hash;
                   3251:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3252:   if (tie(%hash,'GDBM_File',
                   3253: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3254: 	  &GDBM_READER(),0640)) {
1.168     albertel 3255:     my $version=$hash{"version:$symb"};
                   3256:     $returnhash{'version'}=$version;
                   3257:     my $scope;
                   3258:     for ($scope=1;$scope<=$version;$scope++) {
                   3259:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3260:       my @keys=split(/:/,$vkeys);
                   3261:       my $key;
                   3262:       $returnhash{"$scope:keys"}=$vkeys;
                   3263:       foreach $key (@keys) {
1.591     albertel 3264: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3265: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3266:       }
                   3267:     }
1.168     albertel 3268:     if (!(untie(%hash))) {
                   3269:       return "error:$!";
                   3270:     }
                   3271:   } else {
                   3272:     return "error:$!";
                   3273:   }
                   3274:   return %returnhash;
1.167     albertel 3275: }
                   3276: 
1.9       www      3277: # ----------------------------------------------------------------------- Store
                   3278: 
                   3279: sub store {
1.124     www      3280:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3281:     my $home='';
                   3282: 
1.168     albertel 3283:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3284: 
1.213     www      3285:     $symb=&symbclean($symb);
1.122     albertel 3286:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3287: 
1.620     albertel 3288:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3289:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3290: 
                   3291:     &devalidate($symb,$stuname,$domain);
1.109     www      3292: 
                   3293:     $symb=escape($symb);
1.187     www      3294:     if (!$namespace) { 
1.620     albertel 3295:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3296:           return ''; 
                   3297:        } 
                   3298:     }
1.620     albertel 3299:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3300: 
                   3301:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3302:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3303: 
1.12      www      3304:     my $namevalue='';
1.800     albertel 3305:     foreach my $key (keys(%$storehash)) {
                   3306:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3307:     }
1.12      www      3308:     $namevalue=~s/\&$//;
1.187     www      3309:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3310:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3311: }
                   3312: 
1.47      www      3313: # -------------------------------------------------------------- Critical Store
                   3314: 
                   3315: sub cstore {
1.124     www      3316:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3317:     my $home='';
                   3318: 
1.168     albertel 3319:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3320: 
1.213     www      3321:     $symb=&symbclean($symb);
1.122     albertel 3322:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3323: 
1.620     albertel 3324:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3325:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3326: 
                   3327:     &devalidate($symb,$stuname,$domain);
1.109     www      3328: 
                   3329:     $symb=escape($symb);
1.187     www      3330:     if (!$namespace) { 
1.620     albertel 3331:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3332:           return ''; 
                   3333:        } 
                   3334:     }
1.620     albertel 3335:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3336: 
                   3337:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3338:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3339: 
1.47      www      3340:     my $namevalue='';
1.800     albertel 3341:     foreach my $key (keys(%$storehash)) {
                   3342:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3343:     }
1.47      www      3344:     $namevalue=~s/\&$//;
1.187     www      3345:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3346:     return critical
                   3347:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3348: }
                   3349: 
1.9       www      3350: # --------------------------------------------------------------------- Restore
                   3351: 
                   3352: sub restore {
1.124     www      3353:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3354:     my $home='';
                   3355: 
1.168     albertel 3356:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3357: 
1.122     albertel 3358:     if (!$symb) {
                   3359:       unless ($symb=escape(&symbread())) { return ''; }
                   3360:     } else {
1.213     www      3361:       $symb=&escape(&symbclean($symb));
1.122     albertel 3362:     }
1.188     www      3363:     if (!$namespace) { 
1.620     albertel 3364:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3365:           return ''; 
                   3366:        } 
                   3367:     }
1.620     albertel 3368:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3369:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3370:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3371:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3372: 
1.12      www      3373:     my %returnhash=();
1.800     albertel 3374:     foreach my $line (split(/\&/,$answer)) {
                   3375: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3376:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3377:     }
1.75      www      3378:     my $version;
                   3379:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3380:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3381:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3382:        }
1.75      www      3383:     }
1.13      www      3384:     return %returnhash;
1.34      www      3385: }
                   3386: 
                   3387: # ---------------------------------------------------------- Course Description
                   3388: 
                   3389: sub coursedescription {
1.731     albertel 3390:     my ($courseid,$args)=@_;
1.34      www      3391:     $courseid=~s/^\///;
1.49      www      3392:     $courseid=~s/\_/\//g;
1.34      www      3393:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3394:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3395:     my $normalid=$cdomain.'_'.$cnum;
                   3396:     # need to always cache even if we get errors otherwise we keep 
                   3397:     # trying and trying and trying to get the course description.
                   3398:     my %envhash=();
                   3399:     my %returnhash=();
1.731     albertel 3400:     
                   3401:     my $expiretime=600;
                   3402:     if ($env{'request.course.id'} eq $normalid) {
                   3403: 	$expiretime=120;
                   3404:     }
                   3405: 
                   3406:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3407:     if (!$args->{'freshen_cache'}
                   3408: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3409: 	foreach my $key (keys(%env)) {
                   3410: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3411: 	    my ($setting) = $1;
                   3412: 	    $returnhash{$setting} = $env{$key};
                   3413: 	}
                   3414: 	return %returnhash;
                   3415:     }
                   3416: 
                   3417:     # get the data agin
                   3418:     if (!$args->{'one_time'}) {
                   3419: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3420:     }
1.811     albertel 3421: 
1.34      www      3422:     if ($chome ne 'no_host') {
1.302     albertel 3423:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3424:        if (!exists($returnhash{'con_lost'})) {
                   3425:            $returnhash{'home'}= $chome;
                   3426: 	   $returnhash{'domain'} = $cdomain;
                   3427: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3428:            if (!defined($returnhash{'type'})) {
                   3429:                $returnhash{'type'} = 'Course';
                   3430:            }
1.130     albertel 3431:            while (my ($name,$value) = each %returnhash) {
1.53      www      3432:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3433:            }
1.270     www      3434:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3435:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3436: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3437:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3438:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3439:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3440:        }
                   3441:     }
1.731     albertel 3442:     if (!$args->{'one_time'}) {
1.949     raeburn  3443: 	&appenv(\%envhash);
1.731     albertel 3444:     }
1.302     albertel 3445:     return %returnhash;
1.461     www      3446: }
                   3447: 
                   3448: # -------------------------------------------------See if a user is privileged
                   3449: 
                   3450: sub privileged {
                   3451:     my ($username,$domain)=@_;
                   3452:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3453: 			&homeserver($username,$domain));
                   3454:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3455:     my $now=time;
                   3456:     if ($rolesdump ne '') {
1.800     albertel 3457:         foreach my $entry (split(/&/,$rolesdump)) {
                   3458: 	    if ($entry!~/^rolesdef_/) {
                   3459: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3460: 		$area=~s/\_\w\w$//;
                   3461: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3462: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3463: 		    my $active=1;
                   3464: 		    if ($tend) {
                   3465: 			if ($tend<$now) { $active=0; }
                   3466: 		    }
                   3467: 		    if ($tstart) {
                   3468: 			if ($tstart>$now) { $active=0; }
                   3469: 		    }
                   3470: 		    if ($active) { return 1; }
                   3471: 		}
                   3472: 	    }
                   3473: 	}
                   3474:     }
                   3475:     return 0;
1.9       www      3476: }
1.1       albertel 3477: 
1.103     harris41 3478: # -------------------------------------------------------- Get user privileges
1.11      www      3479: 
                   3480: sub rolesinit {
                   3481:     my ($domain,$username,$authhost)=@_;
                   3482:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3483:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3484:     my %allroles=();
1.678     raeburn  3485:     my %allgroups=();   
1.11      www      3486:     my $now=time;
1.743     albertel 3487:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3488:     my $group_privs;
1.11      www      3489: 
                   3490:     if ($rolesdump ne '') {
1.800     albertel 3491:         foreach my $entry (split(/&/,$rolesdump)) {
                   3492: 	  if ($entry!~/^rolesdef_/) {
                   3493:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3494: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3495:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3496: 	    if ($role=~/^cr/) { 
1.807     albertel 3497: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3498: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3499: 		    ($tend,$tstart)=split('_',$trest);
                   3500: 		} else {
                   3501: 		    $trole=$role;
                   3502: 		}
1.678     raeburn  3503:             } elsif ($role =~ m|^gr/|) {
                   3504:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3505:                 ($trole,$group_privs) = split(/\//,$trole);
                   3506:                 $group_privs = &unescape($group_privs);
1.587     albertel 3507: 	    } else {
                   3508: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3509: 	    }
1.743     albertel 3510: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3511: 					 $username);
                   3512: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3513:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3514:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3515:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3516: 		my $spec=$trole.'.'.$area;
                   3517: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3518: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3519:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3520:                 } elsif ($trole eq 'gr') {
                   3521:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3522: 		} else {
1.567     raeburn  3523:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3524: 		}
1.12      www      3525:             }
1.662     raeburn  3526:           }
1.191     harris41 3527:         }
1.743     albertel 3528:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3529:         $userroles{'user.adv'}    = $adv;
                   3530: 	$userroles{'user.author'} = $author;
1.620     albertel 3531:         $env{'user.adv'}=$adv;
1.11      www      3532:     }
1.743     albertel 3533:     return \%userroles;  
1.11      www      3534: }
                   3535: 
1.567     raeburn  3536: sub set_arearole {
                   3537:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3538: # log the associated role with the area
                   3539:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3540:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3541: }
                   3542: 
                   3543: sub custom_roleprivs {
                   3544:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3545:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3546:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3547:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3548:         my ($rdummy,$roledef)=
                   3549:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3550:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3551:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3552:             if (defined($syspriv)) {
                   3553:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3554:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3555:             }
                   3556:             if ($tdomain ne '') {
                   3557:                 if (defined($dompriv)) {
                   3558:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3559:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3560:                 }
                   3561:                 if (($trest ne '') && (defined($coursepriv))) {
                   3562:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3563:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3564:                 }
                   3565:             }
                   3566:         }
                   3567:     }
                   3568: }
                   3569: 
1.678     raeburn  3570: sub group_roleprivs {
                   3571:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3572:     my $access = 1;
                   3573:     my $now = time;
                   3574:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3575:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3576:     if ($access) {
1.811     albertel 3577:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3578:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3579:     }
                   3580: }
1.567     raeburn  3581: 
                   3582: sub standard_roleprivs {
                   3583:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3584:     if (defined($pr{$trole.':s'})) {
                   3585:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3586:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3587:     }
                   3588:     if ($tdomain ne '') {
                   3589:         if (defined($pr{$trole.':d'})) {
                   3590:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3591:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3592:         }
                   3593:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3594:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3595:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3596:         }
                   3597:     }
                   3598: }
                   3599: 
                   3600: sub set_userprivs {
1.678     raeburn  3601:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3602:     my $author=0;
                   3603:     my $adv=0;
1.678     raeburn  3604:     my %grouproles = ();
                   3605:     if (keys(%{$allgroups}) > 0) {
                   3606:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3607:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3608:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3609:                 $trole = $1;
                   3610:                 $area = $2;
1.681     raeburn  3611:                 $sec = $3;
                   3612:                 $extendedarea = $area.$sec;
                   3613:                 if (exists($$allgroups{$area})) {
                   3614:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3615:                         my $spec = $trole.'.'.$extendedarea;
                   3616:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3617:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3618:                     }
                   3619:                 }
                   3620:             }
                   3621:         }
                   3622:     }
1.800     albertel 3623:     foreach my $group (keys(%grouproles)) {
                   3624:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3625:     }
1.800     albertel 3626:     foreach my $role (keys(%{$allroles})) {
                   3627:         my %thesepriv;
1.941     raeburn  3628:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3629:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3630:             if ($item ne '') {
                   3631:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3632:                 if ($restrictions eq '') {
                   3633:                     $thesepriv{$privilege}='F';
                   3634:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3635:                     $thesepriv{$privilege}.=$restrictions;
                   3636:                 }
                   3637:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3638:             }
                   3639:         }
                   3640:         my $thesestr='';
1.800     albertel 3641:         foreach my $priv (keys(%thesepriv)) {
                   3642: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3643: 	}
                   3644:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3645:     }
                   3646:     return ($author,$adv);
                   3647: }
                   3648: 
1.12      www      3649: # --------------------------------------------------------------- get interface
                   3650: 
                   3651: sub get {
1.131     albertel 3652:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3653:    my $items='';
1.800     albertel 3654:    foreach my $item (@$storearr) {
                   3655:        $items.=&escape($item).'&';
1.191     harris41 3656:    }
1.12      www      3657:    $items=~s/\&$//;
1.620     albertel 3658:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3659:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3660:    my $uhome=&homeserver($uname,$udomain);
                   3661: 
1.133     albertel 3662:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3663:    my @pairs=split(/\&/,$rep);
1.273     albertel 3664:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3665:      return @pairs;
                   3666:    }
1.15      www      3667:    my %returnhash=();
1.42      www      3668:    my $i=0;
1.800     albertel 3669:    foreach my $item (@$storearr) {
                   3670:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3671:       $i++;
1.191     harris41 3672:    }
1.15      www      3673:    return %returnhash;
1.27      www      3674: }
                   3675: 
                   3676: # --------------------------------------------------------------- del interface
                   3677: 
                   3678: sub del {
1.133     albertel 3679:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3680:    my $items='';
1.800     albertel 3681:    foreach my $item (@$storearr) {
                   3682:        $items.=&escape($item).'&';
1.191     harris41 3683:    }
1.27      www      3684:    $items=~s/\&$//;
1.620     albertel 3685:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3686:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3687:    my $uhome=&homeserver($uname,$udomain);
                   3688: 
                   3689:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3690: }
                   3691: 
                   3692: # -------------------------------------------------------------- dump interface
                   3693: 
                   3694: sub dump {
1.755     albertel 3695:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3696:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3697:     if (!$uname) { $uname=$env{'user.name'}; }
                   3698:     my $uhome=&homeserver($uname,$udomain);
                   3699:     if ($regexp) {
                   3700: 	$regexp=&escape($regexp);
                   3701:     } else {
                   3702: 	$regexp='.';
                   3703:     }
                   3704:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3705:     my @pairs=split(/\&/,$rep);
                   3706:     my %returnhash=();
                   3707:     foreach my $item (@pairs) {
                   3708: 	my ($key,$value)=split(/=/,$item,2);
                   3709: 	$key = &unescape($key);
                   3710: 	next if ($key =~ /^error: 2 /);
                   3711: 	$returnhash{$key}=&thaw_unescape($value);
                   3712:     }
                   3713:     return %returnhash;
1.407     www      3714: }
                   3715: 
1.717     albertel 3716: # --------------------------------------------------------- dumpstore interface
                   3717: 
                   3718: sub dumpstore {
                   3719:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3720:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3721:    if (!$uname) { $uname=$env{'user.name'}; }
                   3722:    my $uhome=&homeserver($uname,$udomain);
                   3723:    if ($regexp) {
                   3724:        $regexp=&escape($regexp);
                   3725:    } else {
                   3726:        $regexp='.';
                   3727:    }
                   3728:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3729:    my @pairs=split(/\&/,$rep);
                   3730:    my %returnhash=();
                   3731:    foreach my $item (@pairs) {
                   3732:        my ($key,$value)=split(/=/,$item,2);
                   3733:        next if ($key =~ /^error: 2 /);
                   3734:        $returnhash{$key}=&thaw_unescape($value);
                   3735:    }
                   3736:    return %returnhash;
1.717     albertel 3737: }
                   3738: 
1.407     www      3739: # -------------------------------------------------------------- keys interface
                   3740: 
                   3741: sub getkeys {
                   3742:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3743:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3744:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3745:    my $uhome=&homeserver($uname,$udomain);
                   3746:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3747:    my @keyarray=();
1.800     albertel 3748:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3749:       next if ($key =~ /^error: 2 /);
1.800     albertel 3750:       push(@keyarray,&unescape($key));
1.407     www      3751:    }
                   3752:    return @keyarray;
1.318     matthew  3753: }
                   3754: 
1.319     matthew  3755: # --------------------------------------------------------------- currentdump
                   3756: sub currentdump {
1.328     matthew  3757:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3758:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3759:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3760:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3761:    my $uhome = &homeserver($sname,$sdom);
                   3762:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3763:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3764:    #
1.318     matthew  3765:    my %returnhash=();
1.319     matthew  3766:    #
                   3767:    if ($rep eq "unknown_cmd") { 
                   3768:        # an old lond will not know currentdump
                   3769:        # Do a dump and make it look like a currentdump
1.822     albertel 3770:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3771:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3772:        my %hash = @tmp;
                   3773:        @tmp=();
1.424     matthew  3774:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3775:    } else {
                   3776:        my @pairs=split(/\&/,$rep);
1.800     albertel 3777:        foreach my $pair (@pairs) {
                   3778:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3779:            my ($symb,$param) = split(/:/,$key);
                   3780:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3781:                                                         &thaw_unescape($value);
1.319     matthew  3782:        }
1.191     harris41 3783:    }
1.12      www      3784:    return %returnhash;
1.424     matthew  3785: }
                   3786: 
                   3787: sub convert_dump_to_currentdump{
                   3788:     my %hash = %{shift()};
                   3789:     my %returnhash;
                   3790:     # Code ripped from lond, essentially.  The only difference
                   3791:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3792:     # we might run in to problems with parameter names =~ /^v\./
                   3793:     while (my ($key,$value) = each(%hash)) {
                   3794:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3795: 	$symb  = &unescape($symb);
                   3796: 	$param = &unescape($param);
1.424     matthew  3797:         next if ($v eq 'version' || $symb eq 'keys');
                   3798:         next if (exists($returnhash{$symb}) &&
                   3799:                  exists($returnhash{$symb}->{$param}) &&
                   3800:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3801:         $returnhash{$symb}->{$param}=$value;
                   3802:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3803:     }
                   3804:     #
                   3805:     # Remove all of the keys in the hashes which keep track of
                   3806:     # the version of the parameter.
                   3807:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3808:         # use a foreach because we are going to delete from the hash.
                   3809:         foreach my $key (keys(%$param_hash)) {
                   3810:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3811:         }
                   3812:     }
                   3813:     return \%returnhash;
1.12      www      3814: }
                   3815: 
1.627     albertel 3816: # ------------------------------------------------------ critical inc interface
                   3817: 
                   3818: sub cinc {
                   3819:     return &inc(@_,'critical');
                   3820: }
                   3821: 
1.449     matthew  3822: # --------------------------------------------------------------- inc interface
                   3823: 
                   3824: sub inc {
1.627     albertel 3825:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3826:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3827:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3828:     my $uhome=&homeserver($uname,$udomain);
                   3829:     my $items='';
                   3830:     if (! ref($store)) {
                   3831:         # got a single value, so use that instead
                   3832:         $items = &escape($store).'=&';
                   3833:     } elsif (ref($store) eq 'SCALAR') {
                   3834:         $items = &escape($$store).'=&';        
                   3835:     } elsif (ref($store) eq 'ARRAY') {
                   3836:         $items = join('=&',map {&escape($_);} @{$store});
                   3837:     } elsif (ref($store) eq 'HASH') {
                   3838:         while (my($key,$value) = each(%{$store})) {
                   3839:             $items.= &escape($key).'='.&escape($value).'&';
                   3840:         }
                   3841:     }
                   3842:     $items=~s/\&$//;
1.627     albertel 3843:     if ($critical) {
                   3844: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3845:     } else {
                   3846: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3847:     }
1.449     matthew  3848: }
                   3849: 
1.12      www      3850: # --------------------------------------------------------------- put interface
                   3851: 
                   3852: sub put {
1.134     albertel 3853:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3855:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3856:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3857:    my $items='';
1.800     albertel 3858:    foreach my $item (keys(%$storehash)) {
                   3859:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3860:    }
1.12      www      3861:    $items=~s/\&$//;
1.134     albertel 3862:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3863: }
                   3864: 
1.631     albertel 3865: # ------------------------------------------------------------ newput interface
                   3866: 
                   3867: sub newput {
                   3868:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3869:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3870:    if (!$uname) { $uname=$env{'user.name'}; }
                   3871:    my $uhome=&homeserver($uname,$udomain);
                   3872:    my $items='';
                   3873:    foreach my $key (keys(%$storehash)) {
                   3874:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3875:    }
                   3876:    $items=~s/\&$//;
                   3877:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3878: }
                   3879: 
                   3880: # ---------------------------------------------------------  putstore interface
                   3881: 
1.524     raeburn  3882: sub putstore {
1.715     albertel 3883:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3884:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3885:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3886:    my $uhome=&homeserver($uname,$udomain);
                   3887:    my $items='';
1.715     albertel 3888:    foreach my $key (keys(%$storehash)) {
                   3889:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3890:    }
1.715     albertel 3891:    $items=~s/\&$//;
1.716     albertel 3892:    my $esc_symb=&escape($symb);
                   3893:    my $esc_v=&escape($version);
1.715     albertel 3894:    my $reply =
1.716     albertel 3895:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3896: 	      $uhome);
                   3897:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3898:        # gfall back to way things use to be done
1.715     albertel 3899:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3900: 			    $uname);
1.524     raeburn  3901:    }
1.715     albertel 3902:    return $reply;
                   3903: }
                   3904: 
                   3905: sub old_putstore {
1.716     albertel 3906:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3907:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3908:     if (!$uname) { $uname=$env{'user.name'}; }
                   3909:     my $uhome=&homeserver($uname,$udomain);
                   3910:     my %newstorehash;
1.800     albertel 3911:     foreach my $item (keys(%$storehash)) {
                   3912: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3913: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3914:     }
                   3915:     my $items='';
                   3916:     my %allitems = ();
1.800     albertel 3917:     foreach my $item (keys(%newstorehash)) {
                   3918: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3919: 	    my $key = $1.':keys:'.$2;
                   3920: 	    $allitems{$key} .= $3.':';
                   3921: 	}
1.800     albertel 3922: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3923:     }
1.800     albertel 3924:     foreach my $item (keys(%allitems)) {
                   3925: 	$allitems{$item} =~ s/\:$//;
                   3926: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3927:     }
                   3928:     $items=~s/\&$//;
                   3929:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3930: }
                   3931: 
1.47      www      3932: # ------------------------------------------------------ critical put interface
                   3933: 
                   3934: sub cput {
1.134     albertel 3935:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3936:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3937:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3938:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3939:    my $items='';
1.800     albertel 3940:    foreach my $item (keys(%$storehash)) {
                   3941:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3942:    }
1.47      www      3943:    $items=~s/\&$//;
1.134     albertel 3944:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3945: }
                   3946: 
                   3947: # -------------------------------------------------------------- eget interface
                   3948: 
                   3949: sub eget {
1.133     albertel 3950:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3951:    my $items='';
1.800     albertel 3952:    foreach my $item (@$storearr) {
                   3953:        $items.=&escape($item).'&';
1.191     harris41 3954:    }
1.12      www      3955:    $items=~s/\&$//;
1.620     albertel 3956:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3957:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3958:    my $uhome=&homeserver($uname,$udomain);
                   3959:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3960:    my @pairs=split(/\&/,$rep);
                   3961:    my %returnhash=();
1.42      www      3962:    my $i=0;
1.800     albertel 3963:    foreach my $item (@$storearr) {
                   3964:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3965:       $i++;
1.191     harris41 3966:    }
1.12      www      3967:    return %returnhash;
                   3968: }
                   3969: 
1.667     albertel 3970: # ------------------------------------------------------------ tmpput interface
                   3971: sub tmpput {
1.802     raeburn  3972:     my ($storehash,$server,$context)=@_;
1.667     albertel 3973:     my $items='';
1.800     albertel 3974:     foreach my $item (keys(%$storehash)) {
                   3975: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3976:     }
                   3977:     $items=~s/\&$//;
1.802     raeburn  3978:     if (defined($context)) {
                   3979:         $items .= ':'.&escape($context);
                   3980:     }
1.667     albertel 3981:     return &reply("tmpput:$items",$server);
                   3982: }
                   3983: 
                   3984: # ------------------------------------------------------------ tmpget interface
                   3985: sub tmpget {
1.688     albertel 3986:     my ($token,$server)=@_;
                   3987:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3988:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3989:     my %returnhash;
                   3990:     foreach my $item (split(/\&/,$rep)) {
                   3991: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  3992:         next if ($key =~ /^error: 2 /);
1.667     albertel 3993: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3994:     }
                   3995:     return %returnhash;
                   3996: }
                   3997: 
1.688     albertel 3998: # ------------------------------------------------------------ tmpget interface
                   3999: sub tmpdel {
                   4000:     my ($token,$server)=@_;
                   4001:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4002:     return &reply("tmpdel:$token",$server);
                   4003: }
                   4004: 
1.765     albertel 4005: # -------------------------------------------------- portfolio access checking
                   4006: 
                   4007: sub portfolio_access {
1.766     albertel 4008:     my ($requrl) = @_;
1.765     albertel 4009:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4010:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4011:     if ($result) {
                   4012:         my %setters;
                   4013:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4014:             my ($startblock,$endblock) =
                   4015:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4016:             if ($startblock && $endblock) {
                   4017:                 return 'B';
                   4018:             }
                   4019:         } else {
                   4020:             my ($startblock,$endblock) =
                   4021:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4022:             if ($startblock && $endblock) {
                   4023:                 return 'B';
                   4024:             }
                   4025:         }
                   4026:     }
1.765     albertel 4027:     if ($result eq 'ok') {
1.766     albertel 4028:        return 'F';
1.765     albertel 4029:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4030:        return 'A';
1.765     albertel 4031:     }
1.766     albertel 4032:     return '';
1.765     albertel 4033: }
                   4034: 
                   4035: sub get_portfolio_access {
1.767     albertel 4036:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4037: 
                   4038:     if (!ref($access_hash)) {
                   4039: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4040: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4041: 						   $file_name);
                   4042: 	$access_hash = $access_controls{$file_name};
                   4043:     }
                   4044: 
1.765     albertel 4045:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4046:     my $now = time;
                   4047:     if (ref($access_hash) eq 'HASH') {
                   4048:         foreach my $key (keys(%{$access_hash})) {
                   4049:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4050:             if ($start > $now) {
                   4051:                 next;
                   4052:             }
                   4053:             if ($end && $end<$now) {
                   4054:                 next;
                   4055:             }
                   4056:             if ($scope eq 'public') {
                   4057:                 $public = $key;
                   4058:                 last;
                   4059:             } elsif ($scope eq 'guest') {
                   4060:                 $guest = $key;
                   4061:             } elsif ($scope eq 'domains') {
                   4062:                 push(@domains,$key);
                   4063:             } elsif ($scope eq 'users') {
                   4064:                 push(@users,$key);
                   4065:             } elsif ($scope eq 'course') {
                   4066:                 push(@courses,$key);
                   4067:             } elsif ($scope eq 'group') {
                   4068:                 push(@groups,$key);
                   4069:             }
                   4070:         }
                   4071:         if ($public) {
                   4072:             return 'ok';
                   4073:         }
                   4074:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4075:             if ($guest) {
                   4076:                 return $guest;
                   4077:             }
                   4078:         } else {
                   4079:             if (@domains > 0) {
                   4080:                 foreach my $domkey (@domains) {
                   4081:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4082:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4083:                             return 'ok';
                   4084:                         }
                   4085:                     }
                   4086:                 }
                   4087:             }
                   4088:             if (@users > 0) {
                   4089:                 foreach my $userkey (@users) {
1.865     raeburn  4090:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4091:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4092:                             if (ref($item) eq 'HASH') {
                   4093:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4094:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4095:                                     return 'ok';
                   4096:                                 }
                   4097:                             }
                   4098:                         }
                   4099:                     } 
1.765     albertel 4100:                 }
                   4101:             }
                   4102:             my %roleshash;
                   4103:             my @courses_and_groups = @courses;
                   4104:             push(@courses_and_groups,@groups); 
                   4105:             if (@courses_and_groups > 0) {
                   4106:                 my (%allgroups,%allroles); 
                   4107:                 my ($start,$end,$role,$sec,$group);
                   4108:                 foreach my $envkey (%env) {
1.811     albertel 4109:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4110:                         my $cid = $2.'_'.$3; 
                   4111:                         if ($1 eq 'gr') {
                   4112:                             $group = $4;
                   4113:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4114:                         } else {
                   4115:                             if ($4 eq '') {
                   4116:                                 $sec = 'none';
                   4117:                             } else {
                   4118:                                 $sec = $4;
                   4119:                             }
                   4120:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4121:                         }
1.811     albertel 4122:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4123:                         my $cid = $2.'_'.$3;
                   4124:                         if ($4 eq '') {
                   4125:                             $sec = 'none';
                   4126:                         } else {
                   4127:                             $sec = $4;
                   4128:                         }
                   4129:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4130:                     }
                   4131:                 }
                   4132:                 if (keys(%allroles) == 0) {
                   4133:                     return;
                   4134:                 }
                   4135:                 foreach my $key (@courses_and_groups) {
                   4136:                     my %content = %{$$access_hash{$key}};
                   4137:                     my $cnum = $content{'number'};
                   4138:                     my $cdom = $content{'domain'};
                   4139:                     my $cid = $cdom.'_'.$cnum;
                   4140:                     if (!exists($allroles{$cid})) {
                   4141:                         next;
                   4142:                     }    
                   4143:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4144:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4145:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4146:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4147:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4148:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4149:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4150:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4151:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4152:                                         if (grep/^all$/,@sections) {
                   4153:                                             return 'ok';
                   4154:                                         } else {
                   4155:                                             if (grep/^$sec$/,@sections) {
                   4156:                                                 return 'ok';
                   4157:                                             }
                   4158:                                         }
                   4159:                                     }
                   4160:                                 }
                   4161:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4162:                                     if (grep/^none$/,@groups) {
                   4163:                                         return 'ok';
                   4164:                                     }
                   4165:                                 } else {
                   4166:                                     if (grep/^all$/,@groups) {
                   4167:                                         return 'ok';
                   4168:                                     } 
                   4169:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4170:                                         if (grep/^$group$/,@groups) {
                   4171:                                             return 'ok';
                   4172:                                         }
                   4173:                                     }
                   4174:                                 } 
                   4175:                             }
                   4176:                         }
                   4177:                     }
                   4178:                 }
                   4179:             }
                   4180:             if ($guest) {
                   4181:                 return $guest;
                   4182:             }
                   4183:         }
                   4184:     }
                   4185:     return;
                   4186: }
                   4187: 
                   4188: sub course_group_datechecker {
                   4189:     my ($dates,$now,$status) = @_;
                   4190:     my ($start,$end) = split(/\./,$dates);
                   4191:     if (!$start && !$end) {
                   4192:         return 'ok';
                   4193:     }
                   4194:     if (grep/^active$/,@{$status}) {
                   4195:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4196:             return 'ok';
                   4197:         }
                   4198:     }
                   4199:     if (grep/^previous$/,@{$status}) {
                   4200:         if ($end > $now ) {
                   4201:             return 'ok';
                   4202:         }
                   4203:     }
                   4204:     if (grep/^future$/,@{$status}) {
                   4205:         if ($start > $now) {
                   4206:             return 'ok';
                   4207:         }
                   4208:     }
                   4209:     return; 
                   4210: }
                   4211: 
                   4212: sub parse_portfolio_url {
                   4213:     my ($url) = @_;
                   4214: 
                   4215:     my ($type,$udom,$unum,$group,$file_name);
                   4216:     
1.823     albertel 4217:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4218: 	$type = 1;
                   4219:         $udom = $1;
                   4220:         $unum = $2;
                   4221:         $file_name = $3;
1.823     albertel 4222:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4223: 	$type = 2;
                   4224:         $udom = $1;
                   4225:         $unum = $2;
                   4226:         $group = $3;
                   4227:         $file_name = $3.'/'.$4;
                   4228:     }
                   4229:     if (wantarray) {
                   4230: 	return ($type,$udom,$unum,$file_name,$group);
                   4231:     }
                   4232:     return $type;
                   4233: }
                   4234: 
                   4235: sub is_portfolio_url {
                   4236:     my ($url) = @_;
                   4237:     return scalar(&parse_portfolio_url($url));
                   4238: }
                   4239: 
1.798     raeburn  4240: sub is_portfolio_file {
                   4241:     my ($file) = @_;
1.820     raeburn  4242:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4243:         return 1;
                   4244:     }
                   4245:     return;
                   4246: }
                   4247: 
                   4248: 
1.341     www      4249: # ---------------------------------------------- Custom access rule evaluation
                   4250: 
                   4251: sub customaccess {
                   4252:     my ($priv,$uri)=@_;
1.807     albertel 4253:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4254:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4255:     $udom = &LONCAPA::clean_domain($udom);
                   4256:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4257:     my $access=0;
1.800     albertel 4258:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4259: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4260: 	if ($type eq 'user') {
                   4261: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4262: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4263: 		if ($tdom) {
                   4264: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4265: 		}
1.896     albertel 4266: 		if ($tuname) {
                   4267: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4268: 		}
                   4269: 		$access=($effect eq 'allow');
                   4270: 		last;
                   4271: 	    }
                   4272: 	} else {
                   4273: 	    if ($role) {
                   4274: 		if ($role ne $urole) { next; }
                   4275: 	    }
                   4276: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4277: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4278: 		if ($tdom) {
                   4279: 		    if ($tdom ne $udom) { next; }
                   4280: 		}
                   4281: 		if ($tcrs) {
                   4282: 		    if ($tcrs ne $ucrs) { next; }
                   4283: 		}
                   4284: 		if ($tsec) {
                   4285: 		    if ($tsec ne $usec) { next; }
                   4286: 		}
                   4287: 		$access=($effect eq 'allow');
                   4288: 		last;
                   4289: 	    }
                   4290: 	    if ($realm eq '' && $role eq '') {
                   4291: 		$access=($effect eq 'allow');
                   4292: 	    }
1.402     bowersj2 4293: 	}
1.341     www      4294:     }
                   4295:     return $access;
                   4296: }
                   4297: 
1.103     harris41 4298: # ------------------------------------------------- Check for a user privilege
1.12      www      4299: 
                   4300: sub allowed {
1.810     raeburn  4301:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4302:     my $ver_orguri=$uri;
1.439     www      4303:     $uri=&deversion($uri);
1.152     www      4304:     my $orguri=$uri;
1.52      www      4305:     $uri=&declutter($uri);
1.809     raeburn  4306: 
1.810     raeburn  4307:     if ($priv eq 'evb') {
                   4308: # Evade communication block restrictions for specified role in a course
                   4309:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4310:             return $1;
                   4311:         } else {
                   4312:             return;
                   4313:         }
                   4314:     }
                   4315: 
1.620     albertel 4316:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4317: # Free bre access to adm and meta resources
1.775     albertel 4318:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4319: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4320: 	&& ($priv eq 'bre')) {
1.14      www      4321: 	return 'F';
1.159     www      4322:     }
                   4323: 
1.545     banghart 4324: # Free bre access to user's own portfolio contents
1.714     raeburn  4325:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4326:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4327: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4328:         my %setters;
                   4329:         my ($startblock,$endblock) = 
                   4330:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4331:         if ($startblock && $endblock) {
                   4332:             return 'B';
                   4333:         } else {
                   4334:             return 'F';
                   4335:         }
1.545     banghart 4336:     }
                   4337: 
1.762     raeburn  4338: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4339:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4340:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4341:         if (exists($env{'request.course.id'})) {
                   4342:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4343:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4344:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4345:                 my $courseprivid=$env{'request.course.id'};
                   4346:                 $courseprivid=~s/\_/\//;
                   4347:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4348:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4349:                     return $1; 
1.762     raeburn  4350:                 } else {
                   4351:                     if ($env{'request.course.sec'}) {
                   4352:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4353:                     }
                   4354:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4355:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4356:                         return $2;
                   4357:                     }
1.714     raeburn  4358:                 }
                   4359:             }
                   4360:         }
                   4361:     }
                   4362: 
1.159     www      4363: # Free bre to public access
                   4364: 
                   4365:     if ($priv eq 'bre') {
1.238     www      4366:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4367: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4368:            return 'F'; 
                   4369:         }
1.238     www      4370:         if ($copyright eq 'priv') {
                   4371:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4372: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4373: 		return '';
                   4374:             }
                   4375:         }
                   4376:         if ($copyright eq 'domain') {
                   4377:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4378: 	    unless (($env{'user.domain'} eq $1) ||
                   4379:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4380: 		return '';
                   4381:             }
1.262     matthew  4382:         }
1.620     albertel 4383:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4384:             # Library role, so allow browsing of resources in this domain.
                   4385:             return 'F';
1.238     www      4386:         }
1.341     www      4387:         if ($copyright eq 'custom') {
                   4388: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4389:         }
1.14      www      4390:     }
1.264     matthew  4391:     # Domain coordinator is trying to create a course
1.620     albertel 4392:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4393:         # uri is the requested domain in this case.
                   4394:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4395:         # a role of dc for the domain in question.
1.620     albertel 4396:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4397:     }
1.29      www      4398: 
1.52      www      4399:     my $thisallowed='';
                   4400:     my $statecond=0;
                   4401:     my $courseprivid='';
                   4402: 
                   4403: # Course
                   4404: 
1.620     albertel 4405:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4406:        $thisallowed.=$1;
                   4407:     }
1.29      www      4408: 
1.52      www      4409: # Domain
                   4410: 
1.620     albertel 4411:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4412:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4413:        $thisallowed.=$1;
                   4414:     }
1.52      www      4415: 
                   4416: # Course: uri itself is a course
1.66      www      4417:     my $courseuri=$uri;
                   4418:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4419:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4420: 
1.620     albertel 4421:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4422:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4423:        $thisallowed.=$1;
                   4424:     }
1.29      www      4425: 
1.665     albertel 4426: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4427: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4428:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4429: 	$thisallowed='';
1.671     raeburn  4430:         my ($match)=&is_on_map($uri);
                   4431:         if ($match) {
                   4432:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4433:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4434:                 $thisallowed.=$1;
                   4435:             }
                   4436:         } else {
1.705     albertel 4437:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4438:             if ($refuri) {
                   4439:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4440:                     $thisallowed='F';
1.671     raeburn  4441:                 } else {
                   4442:                     $refuri=&declutter($refuri);
                   4443:                     my ($match) = &is_on_map($refuri);
                   4444:                     if ($match) {
                   4445:                         $thisallowed='F';
                   4446:                     }
1.669     raeburn  4447:                 }
1.671     raeburn  4448:             }
                   4449:         }
1.314     www      4450:     }
1.492     albertel 4451: 
1.766     albertel 4452:     if ($priv eq 'bre'
                   4453: 	&& $thisallowed ne 'F' 
                   4454: 	&& $thisallowed ne '2'
                   4455: 	&& &is_portfolio_url($uri)) {
                   4456: 	$thisallowed = &portfolio_access($uri);
                   4457:     }
                   4458:     
1.52      www      4459: # Full access at system, domain or course-wide level? Exit.
1.29      www      4460: 
                   4461:     if ($thisallowed=~/F/) {
                   4462: 	return 'F';
                   4463:     }
                   4464: 
1.52      www      4465: # If this is generating or modifying users, exit with special codes
1.29      www      4466: 
1.643     www      4467:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4468: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4469: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4470: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4471: 	    unless ($auname) { return $thisallowed; }
                   4472: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4473: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4474: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4475: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4476: 	}
1.52      www      4477: 	return $thisallowed;
                   4478:     }
                   4479: #
1.103     harris41 4480: # Gathered so far: system, domain and course wide privileges
1.52      www      4481: #
                   4482: # Course: See if uri or referer is an individual resource that is part of 
                   4483: # the course
                   4484: 
1.620     albertel 4485:     if ($env{'request.course.id'}) {
1.232     www      4486: 
1.620     albertel 4487:        $courseprivid=$env{'request.course.id'};
                   4488:        if ($env{'request.course.sec'}) {
                   4489:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4490:        }
                   4491:        $courseprivid=~s/\_/\//;
                   4492:        my $checkreferer=1;
1.232     www      4493:        my ($match,$cond)=&is_on_map($uri);
                   4494:        if ($match) {
                   4495:            $statecond=$cond;
1.620     albertel 4496:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4497:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4498:                $thisallowed.=$1;
                   4499:                $checkreferer=0;
                   4500:            }
1.29      www      4501:        }
1.83      www      4502:        
1.148     www      4503:        if ($checkreferer) {
1.620     albertel 4504: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4505:             unless ($refuri) {
1.800     albertel 4506:                 foreach my $key (keys(%env)) {
                   4507: 		    if ($key=~/^httpref\..*\*/) {
                   4508: 			my $pattern=$key;
1.156     www      4509:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4510:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4511:                         $pattern=~s/\//\\\//g;
1.152     www      4512:                         if ($orguri=~/$pattern/) {
1.800     albertel 4513: 			    $refuri=$env{$key};
1.148     www      4514:                         }
                   4515:                     }
1.191     harris41 4516:                 }
1.148     www      4517:             }
1.232     www      4518: 
1.148     www      4519:          if ($refuri) { 
1.152     www      4520: 	  $refuri=&declutter($refuri);
1.232     www      4521:           my ($match,$cond)=&is_on_map($refuri);
                   4522:             if ($match) {
                   4523:               my $refstatecond=$cond;
1.620     albertel 4524:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4525:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4526:                   $thisallowed.=$1;
1.53      www      4527:                   $uri=$refuri;
                   4528:                   $statecond=$refstatecond;
1.52      www      4529:               }
                   4530:           }
1.148     www      4531:         }
1.29      www      4532:        }
1.52      www      4533:    }
1.29      www      4534: 
1.52      www      4535: #
1.103     harris41 4536: # Gathered now: all privileges that could apply, and condition number
1.52      www      4537: # 
                   4538: #
                   4539: # Full or no access?
                   4540: #
1.29      www      4541: 
1.52      www      4542:     if ($thisallowed=~/F/) {
                   4543: 	return 'F';
                   4544:     }
1.29      www      4545: 
1.52      www      4546:     unless ($thisallowed) {
                   4547:         return '';
                   4548:     }
1.29      www      4549: 
1.52      www      4550: # Restrictions exist, deal with them
                   4551: #
                   4552: #   C:according to course preferences
                   4553: #   R:according to resource settings
                   4554: #   L:unless locked
                   4555: #   X:according to user session state
                   4556: #
                   4557: 
                   4558: # Possibly locked functionality, check all courses
1.54      www      4559: # Locks might take effect only after 10 minutes cache expiration for other
                   4560: # courses, and 2 minutes for current course
1.52      www      4561: 
                   4562:     my $envkey;
                   4563:     if ($thisallowed=~/L/) {
1.620     albertel 4564:         foreach $envkey (keys %env) {
1.54      www      4565:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4566:                my $courseid=$2;
                   4567:                my $roleid=$1.'.'.$2;
1.92      www      4568:                $courseid=~s/^\///;
1.54      www      4569:                my $expiretime=600;
1.620     albertel 4570:                if ($env{'request.role'} eq $roleid) {
1.54      www      4571: 		  $expiretime=120;
                   4572:                }
                   4573: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4574:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4575:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4576: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4577:                }
1.620     albertel 4578:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4579:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4580: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4581:                        &log($env{'user.domain'},$env{'user.name'},
                   4582:                             $env{'user.home'},
1.57      www      4583:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4584:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4585:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4586: 		       return '';
                   4587:                    }
                   4588:                }
1.620     albertel 4589:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4590:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4591: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4592:                        &log($env{'user.domain'},$env{'user.name'},
                   4593:                             $env{'user.home'},
1.57      www      4594:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4595:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4596:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4597: 		       return '';
                   4598:                    }
                   4599:                }
                   4600: 	   }
1.29      www      4601:        }
1.52      www      4602:     }
                   4603:    
                   4604: #
                   4605: # Rest of the restrictions depend on selected course
                   4606: #
                   4607: 
1.620     albertel 4608:     unless ($env{'request.course.id'}) {
1.766     albertel 4609: 	if ($thisallowed eq 'A') {
                   4610: 	    return 'A';
1.814     raeburn  4611:         } elsif ($thisallowed eq 'B') {
                   4612:             return 'B';
1.766     albertel 4613: 	} else {
                   4614: 	    return '1';
                   4615: 	}
1.52      www      4616:     }
1.29      www      4617: 
1.52      www      4618: #
                   4619: # Now user is definitely in a course
                   4620: #
1.53      www      4621: 
                   4622: 
                   4623: # Course preferences
                   4624: 
                   4625:    if ($thisallowed=~/C/) {
1.620     albertel 4626:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4627:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4628:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4629: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4630: 	   if ($priv ne 'pch') { 
                   4631: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4632: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4633: 			$env{'request.course.id'});
                   4634: 	   }
1.237     www      4635:            return '';
                   4636:        }
                   4637: 
1.620     albertel 4638:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4639: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4640: 	   if ($priv ne 'pch') { 
                   4641: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4642: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4643: 			$env{'request.course.id'});
                   4644: 	   }
1.54      www      4645:            return '';
                   4646:        }
1.53      www      4647:    }
                   4648: 
                   4649: # Resource preferences
                   4650: 
                   4651:    if ($thisallowed=~/R/) {
1.620     albertel 4652:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4653:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4654: 	   if ($priv ne 'pch') { 
                   4655: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4656: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4657: 	   }
                   4658: 	   return '';
1.54      www      4659:        }
1.53      www      4660:    }
1.30      www      4661: 
1.246     www      4662: # Restricted by state or randomout?
1.30      www      4663: 
1.52      www      4664:    if ($thisallowed=~/X/) {
1.620     albertel 4665:       if ($env{'acc.randomout'}) {
1.579     albertel 4666: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4667:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4668:             return ''; 
                   4669:          }
1.247     www      4670:       }
                   4671:       if (&condval($statecond)) {
1.52      www      4672: 	 return '2';
                   4673:       } else {
                   4674:          return '';
                   4675:       }
                   4676:    }
1.30      www      4677: 
1.766     albertel 4678:     if ($thisallowed eq 'A') {
                   4679: 	return 'A';
1.814     raeburn  4680:     } elsif ($thisallowed eq 'B') {
                   4681:         return 'B';
1.766     albertel 4682:     }
1.52      www      4683:    return 'F';
1.232     www      4684: }
                   4685: 
1.710     albertel 4686: sub split_uri_for_cond {
                   4687:     my $uri=&deversion(&declutter(shift));
                   4688:     my @uriparts=split(/\//,$uri);
                   4689:     my $filename=pop(@uriparts);
                   4690:     my $pathname=join('/',@uriparts);
                   4691:     return ($pathname,$filename);
                   4692: }
1.232     www      4693: # --------------------------------------------------- Is a resource on the map?
                   4694: 
                   4695: sub is_on_map {
1.710     albertel 4696:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4697:     #Trying to find the conditional for the file
1.620     albertel 4698:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4699: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4700:     if ($match) {
1.289     bowersj2 4701: 	return (1,$1);
                   4702:     } else {
1.434     www      4703: 	return (0,0);
1.289     bowersj2 4704:     }
1.12      www      4705: }
                   4706: 
1.427     www      4707: # --------------------------------------------------------- Get symb from alias
                   4708: 
                   4709: sub get_symb_from_alias {
                   4710:     my $symb=shift;
                   4711:     my ($map,$resid,$url)=&decode_symb($symb);
                   4712: # Already is a symb
                   4713:     if ($url) { return $symb; }
                   4714: # Must be an alias
                   4715:     my $aliassymb='';
                   4716:     my %bighash;
1.620     albertel 4717:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4718:                             &GDBM_READER(),0640)) {
                   4719:         my $rid=$bighash{'mapalias_'.$symb};
                   4720: 	if ($rid) {
                   4721: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4722: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4723: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4724: 	}
                   4725:         untie %bighash;
                   4726:     }
                   4727:     return $aliassymb;
                   4728: }
                   4729: 
1.12      www      4730: # ----------------------------------------------------------------- Define Role
                   4731: 
                   4732: sub definerole {
                   4733:   if (allowed('mcr','/')) {
                   4734:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4735:     foreach my $role (split(':',$sysrole)) {
                   4736: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4737:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4738:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4739: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4740:                return "refused:s:$crole&$cqual"; 
                   4741:             }
                   4742:         }
1.191     harris41 4743:     }
1.800     albertel 4744:     foreach my $role (split(':',$domrole)) {
                   4745: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4746:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4747:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4748: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4749:                return "refused:d:$crole&$cqual"; 
                   4750:             }
                   4751:         }
1.191     harris41 4752:     }
1.800     albertel 4753:     foreach my $role (split(':',$courole)) {
                   4754: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4755:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4756:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4757: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4758:                return "refused:c:$crole&$cqual"; 
                   4759:             }
                   4760:         }
1.191     harris41 4761:     }
1.620     albertel 4762:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4763:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4764: 	        "rolesdef_$rolename=".
                   4765:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4766:     return reply($command,$env{'user.home'});
1.12      www      4767:   } else {
                   4768:     return 'refused';
                   4769:   }
1.105     harris41 4770: }
                   4771: 
                   4772: # ---------------- Make a metadata query against the network of library servers
                   4773: 
                   4774: sub metadata_query {
1.244     matthew  4775:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4776:     my %rhash;
1.845     albertel 4777:     my %libserv = &all_library();
1.244     matthew  4778:     my @server_list = (defined($server_array) ? @$server_array
                   4779:                                               : keys(%libserv) );
                   4780:     for my $server (@server_list) {
1.118     harris41 4781: 	unless ($custom or $customshow) {
                   4782: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4783: 	    $rhash{$server}=$reply;
                   4784: 	}
                   4785: 	else {
                   4786: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4787: 			     &escape($custom).':'.&escape($customshow),
                   4788: 			     $server);
                   4789: 	    $rhash{$server}=$reply;
                   4790: 	}
1.112     harris41 4791:     }
1.118     harris41 4792:     return \%rhash;
1.240     www      4793: }
                   4794: 
                   4795: # ----------------------------------------- Send log queries and wait for reply
                   4796: 
                   4797: sub log_query {
                   4798:     my ($uname,$udom,$query,%filters)=@_;
                   4799:     my $uhome=&homeserver($uname,$udom);
                   4800:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4801:     my $uhost=&hostname($uhome);
1.800     albertel 4802:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4803:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4804:                        $uhome);
1.479     albertel 4805:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4806:     return get_query_reply($queryid);
                   4807: }
                   4808: 
1.818     raeburn  4809: # -------------------------- Update MySQL table for portfolio file
                   4810: 
                   4811: sub update_portfolio_table {
1.821     raeburn  4812:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4813:     my $homeserver = &homeserver($uname,$udom);
                   4814:     my $queryid=
1.821     raeburn  4815:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4816:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4817:     my $reply = &get_query_reply($queryid);
                   4818:     return $reply;
                   4819: }
                   4820: 
1.899     raeburn  4821: # -------------------------- Update MySQL allusers table
                   4822: 
                   4823: sub update_allusers_table {
                   4824:     my ($uname,$udom,$names) = @_;
                   4825:     my $homeserver = &homeserver($uname,$udom);
                   4826:     my $queryid=
                   4827:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4828:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4829:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4830:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4831:                'generation='.&escape($names->{'generation'}).'%%'.
                   4832:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4833:                'id='.&escape($names->{'id'}),$homeserver);
                   4834:     my $reply = &get_query_reply($queryid);
                   4835:     return $reply;
                   4836: }
                   4837: 
1.508     raeburn  4838: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4839: 
                   4840: sub fetch_enrollment_query {
1.511     raeburn  4841:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4842:     my $homeserver;
1.547     raeburn  4843:     my $maxtries = 1;
1.508     raeburn  4844:     if ($context eq 'automated') {
                   4845:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4846:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4847:     } else {
                   4848:         $homeserver = &homeserver($cnum,$dom);
                   4849:     }
1.838     albertel 4850:     my $host=&hostname($homeserver);
1.506     raeburn  4851:     my $cmd = '';
1.800     albertel 4852:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4853:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4854:     }
                   4855:     $cmd =~ s/%%$//;
                   4856:     $cmd = &escape($cmd);
                   4857:     my $query = 'fetchenrollment';
1.620     albertel 4858:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4859:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4860:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4861:         return 'error: '.$queryid;
                   4862:     }
1.506     raeburn  4863:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4864:     my $tries = 1;
                   4865:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4866:         $reply = &get_query_reply($queryid);
                   4867:         $tries ++;
                   4868:     }
1.526     raeburn  4869:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4870:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4871:     } else {
1.901     albertel 4872:         my @responses = split(/:/,$reply);
1.515     raeburn  4873:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4874:             foreach my $line (@responses) {
                   4875:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4876:                 $$replyref{$key} = $value;
                   4877:             }
                   4878:         } else {
1.506     raeburn  4879:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4880:             foreach my $line (@responses) {
                   4881:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4882:                 $$replyref{$key} = $value;
                   4883:                 if ($value > 0) {
1.800     albertel 4884:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4885:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4886:                         my $destname = $pathname.'/'.$filename;
                   4887:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4888:                         if ($xml_classlist =~ /^error/) {
                   4889:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4890:                         } else {
1.506     raeburn  4891:                             if ( open(FILE,">$destname") ) {
                   4892:                                 print FILE &unescape($xml_classlist);
                   4893:                                 close(FILE);
1.526     raeburn  4894:                             } else {
                   4895:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4896:                             }
                   4897:                         }
                   4898:                     }
                   4899:                 }
                   4900:             }
                   4901:         }
                   4902:         return 'ok';
                   4903:     }
                   4904:     return 'error';
                   4905: }
                   4906: 
1.242     www      4907: sub get_query_reply {
                   4908:     my $queryid=shift;
1.240     www      4909:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4910:     my $reply='';
                   4911:     for (1..100) {
                   4912: 	sleep 2;
                   4913:         if (-e $replyfile.'.end') {
1.448     albertel 4914: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4915: 		$reply = join('',<$fh>);
                   4916: 		close($fh);
1.240     www      4917: 	   } else { return 'error: reply_file_error'; }
1.242     www      4918:            return &unescape($reply);
                   4919: 	}
1.240     www      4920:     }
1.242     www      4921:     return 'timeout:'.$queryid;
1.240     www      4922: }
                   4923: 
                   4924: sub courselog_query {
1.241     www      4925: #
                   4926: # possible filters:
                   4927: # url: url or symb
                   4928: # username
                   4929: # domain
                   4930: # action: view, submit, grade
                   4931: # start: timestamp
                   4932: # end: timestamp
                   4933: #
1.240     www      4934:     my (%filters)=@_;
1.620     albertel 4935:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4936:     if ($filters{'url'}) {
                   4937: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4938:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4939:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4940:     }
1.620     albertel 4941:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4942:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4943:     return &log_query($cname,$cdom,'courselog',%filters);
                   4944: }
                   4945: 
                   4946: sub userlog_query {
1.858     raeburn  4947: #
                   4948: # possible filters:
                   4949: # action: log check role
                   4950: # start: timestamp
                   4951: # end: timestamp
                   4952: #
1.240     www      4953:     my ($uname,$udom,%filters)=@_;
                   4954:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4955: }
                   4956: 
1.506     raeburn  4957: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4958: 
                   4959: sub auto_run {
1.508     raeburn  4960:     my ($cnum,$cdom) = @_;
1.876     raeburn  4961:     my $response = 0;
                   4962:     my $settings;
                   4963:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4964:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4965:         $settings = $domconfig{'autoenroll'};
                   4966:         if ($settings->{'run'} eq '1') {
                   4967:             $response = 1;
                   4968:         }
                   4969:     } else {
1.934     raeburn  4970:         my $homeserver;
                   4971:         if (&is_course($cdom,$cnum)) {
                   4972:             $homeserver = &homeserver($cnum,$cdom);
                   4973:         } else {
                   4974:             $homeserver = &domain($cdom,'primary');
                   4975:         }
                   4976:         if ($homeserver ne 'no_host') {
                   4977:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4978:         }
1.876     raeburn  4979:     }
1.506     raeburn  4980:     return $response;
                   4981: }
1.776     albertel 4982: 
1.506     raeburn  4983: sub auto_get_sections {
1.508     raeburn  4984:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4985:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4986:     my @secs = ();
1.511     raeburn  4987:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4988:     unless ($response eq 'refused') {
1.901     albertel 4989:         @secs = split(/:/,$response);
1.506     raeburn  4990:     }
                   4991:     return @secs;
                   4992: }
1.776     albertel 4993: 
1.506     raeburn  4994: sub auto_new_course {
1.508     raeburn  4995:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4996:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4997:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4998:     return $response;
                   4999: }
1.776     albertel 5000: 
1.506     raeburn  5001: sub auto_validate_courseID {
1.508     raeburn  5002:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5003:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5004:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5005:     return $response;
                   5006: }
1.776     albertel 5007: 
1.506     raeburn  5008: sub auto_create_password {
1.873     raeburn  5009:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5010:     my ($homeserver,$response);
1.506     raeburn  5011:     my $create_passwd = 0;
                   5012:     my $authchk = '';
1.873     raeburn  5013:     if ($udom =~ /^$match_domain$/) {
                   5014:         $homeserver = &domain($udom,'primary');
                   5015:     }
                   5016:     if ($homeserver eq '') {
                   5017:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5018:             $homeserver = &homeserver($cnum,$cdom);
                   5019:         }
                   5020:     }
                   5021:     if ($homeserver eq '') {
                   5022:         $authchk = 'nodomain';
1.506     raeburn  5023:     } else {
1.873     raeburn  5024:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5025:         if ($response eq 'refused') {
                   5026:             $authchk = 'refused';
                   5027:         } else {
1.901     albertel 5028:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5029:         }
1.506     raeburn  5030:     }
                   5031:     return ($authparam,$create_passwd,$authchk);
                   5032: }
                   5033: 
1.706     raeburn  5034: sub auto_photo_permission {
                   5035:     my ($cnum,$cdom,$students) = @_;
                   5036:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5037:     my ($outcome,$perm_reqd,$conditions) = 
                   5038: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5039:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5040: 	return (undef,undef);
                   5041:     }
1.706     raeburn  5042:     return ($outcome,$perm_reqd,$conditions);
                   5043: }
                   5044: 
                   5045: sub auto_checkphotos {
                   5046:     my ($uname,$udom,$pid) = @_;
                   5047:     my $homeserver = &homeserver($uname,$udom);
                   5048:     my ($result,$resulttype);
                   5049:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5050: 				   &escape($uname).':'.&escape($pid),
                   5051: 				   $homeserver));
1.709     albertel 5052:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5053: 	return (undef,undef);
                   5054:     }
1.706     raeburn  5055:     if ($outcome) {
                   5056:         ($result,$resulttype) = split(/:/,$outcome);
                   5057:     } 
                   5058:     return ($result,$resulttype);
                   5059: }
                   5060: 
                   5061: sub auto_photochoice {
                   5062:     my ($cnum,$cdom) = @_;
                   5063:     my $homeserver = &homeserver($cnum,$cdom);
                   5064:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5065: 						       &escape($cdom),
                   5066: 						       $homeserver)));
1.709     albertel 5067:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5068: 	return (undef,undef);
                   5069:     }
1.706     raeburn  5070:     return ($update,$comment);
                   5071: }
                   5072: 
                   5073: sub auto_photoupdate {
                   5074:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5075:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5076:     my $host=&hostname($homeserver);
1.706     raeburn  5077:     my $cmd = '';
                   5078:     my $maxtries = 1;
1.800     albertel 5079:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5080:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5081:     }
                   5082:     $cmd =~ s/%%$//;
                   5083:     $cmd = &escape($cmd);
                   5084:     my $query = 'institutionalphotos';
                   5085:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5086:     unless ($queryid=~/^\Q$host\E\_/) {
                   5087:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5088:         return 'error: '.$queryid;
                   5089:     }
                   5090:     my $reply = &get_query_reply($queryid);
                   5091:     my $tries = 1;
                   5092:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5093:         $reply = &get_query_reply($queryid);
                   5094:         $tries ++;
                   5095:     }
                   5096:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5097:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5098:     } else {
                   5099:         my @responses = split(/:/,$reply);
                   5100:         my $outcome = shift(@responses); 
                   5101:         foreach my $item (@responses) {
                   5102:             my ($key,$value) = split(/=/,$item);
                   5103:             $$photo{$key} = $value;
                   5104:         }
                   5105:         return $outcome;
                   5106:     }
                   5107:     return 'error';
                   5108: }
                   5109: 
1.521     raeburn  5110: sub auto_instcode_format {
1.793     albertel 5111:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5112: 	$cat_order) = @_;
1.521     raeburn  5113:     my $courses = '';
1.772     raeburn  5114:     my @homeservers;
1.521     raeburn  5115:     if ($caller eq 'global') {
1.841     albertel 5116: 	my %servers = &get_servers($codedom,'library');
                   5117: 	foreach my $tryserver (keys(%servers)) {
                   5118: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5119: 		push(@homeservers,$tryserver);
                   5120: 	    }
1.584     raeburn  5121:         }
1.521     raeburn  5122:     } else {
1.772     raeburn  5123:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5124:     }
1.793     albertel 5125:     foreach my $code (keys(%{$instcodes})) {
                   5126:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5127:     }
                   5128:     chop($courses);
1.772     raeburn  5129:     my $ok_response = 0;
                   5130:     my $response;
                   5131:     while (@homeservers > 0 && $ok_response == 0) {
                   5132:         my $server = shift(@homeservers); 
                   5133:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5134:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5135:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5136: 		split(/:/,$response);
1.772     raeburn  5137:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5138:             push(@{$codetitles},&str2array($codetitles_str));
                   5139:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5140:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5141:             $ok_response = 1;
                   5142:         }
                   5143:     }
                   5144:     if ($ok_response) {
1.521     raeburn  5145:         return 'ok';
1.772     raeburn  5146:     } else {
                   5147:         return $response;
1.521     raeburn  5148:     }
                   5149: }
                   5150: 
1.792     raeburn  5151: sub auto_instcode_defaults {
                   5152:     my ($domain,$returnhash,$code_order) = @_;
                   5153:     my @homeservers;
1.841     albertel 5154: 
                   5155:     my %servers = &get_servers($domain,'library');
                   5156:     foreach my $tryserver (keys(%servers)) {
                   5157: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5158: 	    push(@homeservers,$tryserver);
                   5159: 	}
1.792     raeburn  5160:     }
1.841     albertel 5161: 
1.792     raeburn  5162:     my $response;
1.841     albertel 5163:     foreach my $server (@homeservers) {
1.792     raeburn  5164:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5165:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5166: 	
                   5167: 	foreach my $pair (split(/\&/,$response)) {
                   5168: 	    my ($name,$value)=split(/\=/,$pair);
                   5169: 	    if ($name eq 'code_order') {
                   5170: 		@{$code_order} = split(/\&/,&unescape($value));
                   5171: 	    } else {
                   5172: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5173: 	    }
                   5174: 	}
                   5175: 	return 'ok';
1.792     raeburn  5176:     }
1.841     albertel 5177: 
                   5178:     return $response;
1.792     raeburn  5179: } 
                   5180: 
1.777     albertel 5181: sub auto_validate_class_sec {
1.918     raeburn  5182:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5183:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5184:     my $ownerlist;
                   5185:     if (ref($owners) eq 'ARRAY') {
                   5186:         $ownerlist = join(',',@{$owners});
                   5187:     } else {
                   5188:         $ownerlist = $owners;
                   5189:     }
1.773     raeburn  5190:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5191:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5192:     return $response;
                   5193: }
                   5194: 
1.679     raeburn  5195: # ------------------------------------------------------- Course Group routines
                   5196: 
                   5197: sub get_coursegroups {
1.809     raeburn  5198:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5199:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5200: }
                   5201: 
1.679     raeburn  5202: sub modify_coursegroup {
                   5203:     my ($cdom,$cnum,$groupsettings) = @_;
                   5204:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5205: }
                   5206: 
1.809     raeburn  5207: sub toggle_coursegroup_status {
                   5208:     my ($cdom,$cnum,$group,$action) = @_;
                   5209:     my ($from_namespace,$to_namespace);
                   5210:     if ($action eq 'delete') {
                   5211:         $from_namespace = 'coursegroups';
                   5212:         $to_namespace = 'deleted_groups';
                   5213:     } else {
                   5214:         $from_namespace = 'deleted_groups';
                   5215:         $to_namespace = 'coursegroups';
                   5216:     }
                   5217:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5218:     if (my $tmp = &error(%curr_group)) {
                   5219:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5220:         return ('read error',$tmp);
                   5221:     } else {
                   5222:         my %savedsettings = %curr_group; 
1.809     raeburn  5223:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5224:         my $deloutcome;
                   5225:         if ($result eq 'ok') {
1.809     raeburn  5226:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5227:         } else {
                   5228:             return ('write error',$result);
                   5229:         }
                   5230:         if ($deloutcome eq 'ok') {
                   5231:             return 'ok';
                   5232:         } else {
                   5233:             return ('delete error',$deloutcome);
                   5234:         }
                   5235:     }
                   5236: }
                   5237: 
1.679     raeburn  5238: sub modify_group_roles {
                   5239:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5240:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5241:     my $role = 'gr/'.&escape($userprivs);
                   5242:     my ($uname,$udom) = split(/:/,$user);
                   5243:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5244:     if ($result eq 'ok') {
                   5245:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5246:     }
1.679     raeburn  5247:     return $result;
                   5248: }
                   5249: 
                   5250: sub modify_coursegroup_membership {
                   5251:     my ($cdom,$cnum,$membership) = @_;
                   5252:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5253:     return $result;
                   5254: }
                   5255: 
1.682     raeburn  5256: sub get_active_groups {
                   5257:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5258:     my $now = time;
                   5259:     my %groups = ();
                   5260:     foreach my $key (keys(%env)) {
1.811     albertel 5261:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5262:             my ($start,$end) = split(/\./,$env{$key});
                   5263:             if (($end!=0) && ($end<$now)) { next; }
                   5264:             if (($start!=0) && ($start>$now)) { next; }
                   5265:             if ($1 eq $cdom && $2 eq $cnum) {
                   5266:                 $groups{$3} = $env{$key} ;
                   5267:             }
                   5268:         }
                   5269:     }
                   5270:     return %groups;
                   5271: }
                   5272: 
1.683     raeburn  5273: sub get_group_membership {
                   5274:     my ($cdom,$cnum,$group) = @_;
                   5275:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5276: }
                   5277: 
                   5278: sub get_users_groups {
                   5279:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5280:     my @usersgroups;
1.683     raeburn  5281:     my $cachetime=1800;
                   5282: 
                   5283:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5284:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5285:     if (defined($cached)) {
1.734     albertel 5286:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5287:     } else {  
                   5288:         $grouplist = '';
1.816     raeburn  5289:         my $courseurl = &courseid_to_courseurl($courseid);
                   5290:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5291:         my $access_end = $env{'course.'.$courseid.
                   5292:                               '.default_enrollment_end_date'};
                   5293:         my $now = time;
                   5294:         foreach my $key (keys(%roleshash)) {
                   5295:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5296:                 my $group = $1;
                   5297:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5298:                     my $start = $2;
                   5299:                     my $end = $1;
                   5300:                     if ($start == -1) { next; } # deleted from group
                   5301:                     if (($start!=0) && ($start>$now)) { next; }
                   5302:                     if (($end!=0) && ($end<$now)) {
                   5303:                         if ($access_end && $access_end < $now) {
                   5304:                             if ($access_end - $end < 86400) {
                   5305:                                 push(@usersgroups,$group);
1.733     raeburn  5306:                             }
                   5307:                         }
1.817     raeburn  5308:                         next;
1.733     raeburn  5309:                     }
1.817     raeburn  5310:                     push(@usersgroups,$group);
1.683     raeburn  5311:                 }
                   5312:             }
                   5313:         }
1.817     raeburn  5314:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5315:         $grouplist = join(':',@usersgroups);
                   5316:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5317:     }
1.733     raeburn  5318:     return @usersgroups;
1.683     raeburn  5319: }
                   5320: 
                   5321: sub devalidate_getgroups_cache {
                   5322:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5323:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5324: 
1.683     raeburn  5325:     my $hashid="$udom:$uname:$courseid";
                   5326:     &devalidate_cache_new('getgroups',$hashid);
                   5327: }
                   5328: 
1.12      www      5329: # ------------------------------------------------------------------ Plain Text
                   5330: 
                   5331: sub plaintext {
1.742     raeburn  5332:     my ($short,$type,$cid) = @_;
1.758     albertel 5333:     if ($short =~ /^cr/) {
                   5334: 	return (split('/',$short))[-1];
                   5335:     }
1.742     raeburn  5336:     if (!defined($cid)) {
                   5337:         $cid = $env{'request.course.id'};
                   5338:     }
                   5339:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5340:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5341:                                           '.plaintext'});
                   5342:     }
                   5343:     my %rolenames = (
                   5344:                       Course => 'std',
                   5345:                       Group => 'alt1',
                   5346:                     );
                   5347:     if (defined($type) && 
                   5348:          defined($rolenames{$type}) && 
                   5349:          defined($prp{$short}{$rolenames{$type}})) {
                   5350:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5351:     } else {
                   5352:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5353:     }
1.12      www      5354: }
                   5355: 
                   5356: # ----------------------------------------------------------------- Assign Role
                   5357: 
                   5358: sub assignrole {
1.947     raeburn  5359:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
1.21      www      5360:     my $mrole;
                   5361:     if ($role =~ /^cr\//) {
1.393     www      5362:         my $cwosec=$url;
1.811     albertel 5363:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5364: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5365:            &logthis('Refused custom assignrole: '.
                   5366:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5367: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5368:            return 'refused'; 
                   5369:         }
1.21      www      5370:         $mrole='cr';
1.678     raeburn  5371:     } elsif ($role =~ /^gr\//) {
                   5372:         my $cwogrp=$url;
1.811     albertel 5373:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5374:         unless (&allowed('mdg',$cwogrp)) {
                   5375:             &logthis('Refused group assignrole: '.
                   5376:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5377:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5378:             return 'refused';
                   5379:         }
                   5380:         $mrole='gr';
1.21      www      5381:     } else {
1.82      www      5382:         my $cwosec=$url;
1.811     albertel 5383:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5384:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5385:             my $refused;
                   5386:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5387:                 if (!(&allowed('c'.$role,$url))) {
                   5388:                     $refused = 1;
                   5389:                 }
                   5390:             } else {
                   5391:                 $refused = 1;
                   5392:             }
1.947     raeburn  5393:             if ($refused) {
                   5394:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5395:                     $refused = '';
                   5396:                 } else {
                   5397:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5398:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5399: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5400:                     return 'refused';
                   5401:                 }
1.932     raeburn  5402:             }
1.104     www      5403:         }
1.21      www      5404:         $mrole=$role;
                   5405:     }
1.620     albertel 5406:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5407:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5408:     if ($end) { $command.='_'.$end; }
1.21      www      5409:     if ($start) {
                   5410: 	if ($end) { 
1.81      www      5411:            $command.='_'.$start; 
1.21      www      5412:         } else {
1.81      www      5413:            $command.='_0_'.$start;
1.21      www      5414:         }
                   5415:     }
1.739     raeburn  5416:     my $origstart = $start;
                   5417:     my $origend = $end;
1.357     www      5418: # actually delete
                   5419:     if ($deleteflag) {
1.373     www      5420: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5421: # modify command to delete the role
1.620     albertel 5422:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5423:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5424: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5425: # set start and finish to negative values for userrolelog
                   5426:            $start=-1;
                   5427:            $end=-1;
                   5428:         }
                   5429:     }
                   5430: # send command
1.349     www      5431:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5432: # log new user role if status is ok
1.349     www      5433:     if ($answer eq 'ok') {
1.663     raeburn  5434: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5435: # for course roles, perform group memberships changes triggered by role change.
                   5436:         unless ($role =~ /^gr/) {
                   5437:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5438:                                              $origstart);
                   5439:         }
1.349     www      5440:     }
                   5441:     return $answer;
1.169     harris41 5442: }
                   5443: 
                   5444: # -------------------------------------------------- Modify user authentication
1.197     www      5445: # Overrides without validation
                   5446: 
1.169     harris41 5447: sub modifyuserauth {
                   5448:     my ($udom,$uname,$umode,$upass)=@_;
                   5449:     my $uhome=&homeserver($uname,$udom);
1.197     www      5450:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5451:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5452:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5453:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5454:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5455: 		     &escape($upass),$uhome);
1.620     albertel 5456:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5457:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5458:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5459:     &log($udom,,$uname,$uhome,
1.620     albertel 5460:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5461:                                      $env{'user.name'}.', '.$umode.
1.197     www      5462:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5463:     unless ($reply eq 'ok') {
1.197     www      5464:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5465: 	return 'error: '.$reply;
                   5466:     }   
1.170     harris41 5467:     return 'ok';
1.80      www      5468: }
                   5469: 
1.81      www      5470: # --------------------------------------------------------------- Modify a user
1.80      www      5471: 
1.81      www      5472: sub modifyuser {
1.206     matthew  5473:     my ($udom,    $uname, $uid,
                   5474:         $umode,   $upass, $first,
                   5475:         $middle,  $last,  $gene,
1.387     www      5476:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5477:     $udom= &LONCAPA::clean_domain($udom);
                   5478:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5479:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5480:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5481: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5482:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5483:                                      ' desiredhome not specified'). 
1.620     albertel 5484:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5485:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5486:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5487: # ----------------------------------------------------------------- Create User
1.406     albertel 5488:     if (($uhome eq 'no_host') && 
                   5489: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5490:         my $unhome='';
1.844     albertel 5491:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5492:             $unhome = $desiredhome;
1.620     albertel 5493: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5494: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5495:         } else { # load balancing routine for determining $unhome
1.81      www      5496:             my $loadm=10000000;
1.841     albertel 5497: 	    my %servers = &get_servers($udom,'library');
                   5498: 	    foreach my $tryserver (keys(%servers)) {
                   5499: 		my $answer=reply('load',$tryserver);
                   5500: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5501: 		    $loadm=$answer;
                   5502: 		    $unhome=$tryserver;
                   5503: 		}
1.80      www      5504: 	    }
                   5505:         }
                   5506:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5507: 	    return 'error: unable to find a home server for '.$uname.
                   5508:                    ' in domain '.$udom;
1.80      www      5509:         }
                   5510:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5511:                          &escape($upass),$unhome);
                   5512: 	unless ($reply eq 'ok') {
                   5513:             return 'error: '.$reply;
                   5514:         }   
1.230     stredwic 5515:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5516:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5517: 	    return 'error: unable verify users home machine.';
1.80      www      5518:         }
1.209     matthew  5519:     }   # End of creation of new user
1.80      www      5520: # ---------------------------------------------------------------------- Add ID
                   5521:     if ($uid) {
                   5522:        $uid=~tr/A-Z/a-z/;
                   5523:        my %uidhash=&idrget($udom,$uname);
1.196     www      5524:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5525:          && (!$forceid)) {
1.80      www      5526: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5527: 	      return 'error: user id "'.$uid.'" does not match '.
                   5528:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5529:           }
                   5530:        } else {
                   5531: 	  &idput($udom,($uname => $uid));
                   5532:        }
                   5533:     }
                   5534: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5535:     my @tmp=&get('environment',
1.899     raeburn  5536: 		   ['firstname','middlename','lastname','generation','id',
                   5537:                     'permanentemail'],
1.134     albertel 5538: 		   $udom,$uname);
1.313     matthew  5539:     my %names;
                   5540:     if ($tmp[0] =~ m/^error:.*/) { 
                   5541:         %names=(); 
                   5542:     } else {
                   5543:         %names = @tmp;
                   5544:     }
1.388     www      5545: #
                   5546: # Make sure to not trash student environment if instructor does not bother
                   5547: # to supply name and email information
                   5548: #
                   5549:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5550:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5551:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5552:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5553:     if ($email) {
                   5554:        $email=~s/[^\w\@\.\-\,]//gs;
                   5555:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5556: 			   $names{'critnotification'} = $email;
                   5557: 			   $names{'permanentemail'} = $email; }
                   5558:     }
1.899     raeburn  5559:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5560:     my $reply = &put('environment', \%names, $udom,$uname);
                   5561:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5562:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5563:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5564:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5565:              $umode.', '.$first.', '.$middle.', '.
                   5566: 	     $last.', '.$gene.' by '.
1.620     albertel 5567:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5568:     return 'ok';
1.80      www      5569: }
                   5570: 
1.81      www      5571: # -------------------------------------------------------------- Modify student
1.80      www      5572: 
1.81      www      5573: sub modifystudent {
                   5574:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5575:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5576:     if (!$cid) {
1.620     albertel 5577: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5578: 	    return 'not_in_class';
                   5579: 	}
1.80      www      5580:     }
                   5581: # --------------------------------------------------------------- Make the user
1.81      www      5582:     my $reply=&modifyuser
1.209     matthew  5583: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5584:          $desiredhome,$email);
1.80      www      5585:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5586:     # This will cause &modify_student_enrollment to get the uid from the
                   5587:     # students environment
                   5588:     $uid = undef if (!$forceid);
1.455     albertel 5589:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5590: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5591:     return $reply;
                   5592: }
                   5593: 
                   5594: sub modify_student_enrollment {
1.947     raeburn  5595:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
1.455     albertel 5596:     my ($cdom,$cnum,$chome);
                   5597:     if (!$cid) {
1.620     albertel 5598: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5599: 	    return 'not_in_class';
                   5600: 	}
1.620     albertel 5601: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5602: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5603:     } else {
                   5604: 	($cdom,$cnum)=split(/_/,$cid);
                   5605:     }
1.620     albertel 5606:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5607:     if (!$chome) {
1.457     raeburn  5608: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5609:     }
1.455     albertel 5610:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5611:     # Make sure the user exists
1.81      www      5612:     my $uhome=&homeserver($uname,$udom);
                   5613:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5614: 	return 'error: no such user';
                   5615:     }
1.297     matthew  5616:     # Get student data if we were not given enough information
                   5617:     if (!defined($first)  || $first  eq '' || 
                   5618:         !defined($last)   || $last   eq '' || 
                   5619:         !defined($uid)    || $uid    eq '' || 
                   5620:         !defined($middle) || $middle eq '' || 
                   5621:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5622:         # They did not supply us with enough data to enroll the student, so
                   5623:         # we need to pick up more information.
1.297     matthew  5624:         my %tmp = &get('environment',
1.294     matthew  5625:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5626:                        ,$udom,$uname);
                   5627: 
1.800     albertel 5628:         #foreach my $key (keys(%tmp)) {
                   5629:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5630:         #}
1.294     matthew  5631:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5632:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5633:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5634:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5635:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5636:     }
1.556     albertel 5637:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5638:     my $reply=cput('classlist',
                   5639: 		   {"$uname:$udom" => 
1.515     raeburn  5640: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5641: 		   $cdom,$cnum);
1.81      www      5642:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5643: 	return 'error: '.$reply;
1.652     albertel 5644:     } else {
                   5645: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5646:     }
1.297     matthew  5647:     # Add student role to user
1.83      www      5648:     my $uurl='/'.$cid;
1.81      www      5649:     $uurl=~s/\_/\//g;
                   5650:     if ($usec) {
                   5651: 	$uurl.='/'.$usec;
                   5652:     }
1.947     raeburn  5653:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
1.21      www      5654: }
                   5655: 
1.556     albertel 5656: sub format_name {
                   5657:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5658:     my $name;
                   5659:     if ($first ne 'lastname') {
                   5660: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5661:     } else {
                   5662: 	if ($lastname=~/\S/) {
                   5663: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5664: 	    $name=~s/\s+,/,/;
                   5665: 	} else {
                   5666: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5667: 	}
                   5668:     }
                   5669:     $name=~s/^\s+//;
                   5670:     $name=~s/\s+$//;
                   5671:     $name=~s/\s+/ /g;
                   5672:     return $name;
                   5673: }
                   5674: 
1.84      www      5675: # ------------------------------------------------- Write to course preferences
                   5676: 
                   5677: sub writecoursepref {
                   5678:     my ($courseid,%prefs)=@_;
                   5679:     $courseid=~s/^\///;
                   5680:     $courseid=~s/\_/\//g;
                   5681:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5682:     my $chome=homeserver($cnum,$cdomain);
                   5683:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5684: 	return 'error: no such course';
                   5685:     }
                   5686:     my $cstring='';
1.800     albertel 5687:     foreach my $pref (keys(%prefs)) {
                   5688: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5689:     }
1.84      www      5690:     $cstring=~s/\&$//;
                   5691:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5692: }
                   5693: 
                   5694: # ---------------------------------------------------------- Make/modify course
                   5695: 
                   5696: sub createcourse {
1.741     raeburn  5697:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5698:         $course_owner,$crstype)=@_;
1.84      www      5699:     $url=&declutter($url);
                   5700:     my $cid='';
1.264     matthew  5701:     unless (&allowed('ccc',$udom)) {
1.84      www      5702:         return 'refused';
                   5703:     }
                   5704: # ------------------------------------------------------------------- Create ID
1.674     www      5705:    my $uname=int(1+rand(9)).
                   5706:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5707:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5708:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5709: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5710:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5711:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5712:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5713:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5714:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5715:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5716:            return 'error: unable to generate unique course-ID';
                   5717:        } 
                   5718:    }
1.264     matthew  5719: # ------------------------------------------------ Check supplied server name
1.620     albertel 5720:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5721:     if (! &is_library($course_server)) {
1.264     matthew  5722:         return 'error:bad server name '.$course_server;
                   5723:     }
1.84      www      5724: # ------------------------------------------------------------- Make the course
                   5725:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5726:                       $course_server);
1.84      www      5727:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5728:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5729:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5730: 	return 'error: no such course';
                   5731:     }
1.271     www      5732: # ----------------------------------------------------------------- Course made
1.516     raeburn  5733: # log existence
1.918     raeburn  5734:     my $newcourse = {
                   5735:                     $udom.'_'.$uname => {
1.921     raeburn  5736:                                      description => $description,
                   5737:                                      inst_code   => $inst_code,
                   5738:                                      owner       => $course_owner,
                   5739:                                      type        => $crstype,
1.918     raeburn  5740:                                                 },
                   5741:                     };
1.921     raeburn  5742:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5743: # set toplevel url
1.271     www      5744:     my $topurl=$url;
                   5745:     unless ($nonstandard) {
                   5746: # ------------------------------------------ For standard courses, make top url
                   5747:         my $mapurl=&clutter($url);
1.278     www      5748:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5749:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5750: <map>
                   5751: <resource id="1" type="start"></resource>
                   5752: <resource id="2" src="$mapurl"></resource>
                   5753: <resource id="3" type="finish"></resource>
                   5754: <link index="1" from="1" to="2"></link>
                   5755: <link index="2" from="2" to="3"></link>
                   5756: </map>
                   5757: ENDINITMAP
                   5758:         $topurl=&declutter(
1.638     albertel 5759:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5760:                           );
                   5761:     }
                   5762: # ----------------------------------------------------------- Write preferences
1.84      www      5763:     &writecoursepref($udom.'_'.$uname,
                   5764:                      ('description' => $description,
1.271     www      5765:                       'url'         => $topurl));
1.84      www      5766:     return '/'.$udom.'/'.$uname;
                   5767: }
                   5768: 
1.813     albertel 5769: sub is_course {
                   5770:     my ($cdom,$cnum) = @_;
                   5771:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5772: 				undef,'.');
1.813     albertel 5773:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5774:         return 1;
                   5775:     }
                   5776:     return 0;
                   5777: }
                   5778: 
1.21      www      5779: # ---------------------------------------------------------- Assign Custom Role
                   5780: 
                   5781: sub assigncustomrole {
1.357     www      5782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5783:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5784:                        $end,$start,$deleteflag);
1.21      www      5785: }
                   5786: 
                   5787: # ----------------------------------------------------------------- Revoke Role
                   5788: 
                   5789: sub revokerole {
1.357     www      5790:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5791:     my $now=time;
1.357     www      5792:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5793: }
                   5794: 
                   5795: # ---------------------------------------------------------- Revoke Custom Role
                   5796: 
                   5797: sub revokecustomrole {
1.357     www      5798:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5799:     my $now=time;
1.357     www      5800:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5801:            $deleteflag);
1.17      www      5802: }
                   5803: 
1.533     banghart 5804: # ------------------------------------------------------------ Disk usage
1.535     albertel 5805: sub diskusage {
1.955   ! raeburn  5806:     my ($udom,$uname,$directorypath,$getpropath)=@_;
        !          5807:     $directorypath =~ s/\/$//;
        !          5808:     my $listing=&reply('du2:'.&escape($directorypath).':'
        !          5809:                        .&escape($getpropath).':'.&escape($uname).':'
        !          5810:                        .&escape($udom),homeserver($uname,$udom));
        !          5811:     if ($listing eq 'unknown_cmd') {
        !          5812:         if ($getpropath) {
        !          5813:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
        !          5814:         }
        !          5815:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
        !          5816:     }
1.514     albertel 5817:     return $listing;
1.512     banghart 5818: }
                   5819: 
1.566     banghart 5820: sub is_locked {
                   5821:     my ($file_name, $domain, $user) = @_;
                   5822:     my @check;
                   5823:     my $is_locked;
                   5824:     push @check, $file_name;
1.613     albertel 5825:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5826: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5827:     my ($tmp)=keys(%locked);
                   5828:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5829:     
1.566     banghart 5830:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5831:         $is_locked = 'false';
                   5832:         foreach my $entry (@{$locked{$file_name}}) {
                   5833:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5834:                $is_locked = 'true';
                   5835:                last;
1.745     raeburn  5836:            }
                   5837:        }
1.566     banghart 5838:     } else {
                   5839:         $is_locked = 'false';
                   5840:     }
                   5841: }
                   5842: 
1.759     albertel 5843: sub declutter_portfile {
                   5844:     my ($file) = @_;
1.833     albertel 5845:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5846:     return $file;
                   5847: }
                   5848: 
1.559     banghart 5849: # ------------------------------------------------------------- Mark as Read Only
                   5850: 
                   5851: sub mark_as_readonly {
                   5852:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5853:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5854:     my ($tmp)=keys(%current_permissions);
                   5855:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5856:     foreach my $file (@{$files}) {
1.759     albertel 5857: 	$file = &declutter_portfile($file);
1.561     banghart 5858:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5859:     }
1.613     albertel 5860:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5861:     return;
                   5862: }
                   5863: 
1.572     banghart 5864: # ------------------------------------------------------------Save Selected Files
                   5865: 
                   5866: sub save_selected_files {
                   5867:     my ($user, $path, @files) = @_;
                   5868:     my $filename = $user."savedfiles";
1.573     banghart 5869:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5870:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5871:     foreach my $file (@files) {
1.620     albertel 5872:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5873:     }
                   5874:     foreach my $file (@other_files) {
1.574     banghart 5875:         print (OUT $file."\n");
1.572     banghart 5876:     }
1.574     banghart 5877:     close (OUT);
1.572     banghart 5878:     return 'ok';
                   5879: }
                   5880: 
1.574     banghart 5881: sub clear_selected_files {
                   5882:     my ($user) = @_;
                   5883:     my $filename = $user."savedfiles";
                   5884:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5885:     print (OUT undef);
                   5886:     close (OUT);
                   5887:     return ("ok");    
                   5888: }
                   5889: 
1.572     banghart 5890: sub files_in_path {
                   5891:     my ($user, $path) = @_;
                   5892:     my $filename = $user."savedfiles";
                   5893:     my %return_files;
1.574     banghart 5894:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5895:     while (my $line_in = <IN>) {
1.574     banghart 5896:         chomp ($line_in);
                   5897:         my @paths_and_file = split (m!/!, $line_in);
                   5898:         my $file_part = pop (@paths_and_file);
                   5899:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5900:         $path_part.='/';
                   5901:         my $path_and_file = $path_part.$file_part;
                   5902:         if ($path_part eq $path) {
                   5903:             $return_files{$file_part}= 'selected';
                   5904:         }
                   5905:     }
1.574     banghart 5906:     close (IN);
                   5907:     return (\%return_files);
1.572     banghart 5908: }
                   5909: 
                   5910: # called in portfolio select mode, to show files selected NOT in current directory
                   5911: sub files_not_in_path {
                   5912:     my ($user, $path) = @_;
                   5913:     my $filename = $user."savedfiles";
                   5914:     my @return_files;
                   5915:     my $path_part;
1.800     albertel 5916:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5917:     while (my $line = <IN>) {
1.572     banghart 5918:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5919:         my @paths_and_file = split(m|/|, $line);
                   5920:         my $file_part = pop(@paths_and_file);
                   5921:         chomp($file_part);
                   5922:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5923:         $path_part .= '/';
                   5924:         my $path_and_file = $path_part.$file_part;
                   5925:         if ($path_part ne $path) {
1.800     albertel 5926:             push(@return_files, ($path_and_file));
1.572     banghart 5927:         }
                   5928:     }
1.800     albertel 5929:     close(OUT);
1.574     banghart 5930:     return (@return_files);
1.572     banghart 5931: }
                   5932: 
1.745     raeburn  5933: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5934: 
1.745     raeburn  5935: sub get_portfile_permissions {
                   5936:     my ($domain,$user) = @_;
1.613     albertel 5937:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5938:     my ($tmp)=keys(%current_permissions);
                   5939:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5940:     return \%current_permissions;
                   5941: }
                   5942: 
                   5943: #---------------------------------------------Get portfolio file access controls
                   5944: 
1.749     raeburn  5945: sub get_access_controls {
1.745     raeburn  5946:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5947:     my %access;
                   5948:     my $real_file = $file;
                   5949:     $file =~ s/\.meta$//;
1.745     raeburn  5950:     if (defined($file)) {
1.749     raeburn  5951:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5952:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5953:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5954:             }
                   5955:         }
1.745     raeburn  5956:     } else {
1.749     raeburn  5957:         foreach my $key (keys(%{$current_permissions})) {
                   5958:             if ($key =~ /\0accesscontrol$/) {
                   5959:                 if (defined($group)) {
                   5960:                     if ($key !~ m-^\Q$group\E/-) {
                   5961:                         next;
                   5962:                     }
                   5963:                 }
                   5964:                 my ($fullpath) = split(/\0/,$key);
                   5965:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5966:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5967:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5968:                     }
                   5969:                 }
                   5970:             }
                   5971:         }
                   5972:     }
                   5973:     return %access;
                   5974: }
                   5975: 
                   5976: sub modify_access_controls {
                   5977:     my ($file_name,$changes,$domain,$user)=@_;
                   5978:     my ($outcome,$deloutcome);
                   5979:     my %store_permissions;
                   5980:     my %new_values;
                   5981:     my %new_control;
                   5982:     my %translation;
                   5983:     my @deletions = ();
                   5984:     my $now = time;
                   5985:     if (exists($$changes{'activate'})) {
                   5986:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5987:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5988:             my $numnew = scalar(@newitems);
                   5989:             for (my $i=0; $i<$numnew; $i++) {
                   5990:                 my $newkey = $newitems[$i];
                   5991:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5992:                 if ($newkey =~ /^\d+:/) { 
                   5993:                     $newkey =~ s/^(\d+)/$newid/;
                   5994:                     $translation{$1} = $newid;
                   5995:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5996:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5997:                     $translation{$1} = $newid;
                   5998:                 }
1.749     raeburn  5999:                 $new_values{$file_name."\0".$newkey} = 
                   6000:                                           $$changes{'activate'}{$newitems[$i]};
                   6001:                 $new_control{$newkey} = $now;
                   6002:             }
                   6003:         }
                   6004:     }
                   6005:     my %todelete;
                   6006:     my %changed_items;
                   6007:     foreach my $action ('delete','update') {
                   6008:         if (exists($$changes{$action})) {
                   6009:             if (ref($$changes{$action}) eq 'HASH') {
                   6010:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6011:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6012:                     if ($action eq 'delete') { 
                   6013:                         $todelete{$itemnum} = 1;
                   6014:                     } else {
                   6015:                         $changed_items{$itemnum} = $key;
                   6016:                     }
                   6017:                 }
1.745     raeburn  6018:             }
                   6019:         }
1.749     raeburn  6020:     }
                   6021:     # get lock on access controls for file.
                   6022:     my $lockhash = {
                   6023:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6024:                                                        ':'.$env{'user.domain'},
                   6025:                    }; 
                   6026:     my $tries = 0;
                   6027:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6028:    
                   6029:     while (($gotlock ne 'ok') && $tries <3) {
                   6030:         $tries ++;
                   6031:         sleep 1;
                   6032:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6033:     }
                   6034:     if ($gotlock eq 'ok') {
                   6035:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6036:         my ($tmp)=keys(%curr_permissions);
                   6037:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6038:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6039:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6040:             if (ref($curr_controls) eq 'HASH') {
                   6041:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6042:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6043:                     if (defined($todelete{$itemnum})) {
                   6044:                         push(@deletions,$file_name."\0".$control_item);
                   6045:                     } else {
                   6046:                         if (defined($changed_items{$itemnum})) {
                   6047:                             $new_control{$changed_items{$itemnum}} = $now;
                   6048:                             push(@deletions,$file_name."\0".$control_item);
                   6049:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6050:                         } else {
                   6051:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6052:                         }
                   6053:                     }
1.745     raeburn  6054:                 }
                   6055:             }
                   6056:         }
1.749     raeburn  6057:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6058:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6059:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6060:         #  remove lock
                   6061:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6062:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6063:         my ($file,$group);
                   6064:         if (&is_course($domain,$user)) {
                   6065:             ($group,$file) = split(/\//,$file_name,2);
                   6066:         } else {
                   6067:             $file = $file_name;
                   6068:         }
                   6069:         my $sqlresult =
                   6070:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6071:                                     $group);
1.749     raeburn  6072:     } else {
                   6073:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6074:     }
1.749     raeburn  6075:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6076: }
                   6077: 
1.827     raeburn  6078: sub make_public_indefinitely {
                   6079:     my ($requrl) = @_;
                   6080:     my $now = time;
                   6081:     my $action = 'activate';
                   6082:     my $aclnum = 0;
                   6083:     if (&is_portfolio_url($requrl)) {
                   6084:         my (undef,$udom,$unum,$file_name,$group) =
                   6085:             &parse_portfolio_url($requrl);
                   6086:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6087:         my %access_controls = &get_access_controls($current_perms,
                   6088:                                                    $group,$file_name);
                   6089:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6090:             my ($num,$scope,$end,$start) = 
                   6091:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6092:             if ($scope eq 'public') {
                   6093:                 if ($start <= $now && $end == 0) {
                   6094:                     $action = 'none';
                   6095:                 } else {
                   6096:                     $action = 'update';
                   6097:                     $aclnum = $num;
                   6098:                 }
                   6099:                 last;
                   6100:             }
                   6101:         }
                   6102:         if ($action eq 'none') {
                   6103:              return 'ok';
                   6104:         } else {
                   6105:             my %changes;
                   6106:             my $newend = 0;
                   6107:             my $newstart = $now;
                   6108:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6109:             $changes{$action}{$newkey} = {
                   6110:                 type => 'public',
                   6111:                 time => {
                   6112:                     start => $newstart,
                   6113:                     end   => $newend,
                   6114:                 },
                   6115:             };
                   6116:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6117:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6118:             return $outcome;
                   6119:         }
                   6120:     } else {
                   6121:         return 'invalid';
                   6122:     }
                   6123: }
                   6124: 
1.745     raeburn  6125: #------------------------------------------------------Get Marked as Read Only
                   6126: 
                   6127: sub get_marked_as_readonly {
                   6128:     my ($domain,$user,$what,$group) = @_;
                   6129:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6130:     my @readonly_files;
1.629     banghart 6131:     my $cmp1=$what;
                   6132:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6133:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6134:         if (defined($group)) {
                   6135:             if ($file_name !~ m-^\Q$group\E/-) {
                   6136:                 next;
                   6137:             }
                   6138:         }
1.561     banghart 6139:         if (ref($value) eq "ARRAY"){
                   6140:             foreach my $stored_what (@{$value}) {
1.629     banghart 6141:                 my $cmp2=$stored_what;
1.759     albertel 6142:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6143:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6144:                 }
1.629     banghart 6145:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6146:                     push(@readonly_files, $file_name);
1.745     raeburn  6147:                     last;
1.563     banghart 6148:                 } elsif (!defined($what)) {
                   6149:                     push(@readonly_files, $file_name);
1.745     raeburn  6150:                     last;
1.561     banghart 6151:                 }
                   6152:             }
1.745     raeburn  6153:         }
1.561     banghart 6154:     }
                   6155:     return @readonly_files;
                   6156: }
1.577     banghart 6157: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6158: 
1.577     banghart 6159: sub get_marked_as_readonly_hash {
1.745     raeburn  6160:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6161:     my %readonly_files;
1.745     raeburn  6162:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6163:         if (defined($group)) {
                   6164:             if ($file_name !~ m-^\Q$group\E/-) {
                   6165:                 next;
                   6166:             }
                   6167:         }
1.577     banghart 6168:         if (ref($value) eq "ARRAY"){
                   6169:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6170:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6171:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6172:                         if ($lock_descriptor eq 'graded') {
                   6173:                             $readonly_files{$file_name} = 'graded';
                   6174:                         } elsif ($lock_descriptor eq 'handback') {
                   6175:                             $readonly_files{$file_name} = 'handback';
                   6176:                         } else {
                   6177:                             if (!exists($readonly_files{$file_name})) {
                   6178:                                 $readonly_files{$file_name} = 'locked';
                   6179:                             }
                   6180:                         }
1.745     raeburn  6181:                     }
1.750     banghart 6182:                 } 
1.577     banghart 6183:             }
                   6184:         } 
                   6185:     }
                   6186:     return %readonly_files;
                   6187: }
1.559     banghart 6188: # ------------------------------------------------------------ Unmark as Read Only
                   6189: 
                   6190: sub unmark_as_readonly {
1.629     banghart 6191:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6192:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6193:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6194:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6195:     my $symb_crs = $what;
                   6196:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6197:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6198:     my ($tmp)=keys(%current_permissions);
                   6199:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6200:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6201:     foreach my $file (@readonly_files) {
1.759     albertel 6202: 	my $clean_file = &declutter_portfile($file);
                   6203: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6204: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6205:         my @new_locks;
                   6206:         my @del_keys;
                   6207:         if (ref($current_locks) eq "ARRAY"){
                   6208:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6209:                 my $compare=$locker;
1.749     raeburn  6210:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6211:                     $compare=join('',@{$locker});
1.746     raeburn  6212:                     if ($compare ne $symb_crs) {
                   6213:                         push(@new_locks, $locker);
                   6214:                     }
1.563     banghart 6215:                 }
                   6216:             }
1.650     albertel 6217:             if (scalar(@new_locks) > 0) {
1.563     banghart 6218:                 $current_permissions{$file} = \@new_locks;
                   6219:             } else {
                   6220:                 push(@del_keys, $file);
1.613     albertel 6221:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6222:                 delete($current_permissions{$file});
1.563     banghart 6223:             }
                   6224:         }
1.561     banghart 6225:     }
1.613     albertel 6226:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6227:     return;
                   6228: }
1.512     banghart 6229: 
1.17      www      6230: # ------------------------------------------------------------ Directory lister
                   6231: 
                   6232: sub dirlist {
1.955   ! raeburn  6233:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6234:     $uri=~s/^\///;
                   6235:     $uri=~s/\/$//;
1.253     stredwic 6236:     my ($udom, $uname);
1.955   ! raeburn  6237:     if ($getuserdir) {
1.253     stredwic 6238:         $udom = $userdomain;
                   6239:         $uname = $username;
1.955   ! raeburn  6240:     } else {
        !          6241:         (undef,$udom,$uname)=split(/\//,$uri);
        !          6242:         if(defined($userdomain)) {
        !          6243:             $udom = $userdomain;
        !          6244:         }
        !          6245:         if(defined($username)) {
        !          6246:             $uname = $username;
        !          6247:         }
1.253     stredwic 6248:     }
1.955   ! raeburn  6249:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6250: 
1.955   ! raeburn  6251:     $dirRoot = $perlvar{'lonDocRoot'};
        !          6252:     if (defined($getpropath)) {
        !          6253:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6254:         $dirRoot =~ s/\/$//;
1.955   ! raeburn  6255:     } elsif (defined($getuserdir)) {
        !          6256:         my $subdir=$uname.'__';
        !          6257:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
        !          6258:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
        !          6259:                    ."/$udom/$subdir/$uname";
        !          6260:     } elsif (defined($alternateRoot)) {
        !          6261:         $dirRoot = $alternateRoot;
1.751     banghart 6262:     }
1.253     stredwic 6263: 
                   6264:     if($udom) {
                   6265:         if($uname) {
1.955   ! raeburn  6266:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
        !          6267:                               .$getuserdir.':'.&escape($alternateRoot)
        !          6268:                               .':'.&escape($uname).':'.&escape($udom),
        !          6269:                               &homeserver($uname,$udom));
        !          6270:             if ($listing eq 'unknown_cmd') {
        !          6271:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
        !          6272:                                   &homeserver($uname,$udom));
        !          6273:             } else {
        !          6274:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
        !          6275:             }
1.605     matthew  6276:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6277:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6278: 				  &homeserver($uname,$udom));
1.605     matthew  6279:                 @listing_results = split(/:/,$listing);
                   6280:             } else {
                   6281:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6282:             }
                   6283:             return @listing_results;
1.955   ! raeburn  6284:         } elsif(!$alternateRoot) {
1.800     albertel 6285:             my %allusers;
1.841     albertel 6286: 	    my %servers = &get_servers($udom,'library');
1.955   ! raeburn  6287:  	    foreach my $tryserver (keys(%servers)) {
        !          6288:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
        !          6289:                                   &escape($udom),$tryserver);
        !          6290:                 if ($listing eq 'unknown_cmd') {
        !          6291: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
        !          6292: 				      $udom, $tryserver);
        !          6293:                 } else {
        !          6294:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
        !          6295:                 }
1.841     albertel 6296: 		if ($listing eq 'unknown_cmd') {
                   6297: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6298: 				      $udom, $tryserver);
                   6299: 		    @listing_results = split(/:/,$listing);
                   6300: 		} else {
                   6301: 		    @listing_results =
                   6302: 			map { &unescape($_); } split(/:/,$listing);
                   6303: 		}
                   6304: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6305: 		    $listing_results[0] ne 'empty'       &&
                   6306: 		    $listing_results[0] ne 'con_lost') {
                   6307: 		    foreach my $line (@listing_results) {
                   6308: 			my ($entry) = split(/&/,$line,2);
                   6309: 			$allusers{$entry} = 1;
                   6310: 		    }
                   6311: 		}
1.253     stredwic 6312:             }
                   6313:             my $alluserstr='';
1.800     albertel 6314:             foreach my $user (sort(keys(%allusers))) {
                   6315:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6316:             }
                   6317:             $alluserstr=~s/:$//;
                   6318:             return split(/:/,$alluserstr);
                   6319:         } else {
1.800     albertel 6320:             return ('missing user name');
1.253     stredwic 6321:         }
1.955   ! raeburn  6322:     } elsif(!defined($getpropath)) {
1.841     albertel 6323:         my @all_domains = sort(&all_domains());
1.955   ! raeburn  6324:         foreach my $domain (@all_domains) {
        !          6325:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
        !          6326:         }
        !          6327:         return @all_domains;
        !          6328:     } else {
1.800     albertel 6329:         return ('missing domain');
1.275     stredwic 6330:     }
                   6331: }
                   6332: 
                   6333: # --------------------------------------------- GetFileTimestamp
                   6334: # This function utilizes dirlist and returns the date stamp for
                   6335: # when it was last modified.  It will also return an error of -1
                   6336: # if an error occurs
                   6337: 
                   6338: sub GetFileTimestamp {
1.955   ! raeburn  6339:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6340:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6341:     $studentName   = &LONCAPA::clean_username($studentName);
1.955   ! raeburn  6342:     my ($fileStat) = 
        !          6343:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
        !          6344:                                  undef,$getuserdir);
1.275     stredwic 6345:     my @stats = split('&', $fileStat);
                   6346:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6347:         # @stats contains first the filename, then the stat output
                   6348:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6349:     } else {
                   6350:         return -1;
1.253     stredwic 6351:     }
1.26      www      6352: }
                   6353: 
1.712     albertel 6354: sub stat_file {
                   6355:     my ($uri) = @_;
1.787     albertel 6356:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6357: 
1.955   ! raeburn  6358:     my ($udom,$uname,$file);
1.712     albertel 6359:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6360: 	($udom,$uname,$file) =
1.811     albertel 6361: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6362: 	$file = 'userfiles/'.$file;
                   6363:     }
                   6364:     if ($uri =~ m-^/res/-) {
                   6365: 	($udom,$uname) = 
1.807     albertel 6366: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6367: 	$file = $uri;
                   6368:     }
                   6369: 
                   6370:     if (!$udom || !$uname || !$file) {
                   6371: 	# unable to handle the uri
                   6372: 	return ();
                   6373:     }
                   6374: 
1.955   ! raeburn  6375:     my $getpropath = 1;
        !          6376:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6377:     my @stats = split('&', $result);
1.721     banghart 6378:     
1.712     albertel 6379:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6380: 	shift(@stats); #filename is first
                   6381: 	return @stats;
                   6382:     }
                   6383:     return ();
                   6384: }
                   6385: 
1.26      www      6386: # -------------------------------------------------------- Value of a Condition
                   6387: 
1.713     albertel 6388: # gets the value of a specific preevaluated condition
                   6389: #    stored in the string  $env{user.state.<cid>}
                   6390: # or looks up a condition reference in the bighash and if if hasn't
                   6391: # already been evaluated recurses into docondval to get the value of
                   6392: # the condition, then memoizing it to 
                   6393: #   $env{user.state.<cid>.<condition>}
1.40      www      6394: sub directcondval {
                   6395:     my $number=shift;
1.620     albertel 6396:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6397: 	&Apache::lonuserstate::evalstate();
                   6398:     }
1.713     albertel 6399:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6400: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6401:     } elsif ($number =~ /^_/) {
                   6402: 	my $sub_condition;
                   6403: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6404: 		&GDBM_READER(),0640)) {
                   6405: 	    $sub_condition=$bighash{'conditions'.$number};
                   6406: 	    untie(%bighash);
                   6407: 	}
                   6408: 	my $value = &docondval($sub_condition);
1.949     raeburn  6409: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6410: 	return $value;
                   6411:     }
1.620     albertel 6412:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6413:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6414:     } else {
                   6415:        return 2;
                   6416:     }
                   6417: }
                   6418: 
1.713     albertel 6419: # get the collection of conditions for this resource
1.26      www      6420: sub condval {
                   6421:     my $condidx=shift;
1.54      www      6422:     my $allpathcond='';
1.713     albertel 6423:     foreach my $cond (split(/\|/,$condidx)) {
                   6424: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6425: 	    $allpathcond.=
                   6426: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6427: 	}
1.191     harris41 6428:     }
1.54      www      6429:     $allpathcond=~s/\|$//;
1.713     albertel 6430:     return &docondval($allpathcond);
                   6431: }
                   6432: 
                   6433: #evaluates an expression of conditions
                   6434: sub docondval {
                   6435:     my ($allpathcond) = @_;
                   6436:     my $result=0;
                   6437:     if ($env{'request.course.id'}
                   6438: 	&& defined($allpathcond)) {
                   6439: 	my $operand='|';
                   6440: 	my @stack;
                   6441: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6442: 	    if ($chunk eq '(') {
                   6443: 		push @stack,($operand,$result);
                   6444: 	    } elsif ($chunk eq ')') {
                   6445: 		my $before=pop @stack;
                   6446: 		if (pop @stack eq '&') {
                   6447: 		    $result=$result>$before?$before:$result;
                   6448: 		} else {
                   6449: 		    $result=$result>$before?$result:$before;
                   6450: 		}
                   6451: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6452: 		$operand=$chunk;
                   6453: 	    } else {
                   6454: 		my $new=directcondval($chunk);
                   6455: 		if ($operand eq '&') {
                   6456: 		    $result=$result>$new?$new:$result;
                   6457: 		} else {
                   6458: 		    $result=$result>$new?$result:$new;
                   6459: 		}
                   6460: 	    }
                   6461: 	}
1.26      www      6462:     }
                   6463:     return $result;
1.421     albertel 6464: }
                   6465: 
                   6466: # ---------------------------------------------------- Devalidate courseresdata
                   6467: 
                   6468: sub devalidatecourseresdata {
                   6469:     my ($coursenum,$coursedomain)=@_;
                   6470:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6471:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6472: }
                   6473: 
1.763     www      6474: 
1.200     www      6475: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6476: #
                   6477: #  Parameters:
                   6478: #      $coursenum    - Number of the course.
                   6479: #      $coursedomain - Domain at which the course was created.
                   6480: #  Returns:
                   6481: #     A hash of the course parameters along (I think) with timestamps
                   6482: #     and version info.
1.877     foxr     6483: 
1.624     albertel 6484: sub get_courseresdata {
                   6485:     my ($coursenum,$coursedomain)=@_;
1.200     www      6486:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6487:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6488:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6489:     my %dumpreply;
1.417     albertel 6490:     unless (defined($cached)) {
1.624     albertel 6491: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6492: 	$result=\%dumpreply;
1.251     albertel 6493: 	my ($tmp) = keys(%dumpreply);
                   6494: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6495: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6496: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6497: 	    return $tmp;
1.416     albertel 6498: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6499: 	    $result=undef;
1.599     albertel 6500: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6501: 	}
                   6502:     }
1.624     albertel 6503:     return $result;
                   6504: }
                   6505: 
1.633     albertel 6506: sub devalidateuserresdata {
                   6507:     my ($uname,$udom)=@_;
                   6508:     my $hashid="$udom:$uname";
                   6509:     &devalidate_cache_new('userres',$hashid);
                   6510: }
                   6511: 
1.624     albertel 6512: sub get_userresdata {
                   6513:     my ($uname,$udom)=@_;
                   6514:     #most student don\'t have any data set, check if there is some data
                   6515:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6516: 
                   6517:     my $hashid="$udom:$uname";
                   6518:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6519:     if (!defined($cached)) {
                   6520: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6521: 	$result=\%resourcedata;
                   6522: 	&do_cache_new('userres',$hashid,$result,600);
                   6523:     }
                   6524:     my ($tmp)=keys(%$result);
                   6525:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6526: 	return $result;
                   6527:     }
                   6528:     #error 2 occurs when the .db doesn't exist
                   6529:     if ($tmp!~/error: 2 /) {
1.672     albertel 6530: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6531: 		 " Trying to get resource data for ".
                   6532: 		 $uname." at ".$udom.": ".
                   6533: 		 $tmp."</font>");
                   6534:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6535: 	#&EXT_cache_set($udom,$uname);
                   6536: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6537: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6538:     }
                   6539:     return $tmp;
                   6540: }
1.879     foxr     6541: #----------------------------------------------- resdata - return resource data
                   6542: #  Purpose:
                   6543: #    Return resource data for either users or for a course.
                   6544: #  Parameters:
                   6545: #     $name      - Course/user name.
                   6546: #     $domain    - Name of the domain the user/course is registered on.
                   6547: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6548: #     @which     - Array of names of resources desired.
                   6549: #  Returns:
                   6550: #     The value of the first reasource in @which that is found in the
                   6551: #     resource hash.
                   6552: #  Exceptional Conditions:
                   6553: #     If the $type passed in is not valid (not the string 'course' or 
                   6554: #     'user', an undefined  reference is returned.
                   6555: #     If none of the resources are found, an undef is returned
1.624     albertel 6556: sub resdata {
                   6557:     my ($name,$domain,$type,@which)=@_;
                   6558:     my $result;
                   6559:     if ($type eq 'course') {
                   6560: 	$result=&get_courseresdata($name,$domain);
                   6561:     } elsif ($type eq 'user') {
                   6562: 	$result=&get_userresdata($name,$domain);
                   6563:     }
                   6564:     if (!ref($result)) { return $result; }    
1.251     albertel 6565:     foreach my $item (@which) {
1.927     albertel 6566: 	if (defined($result->{$item->[0]})) {
                   6567: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6568: 	}
1.250     albertel 6569:     }
1.291     albertel 6570:     return undef;
1.200     www      6571: }
                   6572: 
1.379     matthew  6573: #
                   6574: # EXT resource caching routines
                   6575: #
                   6576: 
                   6577: sub clear_EXT_cache_status {
1.383     albertel 6578:     &delenv('cache.EXT.');
1.379     matthew  6579: }
                   6580: 
                   6581: sub EXT_cache_status {
                   6582:     my ($target_domain,$target_user) = @_;
1.383     albertel 6583:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6584:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6585:         # We know already the user has no data
                   6586:         return 1;
                   6587:     } else {
                   6588:         return 0;
                   6589:     }
                   6590: }
                   6591: 
                   6592: sub EXT_cache_set {
                   6593:     my ($target_domain,$target_user) = @_;
1.383     albertel 6594:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6595:     #&appenv({$cachename => time});
1.379     matthew  6596: }
                   6597: 
1.28      www      6598: # --------------------------------------------------------- Value of a Variable
1.58      www      6599: sub EXT {
1.715     albertel 6600: 
1.395     albertel 6601:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6602:     unless ($varname) { return ''; }
1.218     albertel 6603:     #get real user name/domain, courseid and symb
                   6604:     my $courseid;
1.359     albertel 6605:     my $publicuser;
1.427     www      6606:     if ($symbparm) {
                   6607: 	$symbparm=&get_symb_from_alias($symbparm);
                   6608:     }
1.218     albertel 6609:     if (!($uname && $udom)) {
1.790     albertel 6610:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6611:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6612:     } else {
1.620     albertel 6613: 	$courseid=$env{'request.course.id'};
1.218     albertel 6614:     }
1.48      www      6615:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6616:     my $rest;
1.320     albertel 6617:     if (defined($therest[0])) {
1.48      www      6618:        $rest=join('.',@therest);
                   6619:     } else {
                   6620:        $rest='';
                   6621:     }
1.320     albertel 6622: 
1.57      www      6623:     my $qualifierrest=$qualifier;
                   6624:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6625:     my $spacequalifierrest=$space;
                   6626:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6627:     if ($realm eq 'user') {
1.48      www      6628: # --------------------------------------------------------------- user.resource
                   6629: 	if ($space eq 'resource') {
1.651     albertel 6630: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6631: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6632: 		 &&
1.744     albertel 6633: 		 ($symbparm eq &symbread()) ) {	
                   6634: 		# if we are in the middle of processing the resource the
                   6635: 		# get the value we are planning on committing
                   6636:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6637:                     return $Apache::lonhomework::results{$qualifierrest};
                   6638:                 } else {
                   6639:                     return $Apache::lonhomework::history{$qualifierrest};
                   6640:                 }
1.335     albertel 6641: 	    } else {
1.359     albertel 6642: 		my %restored;
1.620     albertel 6643: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6644: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6645: 		} else {
                   6646: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6647: 		}
1.335     albertel 6648: 		return $restored{$qualifierrest};
                   6649: 	    }
1.48      www      6650: # ----------------------------------------------------------------- user.access
                   6651:         } elsif ($space eq 'access') {
1.218     albertel 6652: 	    # FIXME - not supporting calls for a specific user
1.48      www      6653:             return &allowed($qualifier,$rest);
                   6654: # ------------------------------------------ user.preferences, user.environment
                   6655:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6656: 	    if (($uname eq $env{'user.name'}) &&
                   6657: 		($udom eq $env{'user.domain'})) {
                   6658: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6659: 	    } else {
1.359     albertel 6660: 		my %returnhash;
                   6661: 		if (!$publicuser) {
                   6662: 		    %returnhash=&userenvironment($udom,$uname,
                   6663: 						 $qualifierrest);
                   6664: 		}
1.218     albertel 6665: 		return $returnhash{$qualifierrest};
                   6666: 	    }
1.48      www      6667: # ----------------------------------------------------------------- user.course
                   6668:         } elsif ($space eq 'course') {
1.218     albertel 6669: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6670:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6671: # ------------------------------------------------------------------- user.role
                   6672:         } elsif ($space eq 'role') {
1.218     albertel 6673: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6674:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6675:             if ($qualifier eq 'value') {
                   6676: 		return $role;
                   6677:             } elsif ($qualifier eq 'extent') {
                   6678:                 return $where;
                   6679:             }
                   6680: # ----------------------------------------------------------------- user.domain
                   6681:         } elsif ($space eq 'domain') {
1.218     albertel 6682:             return $udom;
1.48      www      6683: # ------------------------------------------------------------------- user.name
                   6684:         } elsif ($space eq 'name') {
1.218     albertel 6685:             return $uname;
1.48      www      6686: # ---------------------------------------------------- Any other user namespace
1.29      www      6687:         } else {
1.359     albertel 6688: 	    my %reply;
                   6689: 	    if (!$publicuser) {
                   6690: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6691: 	    }
                   6692: 	    return $reply{$qualifierrest};
1.48      www      6693:         }
1.236     www      6694:     } elsif ($realm eq 'query') {
                   6695: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6696:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6697: 						[$spacequalifierrest]);
1.620     albertel 6698: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6699:    } elsif ($realm eq 'request') {
1.48      www      6700: # ------------------------------------------------------------- request.browser
                   6701:         if ($space eq 'browser') {
1.430     www      6702: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6703: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6704: 		    return 1;
                   6705: 		} else {
                   6706: 		    return 0;
                   6707: 		}
                   6708: 	    } else {
1.620     albertel 6709: 		return $env{'browser.'.$qualifier};
1.430     www      6710: 	    }
1.57      www      6711: # ------------------------------------------------------------ request.filename
                   6712:         } else {
1.620     albertel 6713:             return $env{'request.'.$spacequalifierrest};
1.29      www      6714:         }
1.28      www      6715:     } elsif ($realm eq 'course') {
1.48      www      6716: # ---------------------------------------------------------- course.description
1.620     albertel 6717:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6718:     } elsif ($realm eq 'resource') {
1.165     www      6719: 
1.620     albertel 6720: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6721: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6722: 	}
1.693     albertel 6723: 
                   6724: 	if ($space eq 'title') {
                   6725: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6726: 	    return &gettitle($symbparm);
                   6727: 	}
                   6728: 	
                   6729: 	if ($space eq 'map') {
                   6730: 	    my ($map) = &decode_symb($symbparm);
                   6731: 	    return &symbread($map);
                   6732: 	}
1.905     albertel 6733: 	if ($space eq 'filename') {
                   6734: 	    if ($symbparm) {
                   6735: 		return &clutter((&decode_symb($symbparm))[2]);
                   6736: 	    }
                   6737: 	    return &hreflocation('',$env{'request.filename'});
                   6738: 	}
1.693     albertel 6739: 
                   6740: 	my ($section, $group, @groups);
1.593     albertel 6741: 	my ($courselevelm,$courselevel);
1.539     albertel 6742: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6743: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6744: 
1.218     albertel 6745: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6746: 
1.60      www      6747: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6748: 	    my $symbp=$symbparm;
1.735     albertel 6749: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6750: 
                   6751: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6752: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6753: 
1.620     albertel 6754: 	    if (($env{'user.name'} eq $uname) &&
                   6755: 		($env{'user.domain'} eq $udom)) {
                   6756: 		$section=$env{'request.course.sec'};
1.733     raeburn  6757:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6758:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6759: 	    } else {
1.539     albertel 6760: 		if (! defined($usection)) {
1.551     albertel 6761: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6762: 		} else {
                   6763: 		    $section = $usection;
                   6764: 		}
1.733     raeburn  6765:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6766: 	    }
                   6767: 
                   6768: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6769: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6770: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6771: 
1.593     albertel 6772: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6773: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6774: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6775: 
1.60      www      6776: # ----------------------------------------------------------- first, check user
1.624     albertel 6777: 
                   6778: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6779: 				       ([$courselevelr,'resource'],
                   6780: 					[$courselevelm,'map'     ],
                   6781: 					[$courselevel, 'course'  ]));
1.931     albertel 6782: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6783: 
1.594     albertel 6784: # ------------------------------------------------ second, check some of course
1.684     raeburn  6785:             my $coursereply;
1.691     raeburn  6786:             if (@groups > 0) {
                   6787:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6788:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6789:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6790:             }
1.96      www      6791: 
1.684     raeburn  6792: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6793: 				  $env{'course.'.$courseid.'.domain'},
                   6794: 				  'course',
                   6795: 				  ([$seclevelr,   'resource'],
                   6796: 				   [$seclevelm,   'map'     ],
                   6797: 				   [$seclevel,    'course'  ],
                   6798: 				   [$courselevelr,'resource']));
                   6799: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6800: 
1.60      www      6801: # ------------------------------------------------------ third, check map parms
1.218     albertel 6802: 	    my %parmhash=();
                   6803: 	    my $thisparm='';
                   6804: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6805: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6806: 		    &GDBM_READER(),0640)) {
1.218     albertel 6807: 		$thisparm=$parmhash{$symbparm};
                   6808: 		untie(%parmhash);
                   6809: 	    }
1.927     albertel 6810: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6811: 	}
1.594     albertel 6812: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6813: 
1.218     albertel 6814: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6815: 	my $filename;
                   6816: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6817: 	if ($symbparm) {
1.409     www      6818: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6819: 	} else {
1.620     albertel 6820: 	    $filename=$env{'request.filename'};
1.282     albertel 6821: 	}
                   6822: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6823: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6824: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6825: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6826: 
1.927     albertel 6827: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6828: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6829: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6830: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6831: 				     $env{'course.'.$courseid.'.domain'},
                   6832: 				     'course',
1.927     albertel 6833: 				     ([$courselevelm,'map'   ],
                   6834: 				      [$courselevel, 'course']));
                   6835: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6836: 	}
1.145     www      6837: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6838: 	unless ($space eq '0') {
1.336     albertel 6839: 	    my @parts=split(/_/,$space);
                   6840: 	    my $id=pop(@parts);
                   6841: 	    my $part=join('_',@parts);
                   6842: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6843: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6844: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6845: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6846: 	}
1.395     albertel 6847: 	if ($recurse) { return undef; }
                   6848: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6849: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6850: # ---------------------------------------------------- Any other user namespace
                   6851:     } elsif ($realm eq 'environment') {
                   6852: # ----------------------------------------------------------------- environment
1.620     albertel 6853: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6854: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6855: 	} else {
1.770     albertel 6856: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6857: 		return '';
                   6858: 	    }
1.219     albertel 6859: 	    my %returnhash=&userenvironment($udom,$uname,
                   6860: 					    $spacequalifierrest);
                   6861: 	    return $returnhash{$spacequalifierrest};
                   6862: 	}
1.28      www      6863:     } elsif ($realm eq 'system') {
1.48      www      6864: # ----------------------------------------------------------------- system.time
                   6865: 	if ($space eq 'time') {
                   6866: 	    return time;
                   6867:         }
1.696     albertel 6868:     } elsif ($realm eq 'server') {
                   6869: # ----------------------------------------------------------------- system.time
                   6870: 	if ($space eq 'name') {
                   6871: 	    return $ENV{'SERVER_NAME'};
                   6872:         }
1.28      www      6873:     }
1.48      www      6874:     return '';
1.61      www      6875: }
                   6876: 
1.927     albertel 6877: sub get_reply {
                   6878:     my ($reply_value) = @_;
1.940     raeburn  6879:     if (ref($reply_value) eq 'ARRAY') {
                   6880:         if (wantarray) {
                   6881: 	    return @$reply_value;
                   6882:         }
                   6883:         return $reply_value->[0];
                   6884:     } else {
                   6885:         return $reply_value;
1.927     albertel 6886:     }
                   6887: }
                   6888: 
1.691     raeburn  6889: sub check_group_parms {
                   6890:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6891:     my @groupitems = ();
                   6892:     my $resultitem;
1.927     albertel 6893:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6894:     foreach my $group (@{$groups}) {
                   6895:         foreach my $level (@levels) {
1.927     albertel 6896:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6897:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6898:         }
                   6899:     }
                   6900:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6901:                             $env{'course.'.$courseid.'.domain'},
                   6902:                                      'course',@groupitems);
                   6903:     return $coursereply;
                   6904: }
                   6905: 
                   6906: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6907:     my ($courseid,@groups) = @_;
                   6908:     @groups = sort(@groups);
1.691     raeburn  6909:     return @groups;
                   6910: }
                   6911: 
1.395     albertel 6912: sub packages_tab_default {
                   6913:     my ($uri,$varname)=@_;
                   6914:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6915: 
                   6916:     my (@extension,@specifics,$do_default);
                   6917:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6918: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6919: 	if ($pack_type eq 'default') {
                   6920: 	    $do_default=1;
                   6921: 	} elsif ($pack_type eq 'extension') {
                   6922: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6923: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6924: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6925: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6926: 	}
                   6927:     }
                   6928:     # first look for a package that matches the requested part id
                   6929:     foreach my $package (@specifics) {
                   6930: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6931: 	next if ($pack_part ne $part);
                   6932: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6933: 	    return $packagetab{"$pack_type&$name&default"};
                   6934: 	}
                   6935:     }
                   6936:     # look for any possible matching non extension_ package
                   6937:     foreach my $package (@specifics) {
                   6938: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6939: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6940: 	    return $packagetab{"$pack_type&$name&default"};
                   6941: 	}
1.585     albertel 6942: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6943: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6944: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6945: 	}
                   6946:     }
1.738     albertel 6947:     # look for any posible extension_ match
                   6948:     foreach my $package (@extension) {
                   6949: 	my ($package,$pack_type)=@{$package};
                   6950: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6951: 	    return $packagetab{"$pack_type&$name&default"};
                   6952: 	}
                   6953: 	if (defined($packagetab{$package."&$name&default"})) {
                   6954: 	    return $packagetab{$package."&$name&default"};
                   6955: 	}
                   6956:     }
                   6957:     # look for a global default setting
                   6958:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6959: 	return $packagetab{"default&$name&default"};
                   6960:     }
1.395     albertel 6961:     return undef;
                   6962: }
                   6963: 
1.334     albertel 6964: sub add_prefix_and_part {
                   6965:     my ($prefix,$part)=@_;
                   6966:     my $keyroot;
                   6967:     if (defined($prefix) && $prefix !~ /^__/) {
                   6968: 	# prefix that has a part already
                   6969: 	$keyroot=$prefix;
                   6970:     } elsif (defined($prefix)) {
                   6971: 	# prefix that is missing a part
                   6972: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6973:     } else {
                   6974: 	# no prefix at all
                   6975: 	if (defined($part)) { $keyroot='_'.$part; }
                   6976:     }
                   6977:     return $keyroot;
                   6978: }
                   6979: 
1.71      www      6980: # ---------------------------------------------------------------- Get metadata
                   6981: 
1.599     albertel 6982: my %metaentry;
1.71      www      6983: sub metadata {
1.176     www      6984:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6985:     $uri=&declutter($uri);
1.288     albertel 6986:     # if it is a non metadata possible uri return quickly
1.529     albertel 6987:     if (($uri eq '') || 
                   6988: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6989: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6990:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6991: 	return undef;
                   6992:     }
                   6993:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6994: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6995: 	return undef;
1.288     albertel 6996:     }
1.73      www      6997:     my $filename=$uri;
                   6998:     $uri=~s/\.meta$//;
1.172     www      6999: #
                   7000: # Is the metadata already cached?
1.177     www      7001: # Look at timestamp of caching
1.172     www      7002: # Everything is cached by the main uri, libraries are never directly cached
                   7003: #
1.428     albertel 7004:     if (!defined($liburi)) {
1.599     albertel 7005: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7006: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7007:     }
                   7008:     {
1.172     www      7009: #
                   7010: # Is this a recursive call for a library?
                   7011: #
1.599     albertel 7012: #	if (! exists($metacache{$uri})) {
                   7013: #	    $metacache{$uri}={};
                   7014: #	}
1.924     albertel 7015: 	my $cachetime = 60*60;
1.171     www      7016:         if ($liburi) {
                   7017: 	    $liburi=&declutter($liburi);
                   7018:             $filename=$liburi;
1.401     bowersj2 7019:         } else {
1.599     albertel 7020: 	    &devalidate_cache_new('meta',$uri);
                   7021: 	    undef(%metaentry);
1.401     bowersj2 7022: 	}
1.140     www      7023:         my %metathesekeys=();
1.73      www      7024:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7025: 	my $metastring;
1.924     albertel 7026: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7027: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7028: 	    $metastring = 
1.929     albertel 7029: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7030: 					  ('grade_target' => 'meta'));
                   7031: 	    $cachetime = 1; # only want this cached in the child not long term
                   7032: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7033: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7034: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7035: 	    $metastring=&getfile($file);
1.489     albertel 7036: 	}
1.208     albertel 7037:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7038:         my $token;
1.140     www      7039:         undef %metathesekeys;
1.71      www      7040:         while ($token=$parser->get_token) {
1.339     albertel 7041: 	    if ($token->[0] eq 'S') {
                   7042: 		if (defined($token->[2]->{'package'})) {
1.172     www      7043: #
                   7044: # This is a package - get package info
                   7045: #
1.339     albertel 7046: 		    my $package=$token->[2]->{'package'};
                   7047: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7048: 		    if (defined($token->[2]->{'id'})) { 
                   7049: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7050: 		    }
1.599     albertel 7051: 		    if ($metaentry{':packages'}) {
                   7052: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7053: 		    } else {
1.599     albertel 7054: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7055: 		    }
1.736     albertel 7056: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7057: 			my $part=$keyroot;
                   7058: 			$part=~s/^\_//;
1.736     albertel 7059: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7060: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7061: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7062: 			    # ignore package.tab specified default values
                   7063:                             # here &package_tab_default() will fetch those
                   7064: 			    if ($subp eq 'default') { next; }
1.736     albertel 7065: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7066: 			    my $unikey;
                   7067: 			    if ($pack =~ /_0$/) {
                   7068: 				$unikey='parameter_0_'.$name;
                   7069: 				$part=0;
                   7070: 			    } else {
                   7071: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7072: 			    }
1.339     albertel 7073: 			    if ($subp eq 'display') {
                   7074: 				$value.=' [Part: '.$part.']';
                   7075: 			    }
1.599     albertel 7076: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7077: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7078: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7079: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7080: 			    }
1.599     albertel 7081: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7082: 				$metaentry{':'.$unikey}=
                   7083: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7084: 			    }
1.339     albertel 7085: 			}
                   7086: 		    }
                   7087: 		} else {
1.172     www      7088: #
                   7089: # This is not a package - some other kind of start tag
1.339     albertel 7090: #
                   7091: 		    my $entry=$token->[1];
                   7092: 		    my $unikey;
                   7093: 		    if ($entry eq 'import') {
                   7094: 			$unikey='';
                   7095: 		    } else {
                   7096: 			$unikey=$entry;
                   7097: 		    }
                   7098: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7099: 
                   7100: 		    if (defined($token->[2]->{'id'})) { 
                   7101: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7102: 		    }
1.175     www      7103: 
1.339     albertel 7104: 		    if ($entry eq 'import') {
1.175     www      7105: #
                   7106: # Importing a library here
1.339     albertel 7107: #
                   7108: 			if ($depthcount<20) {
                   7109: 			    my $location=$parser->get_text('/import');
                   7110: 			    my $dir=$filename;
                   7111: 			    $dir=~s|[^/]*$||;
                   7112: 			    $location=&filelocation($dir,$location);
1.736     albertel 7113: 			    my $metadata = 
                   7114: 				&metadata($uri,'keys', $location,$unikey,
                   7115: 					  $depthcount+1);
                   7116: 			    foreach my $meta (split(',',$metadata)) {
                   7117: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7118: 				$metathesekeys{$meta}=1;
1.339     albertel 7119: 			    }
                   7120: 			}
                   7121: 		    } else { 
                   7122: 			
                   7123: 			if (defined($token->[2]->{'name'})) { 
                   7124: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7125: 			}
                   7126: 			$metathesekeys{$unikey}=1;
1.736     albertel 7127: 			foreach my $param (@{$token->[3]}) {
                   7128: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7129: 				$token->[2]->{$param};
1.339     albertel 7130: 			}
                   7131: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7132: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7133: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7134: 		 # only ws inside the tag, and not in default, so use default
                   7135: 		 # as value
1.599     albertel 7136: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7137: 			} elsif ( $internaltext =~ /\S/ ) {
                   7138: 		  # something interesting inside the tag
                   7139: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7140: 			} else {
1.908     albertel 7141: 		  # no interesting values, don't set a default
1.339     albertel 7142: 			}
1.172     www      7143: # end of not-a-package not-a-library import
1.339     albertel 7144: 		    }
1.172     www      7145: # end of not-a-package start tag
1.339     albertel 7146: 		}
1.172     www      7147: # the next is the end of "start tag"
1.339     albertel 7148: 	    }
                   7149: 	}
1.483     albertel 7150: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7151: 	$extension = lc($extension);
                   7152: 	if ($extension eq 'htm') { $extension='html'; }
                   7153: 
1.737     albertel 7154: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7155: 	    #no specific packages #how's our extension
                   7156: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7157: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7158: 					 \%metathesekeys);
                   7159: 	}
1.883     albertel 7160: 
                   7161: 	if (!exists($metaentry{':packages'})
                   7162: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7163: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7164: 		#no specific packages well let's get default then
                   7165: 		if ($key!~/^default&/) { next; }
1.488     albertel 7166: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7167: 					     \%metathesekeys);
                   7168: 	    }
                   7169: 	}
1.338     www      7170: # are there custom rights to evaluate
1.599     albertel 7171: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7172: 
1.338     www      7173:     #
                   7174:     # Importing a rights file here
1.339     albertel 7175:     #
                   7176: 	    unless ($depthcount) {
1.599     albertel 7177: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7178: 		my $dir=$filename;
                   7179: 		$dir=~s|[^/]*$||;
                   7180: 		$location=&filelocation($dir,$location);
1.736     albertel 7181: 		my $rights_metadata =
                   7182: 		    &metadata($uri,'keys',$location,'_rights',
                   7183: 			      $depthcount+1);
                   7184: 		foreach my $rights (split(',',$rights_metadata)) {
                   7185: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7186: 		    $metathesekeys{$rights}=1;
1.339     albertel 7187: 		}
                   7188: 	    }
                   7189: 	}
1.737     albertel 7190: 	# uniqifiy package listing
                   7191: 	my %seen;
                   7192: 	my @uniq_packages =
                   7193: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7194: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7195: 
                   7196: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7197: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7198: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7199: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7200: # this is the end of "was not already recently cached
1.71      www      7201:     }
1.599     albertel 7202:     return $metaentry{':'.$what};
1.261     albertel 7203: }
                   7204: 
1.488     albertel 7205: sub metadata_create_package_def {
1.483     albertel 7206:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7207:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7208:     if ($subp eq 'default') { next; }
                   7209:     
1.599     albertel 7210:     if (defined($metaentry{':packages'})) {
                   7211: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7212:     } else {
1.599     albertel 7213: 	$metaentry{':packages'}=$package;
1.483     albertel 7214:     }
                   7215:     my $value=$packagetab{$key};
                   7216:     my $unikey;
                   7217:     $unikey='parameter_0_'.$name;
1.599     albertel 7218:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7219:     $$metathesekeys{$unikey}=1;
1.599     albertel 7220:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7221: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7222:     }
1.599     albertel 7223:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7224: 	$metaentry{':'.$unikey}=
                   7225: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7226:     }
                   7227: }
                   7228: 
1.261     albertel 7229: sub metadata_generate_part0 {
                   7230:     my ($metadata,$metacache,$uri) = @_;
                   7231:     my %allnames;
1.737     albertel 7232:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7233: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7234: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7235: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7236: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7237: 	    $allnames{$name}=$part;
                   7238: 	  }
                   7239: 	}
                   7240:     }
                   7241:     foreach my $name (keys(%allnames)) {
                   7242:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7243:       my $key=":parameter_0_$name";
1.261     albertel 7244:       $$metacache{"$key.part"}='0';
                   7245:       $$metacache{"$key.name"}=$name;
1.428     albertel 7246:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7247: 					   $allnames{$name}.'_'.$name.
                   7248: 					   '.type'};
1.428     albertel 7249:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7250: 			     '.display'};
1.644     www      7251:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7252:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7253:       $$metacache{"$key.display"}=$olddis;
                   7254:     }
1.71      www      7255: }
                   7256: 
1.764     albertel 7257: # ------------------------------------------------------ Devalidate title cache
                   7258: 
                   7259: sub devalidate_title_cache {
                   7260:     my ($url)=@_;
                   7261:     if (!$env{'request.course.id'}) { return; }
                   7262:     my $symb=&symbread($url);
                   7263:     if (!$symb) { return; }
                   7264:     my $key=$env{'request.course.id'}."\0".$symb;
                   7265:     &devalidate_cache_new('title',$key);
                   7266: }
                   7267: 
1.301     www      7268: # ------------------------------------------------- Get the title of a resource
                   7269: 
                   7270: sub gettitle {
                   7271:     my $urlsymb=shift;
                   7272:     my $symb=&symbread($urlsymb);
1.534     albertel 7273:     if ($symb) {
1.620     albertel 7274: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7275: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7276: 	if (defined($cached)) { 
                   7277: 	    return $result;
                   7278: 	}
1.534     albertel 7279: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7280: 	my $title='';
1.907     albertel 7281: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7282: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7283: 	} else {
                   7284: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7285: 		    &GDBM_READER(),0640)) {
                   7286: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7287: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7288: 		untie(%bighash);
                   7289: 	    }
1.534     albertel 7290: 	}
                   7291: 	$title=~s/\&colon\;/\:/gs;
                   7292: 	if ($title) {
1.599     albertel 7293: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7294: 	}
                   7295: 	$urlsymb=$url;
                   7296:     }
                   7297:     my $title=&metadata($urlsymb,'title');
                   7298:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7299:     return $title;
1.301     www      7300: }
1.613     albertel 7301: 
1.614     albertel 7302: sub get_slot {
                   7303:     my ($which,$cnum,$cdom)=@_;
                   7304:     if (!$cnum || !$cdom) {
1.790     albertel 7305: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7306: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7307: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7308:     }
1.703     albertel 7309:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7310:     my %slotinfo;
                   7311:     if (exists($remembered{$key})) {
                   7312: 	$slotinfo{$which} = $remembered{$key};
                   7313:     } else {
                   7314: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7315: 	&Apache::lonhomework::showhash(%slotinfo);
                   7316: 	my ($tmp)=keys(%slotinfo);
                   7317: 	if ($tmp=~/^error:/) { return (); }
                   7318: 	$remembered{$key} = $slotinfo{$which};
                   7319:     }
1.616     albertel 7320:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7321: 	return %{$slotinfo{$which}};
                   7322:     }
                   7323:     return $slotinfo{$which};
1.614     albertel 7324: }
1.31      www      7325: # ------------------------------------------------- Update symbolic store links
                   7326: 
                   7327: sub symblist {
                   7328:     my ($mapname,%newhash)=@_;
1.438     www      7329:     $mapname=&deversion(&declutter($mapname));
1.31      www      7330:     my %hash;
1.620     albertel 7331:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7332:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7333:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7334: 	    foreach my $url (keys %newhash) {
                   7335: 		next if ($url eq 'last_known'
                   7336: 			 && $env{'form.no_update_last_known'});
                   7337: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7338: 						    $newhash{$url}->[1],
                   7339: 						    $newhash{$url}->[0]);
1.191     harris41 7340:             }
1.31      www      7341:             if (untie(%hash)) {
                   7342: 		return 'ok';
                   7343:             }
                   7344:         }
                   7345:     }
                   7346:     return 'error';
1.212     www      7347: }
                   7348: 
                   7349: # --------------------------------------------------------------- Verify a symb
                   7350: 
                   7351: sub symbverify {
1.510     www      7352:     my ($symb,$thisurl)=@_;
                   7353:     my $thisfn=$thisurl;
1.439     www      7354:     $thisfn=&declutter($thisfn);
1.215     www      7355: # direct jump to resource in page or to a sequence - will construct own symbs
                   7356:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7357: # check URL part
1.409     www      7358:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7359: 
1.431     www      7360:     unless ($url eq $thisfn) { return 0; }
1.213     www      7361: 
1.216     www      7362:     $symb=&symbclean($symb);
1.510     www      7363:     $thisurl=&deversion($thisurl);
1.439     www      7364:     $thisfn=&deversion($thisfn);
1.213     www      7365: 
                   7366:     my %bighash;
                   7367:     my $okay=0;
1.431     www      7368: 
1.620     albertel 7369:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7370:                             &GDBM_READER(),0640)) {
1.510     www      7371:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7372:         unless ($ids) { 
1.510     www      7373:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7374:         }
                   7375:         if ($ids) {
                   7376: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7377: 	    foreach my $id (split(/\,/,$ids)) {
                   7378: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7379:                if (
                   7380:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7381:    eq $symb) { 
1.620     albertel 7382: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7383: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7384: 		       $okay=1; 
                   7385: 		   }
                   7386: 	       }
1.216     www      7387: 	   }
                   7388:         }
1.213     www      7389: 	untie(%bighash);
                   7390:     }
                   7391:     return $okay;
1.31      www      7392: }
                   7393: 
1.210     www      7394: # --------------------------------------------------------------- Clean-up symb
                   7395: 
                   7396: sub symbclean {
                   7397:     my $symb=shift;
1.568     albertel 7398:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7399: # remove version from map
                   7400:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7401: 
1.210     www      7402: # remove version from URL
                   7403:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7404: 
1.507     www      7405: # remove wrapper
                   7406: 
1.510     www      7407:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7408:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7409:     return $symb;
1.409     www      7410: }
                   7411: 
                   7412: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7413: 
                   7414: sub encode_symb {
                   7415:     my ($map,$resid,$url)=@_;
                   7416:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7417: }
1.409     www      7418: 
                   7419: sub decode_symb {
1.568     albertel 7420:     my $symb=shift;
                   7421:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7422:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7423:     return (&fixversion($map),$resid,&fixversion($url));
                   7424: }
                   7425: 
                   7426: sub fixversion {
                   7427:     my $fn=shift;
1.609     banghart 7428:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7429:     my %bighash;
                   7430:     my $uri=&clutter($fn);
1.620     albertel 7431:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7432: # is this cached?
1.599     albertel 7433:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7434:     if (defined($cached)) { return $result; }
                   7435: # unfortunately not cached, or expired
1.620     albertel 7436:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7437: 	    &GDBM_READER(),0640)) {
                   7438:  	if ($bighash{'version_'.$uri}) {
                   7439:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7440:  	    unless (($version eq 'mostrecent') || 
                   7441: 		    ($version==&getversion($uri))) {
1.440     www      7442:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7443:  	    }
                   7444:  	}
                   7445:  	untie %bighash;
1.413     www      7446:     }
1.599     albertel 7447:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7448: }
                   7449: 
                   7450: sub deversion {
                   7451:     my $url=shift;
                   7452:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7453:     return $url;
1.210     www      7454: }
                   7455: 
1.31      www      7456: # ------------------------------------------------------ Return symb list entry
                   7457: 
                   7458: sub symbread {
1.249     www      7459:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7460:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7461:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7462: # no filename provided? try from environment
1.44      www      7463:     unless ($thisfn) {
1.620     albertel 7464:         if ($env{'request.symb'}) {
                   7465: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7466: 	}
1.620     albertel 7467: 	$thisfn=$env{'request.filename'};
1.44      www      7468:     }
1.569     albertel 7469:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7470: # is that filename actually a symb? Verify, clean, and return
                   7471:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7472: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7473: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7474: 	}
1.242     www      7475:     }
1.44      www      7476:     $thisfn=declutter($thisfn);
1.31      www      7477:     my %hash;
1.37      www      7478:     my %bighash;
                   7479:     my $syval='';
1.620     albertel 7480:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7481:         my $targetfn = $thisfn;
1.609     banghart 7482:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7483:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7484:         }
1.687     albertel 7485: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7486: 	    $targetfn=$1;
                   7487: 	}
1.620     albertel 7488:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7489:                       &GDBM_READER(),0640)) {
1.481     raeburn  7490: 	    $syval=$hash{$targetfn};
1.37      www      7491:             untie(%hash);
                   7492:         }
                   7493: # ---------------------------------------------------------- There was an entry
                   7494:         if ($syval) {
1.601     albertel 7495: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7496: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7497: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7498: 		    #return $env{$cache_str}='';
1.601     albertel 7499: 		#}    
                   7500: 		#$syval.=$1;
                   7501: 	    #}
1.37      www      7502:         } else {
                   7503: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7504:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7505:                             &GDBM_READER(),0640)) {
1.37      www      7506: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7507:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7508:               unless ($ids) { 
                   7509:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7510:               }
                   7511:               unless ($ids) {
                   7512: # alias?
                   7513: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7514:               }
1.37      www      7515:               if ($ids) {
                   7516: # ------------------------------------------------------------------- Has ID(s)
                   7517:                  my @possibilities=split(/\,/,$ids);
1.39      www      7518:                  if ($#possibilities==0) {
                   7519: # ----------------------------------------------- There is only one possibility
1.37      www      7520: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7521: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7522: 						    $resid,$thisfn);
1.249     www      7523:                  } elsif (!$donotrecurse) {
1.39      www      7524: # ------------------------------------------ There is more than one possibility
                   7525:                      my $realpossible=0;
1.800     albertel 7526:                      foreach my $id (@possibilities) {
                   7527: 			 my $file=$bighash{'src_'.$id};
1.39      www      7528:                          if (&allowed('bre',$file)) {
1.800     albertel 7529:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7530:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7531: 				$realpossible++;
1.626     albertel 7532:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7533: 						    $resid,$thisfn);
1.39      www      7534:                             }
                   7535: 			 }
1.191     harris41 7536:                      }
1.39      www      7537: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7538:                  } else {
                   7539:                      $syval='';
1.37      www      7540:                  }
                   7541: 	      }
                   7542:               untie(%bighash)
1.481     raeburn  7543:            }
1.31      www      7544:         }
1.62      www      7545:         if ($syval) {
1.620     albertel 7546: 	    return $env{$cache_str}=$syval;
1.62      www      7547:         }
1.31      www      7548:     }
1.949     raeburn  7549:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7550:     return $env{$cache_str}='';
1.31      www      7551: }
                   7552: 
                   7553: # ---------------------------------------------------------- Return random seed
                   7554: 
1.32      www      7555: sub numval {
                   7556:     my $txt=shift;
                   7557:     $txt=~tr/A-J/0-9/;
                   7558:     $txt=~tr/a-j/0-9/;
                   7559:     $txt=~tr/K-T/0-9/;
                   7560:     $txt=~tr/k-t/0-9/;
                   7561:     $txt=~tr/U-Z/0-5/;
                   7562:     $txt=~tr/u-z/0-5/;
                   7563:     $txt=~s/\D//g;
1.564     albertel 7564:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7565:     return int($txt);
1.368     albertel 7566: }
                   7567: 
1.484     albertel 7568: sub numval2 {
                   7569:     my $txt=shift;
                   7570:     $txt=~tr/A-J/0-9/;
                   7571:     $txt=~tr/a-j/0-9/;
                   7572:     $txt=~tr/K-T/0-9/;
                   7573:     $txt=~tr/k-t/0-9/;
                   7574:     $txt=~tr/U-Z/0-5/;
                   7575:     $txt=~tr/u-z/0-5/;
                   7576:     $txt=~s/\D//g;
                   7577:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7578:     my $total;
                   7579:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7580:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7581:     return int($total);
                   7582: }
                   7583: 
1.575     albertel 7584: sub numval3 {
                   7585:     use integer;
                   7586:     my $txt=shift;
                   7587:     $txt=~tr/A-J/0-9/;
                   7588:     $txt=~tr/a-j/0-9/;
                   7589:     $txt=~tr/K-T/0-9/;
                   7590:     $txt=~tr/k-t/0-9/;
                   7591:     $txt=~tr/U-Z/0-5/;
                   7592:     $txt=~tr/u-z/0-5/;
                   7593:     $txt=~s/\D//g;
                   7594:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7595:     my $total;
                   7596:     foreach my $val (@txts) { $total+=$val; }
                   7597:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7598:     return $total;
                   7599: }
                   7600: 
1.675     albertel 7601: sub digest {
                   7602:     my ($data)=@_;
                   7603:     my $digest=&Digest::MD5::md5($data);
                   7604:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7605:     my ($e,$f);
                   7606:     {
                   7607:         use integer;
                   7608:         $e=($a+$b);
                   7609:         $f=($c+$d);
                   7610:         if ($_64bit) {
                   7611:             $e=(($e<<32)>>32);
                   7612:             $f=(($f<<32)>>32);
                   7613:         }
                   7614:     }
                   7615:     if (wantarray) {
                   7616: 	return ($e,$f);
                   7617:     } else {
                   7618: 	my $g;
                   7619: 	{
                   7620: 	    use integer;
                   7621: 	    $g=($e+$f);
                   7622: 	    if ($_64bit) {
                   7623: 		$g=(($g<<32)>>32);
                   7624: 	    }
                   7625: 	}
                   7626: 	return $g;
                   7627:     }
                   7628: }
                   7629: 
1.368     albertel 7630: sub latest_rnd_algorithm_id {
1.675     albertel 7631:     return '64bit5';
1.366     albertel 7632: }
1.32      www      7633: 
1.503     albertel 7634: sub get_rand_alg {
                   7635:     my ($courseid)=@_;
1.790     albertel 7636:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7637:     if ($courseid) {
1.620     albertel 7638: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7639:     }
                   7640:     return &latest_rnd_algorithm_id();
                   7641: }
                   7642: 
1.562     albertel 7643: sub validCODE {
                   7644:     my ($CODE)=@_;
                   7645:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7646:     return 0;
                   7647: }
                   7648: 
1.491     albertel 7649: sub getCODE {
1.620     albertel 7650:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7651:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7652: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7653: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7654: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7655:     }
                   7656:     return undef;
                   7657: }
                   7658: 
1.31      www      7659: sub rndseed {
1.155     albertel 7660:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7661:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7662:     if (!defined($symb)) {
1.366     albertel 7663: 	unless ($symb=$wsymb) { return time; }
                   7664:     }
                   7665:     if (!$courseid) { $courseid=$wcourseid; }
                   7666:     if (!$domain) { $domain=$wdomain; }
                   7667:     if (!$username) { $username=$wusername }
1.503     albertel 7668:     my $which=&get_rand_alg();
1.803     albertel 7669: 
1.491     albertel 7670:     if (defined(&getCODE())) {
1.675     albertel 7671: 	if ($which eq '64bit5') {
                   7672: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7673: 	} elsif ($which eq '64bit4') {
1.575     albertel 7674: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7675: 	} else {
                   7676: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7677: 	}
1.675     albertel 7678:     } elsif ($which eq '64bit5') {
                   7679: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7680:     } elsif ($which eq '64bit4') {
                   7681: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7682:     } elsif ($which eq '64bit3') {
                   7683: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7684:     } elsif ($which eq '64bit2') {
                   7685: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7686:     } elsif ($which eq '64bit') {
                   7687: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7688:     }
                   7689:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7690: }
                   7691: 
                   7692: sub rndseed_32bit {
                   7693:     my ($symb,$courseid,$domain,$username)=@_;
                   7694:     {
                   7695: 	use integer;
                   7696: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7697: 	my $symbseed=numval($symb) << 22;
                   7698: 	my $namechck=unpack("%32C*",$username) << 17;
                   7699: 	my $nameseed=numval($username) << 12;
                   7700: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7701: 	my $courseseed=unpack("%32C*",$courseid);
                   7702: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7703: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7704: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7705: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7706: 	return $num;
                   7707:     }
                   7708: }
                   7709: 
                   7710: sub rndseed_64bit {
                   7711:     my ($symb,$courseid,$domain,$username)=@_;
                   7712:     {
                   7713: 	use integer;
                   7714: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7715: 	my $symbseed=numval($symb) << 10;
                   7716: 	my $namechck=unpack("%32S*",$username);
                   7717: 	
                   7718: 	my $nameseed=numval($username) << 21;
                   7719: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7720: 	my $courseseed=unpack("%32S*",$courseid);
                   7721: 	
                   7722: 	my $num1=$symbchck+$symbseed+$namechck;
                   7723: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7724: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7725: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7726: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7727: 	return "$num1,$num2";
1.155     albertel 7728:     }
1.366     albertel 7729: }
                   7730: 
1.443     albertel 7731: sub rndseed_64bit2 {
                   7732:     my ($symb,$courseid,$domain,$username)=@_;
                   7733:     {
                   7734: 	use integer;
                   7735: 	# strings need to be an even # of cahracters long, it it is odd the
                   7736:         # last characters gets thrown away
                   7737: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7738: 	my $symbseed=numval($symb) << 10;
                   7739: 	my $namechck=unpack("%32S*",$username.' ');
                   7740: 	
                   7741: 	my $nameseed=numval($username) << 21;
1.501     albertel 7742: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7743: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7744: 	
                   7745: 	my $num1=$symbchck+$symbseed+$namechck;
                   7746: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7747: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7748: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7749: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7750: 	return "$num1,$num2";
                   7751:     }
                   7752: }
                   7753: 
                   7754: sub rndseed_64bit3 {
                   7755:     my ($symb,$courseid,$domain,$username)=@_;
                   7756:     {
                   7757: 	use integer;
                   7758: 	# strings need to be an even # of cahracters long, it it is odd the
                   7759:         # last characters gets thrown away
                   7760: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7761: 	my $symbseed=numval2($symb) << 10;
                   7762: 	my $namechck=unpack("%32S*",$username.' ');
                   7763: 	
                   7764: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7765: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7766: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7767: 	
                   7768: 	my $num1=$symbchck+$symbseed+$namechck;
                   7769: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7770: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7771: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7772: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7773: 	
1.503     albertel 7774: 	return "$num1:$num2";
1.443     albertel 7775:     }
                   7776: }
                   7777: 
1.575     albertel 7778: sub rndseed_64bit4 {
                   7779:     my ($symb,$courseid,$domain,$username)=@_;
                   7780:     {
                   7781: 	use integer;
                   7782: 	# strings need to be an even # of cahracters long, it it is odd the
                   7783:         # last characters gets thrown away
                   7784: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7785: 	my $symbseed=numval3($symb) << 10;
                   7786: 	my $namechck=unpack("%32S*",$username.' ');
                   7787: 	
                   7788: 	my $nameseed=numval3($username) << 21;
                   7789: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7790: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7791: 	
                   7792: 	my $num1=$symbchck+$symbseed+$namechck;
                   7793: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7794: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7795: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7796: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7797: 	
                   7798: 	return "$num1:$num2";
                   7799:     }
                   7800: }
                   7801: 
1.675     albertel 7802: sub rndseed_64bit5 {
                   7803:     my ($symb,$courseid,$domain,$username)=@_;
                   7804:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7805:     return "$num1:$num2";
                   7806: }
                   7807: 
1.366     albertel 7808: sub rndseed_CODE_64bit {
                   7809:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7810:     {
1.366     albertel 7811: 	use integer;
1.443     albertel 7812: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7813: 	my $symbseed=numval2($symb);
1.491     albertel 7814: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7815: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7816: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7817: 	my $num1=$symbseed+$CODEchck;
                   7818: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7819: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7820: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7821: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7822: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7823: 	return "$num1:$num2";
1.366     albertel 7824:     }
                   7825: }
                   7826: 
1.575     albertel 7827: sub rndseed_CODE_64bit4 {
                   7828:     my ($symb,$courseid,$domain,$username)=@_;
                   7829:     {
                   7830: 	use integer;
                   7831: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7832: 	my $symbseed=numval3($symb);
                   7833: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7834: 	my $CODEseed=numval3(&getCODE());
                   7835: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7836: 	my $num1=$symbseed+$CODEchck;
                   7837: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7838: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7839: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7840: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7841: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7842: 	return "$num1:$num2";
                   7843:     }
                   7844: }
                   7845: 
1.675     albertel 7846: sub rndseed_CODE_64bit5 {
                   7847:     my ($symb,$courseid,$domain,$username)=@_;
                   7848:     my $code = &getCODE();
                   7849:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7850:     return "$num1:$num2";
                   7851: }
                   7852: 
1.366     albertel 7853: sub setup_random_from_rndseed {
                   7854:     my ($rndseed)=@_;
1.503     albertel 7855:     if ($rndseed =~/([,:])/) {
                   7856: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7857: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7858:     } else {
                   7859: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7860:     }
1.36      albertel 7861: }
                   7862: 
1.474     albertel 7863: sub latest_receipt_algorithm_id {
1.835     albertel 7864:     return 'receipt3';
1.474     albertel 7865: }
                   7866: 
1.480     www      7867: sub recunique {
                   7868:     my $fucourseid=shift;
                   7869:     my $unique;
1.835     albertel 7870:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7871: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7872: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7873:     } else {
                   7874: 	$unique=$perlvar{'lonReceipt'};
                   7875:     }
                   7876:     return unpack("%32C*",$unique);
                   7877: }
                   7878: 
                   7879: sub recprefix {
                   7880:     my $fucourseid=shift;
                   7881:     my $prefix;
1.835     albertel 7882:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7883: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7884: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7885:     } else {
                   7886: 	$prefix=$perlvar{'lonHostID'};
                   7887:     }
                   7888:     return unpack("%32C*",$prefix);
                   7889: }
                   7890: 
1.76      www      7891: sub ireceipt {
1.474     albertel 7892:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7893: 
                   7894:     my $return =&recprefix($fucourseid).'-';
                   7895: 
                   7896:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7897: 	$env{'request.state'} eq 'construct') {
                   7898: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7899: 	return $return;
                   7900:     }
                   7901: 
1.76      www      7902:     my $cuname=unpack("%32C*",$funame);
                   7903:     my $cudom=unpack("%32C*",$fudom);
                   7904:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7905:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7906:     my $cunique=&recunique($fucourseid);
1.474     albertel 7907:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7908:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7909: 
1.790     albertel 7910: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7911: 			       
                   7912: 	$return.= ($cunique%$cuname+
                   7913: 		   $cunique%$cudom+
                   7914: 		   $cusymb%$cuname+
                   7915: 		   $cusymb%$cudom+
                   7916: 		   $cucourseid%$cuname+
                   7917: 		   $cucourseid%$cudom+
                   7918: 		   $cpart%$cuname+
                   7919: 		   $cpart%$cudom);
                   7920:     } else {
                   7921: 	$return.= ($cunique%$cuname+
                   7922: 		   $cunique%$cudom+
                   7923: 		   $cusymb%$cuname+
                   7924: 		   $cusymb%$cudom+
                   7925: 		   $cucourseid%$cuname+
                   7926: 		   $cucourseid%$cudom);
                   7927:     }
                   7928:     return $return;
1.76      www      7929: }
                   7930: 
                   7931: sub receipt {
1.474     albertel 7932:     my ($part)=@_;
1.790     albertel 7933:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7934:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7935: }
1.260     ng       7936: 
1.790     albertel 7937: sub whichuser {
                   7938:     my ($passedsymb)=@_;
                   7939:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7940:     if (defined($env{'form.grade_symb'})) {
                   7941: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7942: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7943: 	if (!$allowed &&
                   7944: 	    exists($env{'request.course.sec'}) &&
                   7945: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7946: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7947: 			      '/'.$env{'request.course.sec'});
                   7948: 	}
                   7949: 	if ($allowed) {
                   7950: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7951: 	    $courseid=$tmp_courseid;
                   7952: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7953: 	    ($name)=&get_env_multiple('form.grade_username');
                   7954: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7955: 	}
                   7956:     }
                   7957:     if (!$passedsymb) {
                   7958: 	$symb=&symbread();
                   7959:     } else {
                   7960: 	$symb=$passedsymb;
                   7961:     }
                   7962:     $courseid=$env{'request.course.id'};
                   7963:     $domain=$env{'user.domain'};
                   7964:     $name=$env{'user.name'};
                   7965:     if ($name eq 'public' && $domain eq 'public') {
                   7966: 	if (!defined($env{'form.username'})) {
                   7967: 	    $env{'form.username'}.=time.rand(10000000);
                   7968: 	}
                   7969: 	$name.=$env{'form.username'};
                   7970:     }
                   7971:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7972: 
                   7973: }
                   7974: 
1.36      albertel 7975: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7976: # returns either the contents of the file or 
                   7977: # -1 if the file doesn't exist
1.481     raeburn  7978: #
                   7979: # if the target is a file that was uploaded via DOCS, 
                   7980: # a check will be made to see if a current copy exists on the local server,
                   7981: # if it does this will be served, otherwise a copy will be retrieved from
                   7982: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7983: # the local server.   
1.472     albertel 7984: 
1.36      albertel 7985: sub getfile {
1.538     albertel 7986:     my ($file) = @_;
1.609     banghart 7987:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7988:     &repcopy($file);
                   7989:     return &readfile($file);
                   7990: }
                   7991: 
                   7992: sub repcopy_userfile {
                   7993:     my ($file)=@_;
1.609     banghart 7994:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7995:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7996:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7997: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7998:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7999:     if (-e "$file") {
1.828     www      8000: # we already have a local copy, check it out
1.538     albertel 8001: 	my @fileinfo = stat($file);
1.828     www      8002: 	my $rtncode;
                   8003: 	my $info;
1.538     albertel 8004: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8005: 	if ($lwpresp ne 'ok') {
1.828     www      8006: # there is no such file anymore, even though we had a local copy
1.482     albertel 8007: 	    if ($rtncode eq '404') {
1.538     albertel 8008: 		unlink($file);
1.482     albertel 8009: 	    }
                   8010: 	    return -1;
                   8011: 	}
                   8012: 	if ($info < $fileinfo[9]) {
1.828     www      8013: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8014: 	    return 'ok';
1.828     www      8015: 	} else {
                   8016: # the file is outdated, get rid of it
                   8017: 	    unlink($file);
1.482     albertel 8018: 	}
1.828     www      8019:     }
                   8020: # one way or the other, at this point, we don't have the file
                   8021: # construct the correct path for the file
                   8022:     my @parts = ($cdom,$cnum); 
                   8023:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8024: 	push @parts, split(/\//,$1);
                   8025:     }
                   8026:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8027:     foreach my $part (@parts) {
                   8028: 	$path .= '/'.$part;
                   8029: 	if (!-e $path) {
                   8030: 	    mkdir($path,0770);
1.482     albertel 8031: 	}
                   8032:     }
1.828     www      8033: # now the path exists for sure
                   8034: # get a user agent
                   8035:     my $ua=new LWP::UserAgent;
                   8036:     my $transferfile=$file.'.in.transfer';
                   8037: # FIXME: this should flock
                   8038:     if (-e $transferfile) { return 'ok'; }
                   8039:     my $request;
                   8040:     $uri=~s/^\///;
1.838     albertel 8041:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8042:     my $response=$ua->request($request,$transferfile);
                   8043: # did it work?
                   8044:     if ($response->is_error()) {
                   8045: 	unlink($transferfile);
                   8046: 	&logthis("Userfile repcopy failed for $uri");
                   8047: 	return -1;
                   8048:     }
                   8049: # worked, rename the transfer file
                   8050:     rename($transferfile,$file);
1.607     raeburn  8051:     return 'ok';
1.481     raeburn  8052: }
                   8053: 
1.517     albertel 8054: sub tokenwrapper {
                   8055:     my $uri=shift;
1.552     albertel 8056:     $uri=~s|^http\://([^/]+)||;
                   8057:     $uri=~s|^/||;
1.620     albertel 8058:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8059:     my $token=$1;
1.552     albertel 8060:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8061:     if ($udom && $uname && $file) {
                   8062: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8063:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8064:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8065:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8066:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8067:     } else {
                   8068:         return '/adm/notfound.html';
                   8069:     }
                   8070: }
                   8071: 
1.828     www      8072: # call with reqtype HEAD: get last modification time
                   8073: # call with reqtype GET: get the file contents
                   8074: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8075: #
1.481     raeburn  8076: sub getuploaded {
                   8077:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8078:     $uri=~s/^\///;
1.838     albertel 8079:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8080:     my $ua=new LWP::UserAgent;
                   8081:     my $request=new HTTP::Request($reqtype,$uri);
                   8082:     my $response=$ua->request($request);
                   8083:     $$rtncode = $response->code;
1.482     albertel 8084:     if (! $response->is_success()) {
                   8085: 	return 'failed';
                   8086:     }      
                   8087:     if ($reqtype eq 'HEAD') {
1.486     www      8088: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8089:     } elsif ($reqtype eq 'GET') {
                   8090: 	$$info = $response->content;
1.472     albertel 8091:     }
1.482     albertel 8092:     return 'ok';
1.36      albertel 8093: }
                   8094: 
1.481     raeburn  8095: sub readfile {
                   8096:     my $file = shift;
                   8097:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8098:     my $fh;
                   8099:     open($fh,"<$file");
                   8100:     my $a='';
1.800     albertel 8101:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8102:     return $a;
                   8103: }
                   8104: 
1.36      albertel 8105: sub filelocation {
1.590     banghart 8106:     my ($dir,$file) = @_;
                   8107:     my $location;
                   8108:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8109: 
                   8110:     if ($file =~ m-^/adm/-) {
                   8111: 	$file=~s-^/adm/wrapper/-/-;
                   8112: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8113:     }
1.882     albertel 8114: 
1.590     banghart 8115:     if ($file=~m:^/~:) { # is a contruction space reference
                   8116:         $location = $file;
                   8117:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8118:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8119: 	# is a correct contruction space reference
                   8120:         $location = $file;
1.609     banghart 8121:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8122:         my ($udom,$uname,$filename)=
1.811     albertel 8123:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8124:         my $home=&homeserver($uname,$udom);
                   8125:         my $is_me=0;
                   8126:         my @ids=&current_machine_ids();
                   8127:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8128:         if ($is_me) {
1.955   ! raeburn  8129:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8130:         } else {
                   8131:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8132:   	      $udom.'/'.$uname.'/'.$filename;
                   8133:         }
1.882     albertel 8134:     } elsif ($file =~ m-^/adm/-) {
                   8135: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8136:     } else {
                   8137:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8138:         $file=~s:^/res/:/:;
                   8139:         if ( !( $file =~ m:^/:) ) {
                   8140:             $location = $dir. '/'.$file;
                   8141:         } else {
                   8142:             $location = '/home/httpd/html/res'.$file;
                   8143:         }
1.59      albertel 8144:     }
1.590     banghart 8145:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8146:     while ($location=~m{/\.\./}) {
                   8147: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8148: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8149: 	} else {
                   8150: 	    $location=~ s{/\.\./}{/}g;
                   8151: 	}
                   8152:     } #remove dir/..
1.590     banghart 8153:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8154:     return $location;
1.46      www      8155: }
1.36      albertel 8156: 
1.46      www      8157: sub hreflocation {
                   8158:     my ($dir,$file)=@_;
1.460     albertel 8159:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8160: 	$file=filelocation($dir,$file);
1.700     albertel 8161:     } elsif ($file=~m-^/adm/-) {
                   8162: 	$file=~s-^/adm/wrapper/-/-;
                   8163: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8164:     }
                   8165:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8166: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8167:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8168: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8169:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8170: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8171: 	    -/uploaded/$1/$2/-x;
1.46      www      8172:     }
1.913     albertel 8173:     if ($file=~ m{^/userfiles/}) {
                   8174: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8175:     }
1.462     albertel 8176:     return $file;
1.465     albertel 8177: }
                   8178: 
                   8179: sub current_machine_domains {
1.853     albertel 8180:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8181: }
                   8182: 
                   8183: sub machine_domains {
                   8184:     my ($hostname) = @_;
1.465     albertel 8185:     my @domains;
1.838     albertel 8186:     my %hostname = &all_hostnames();
1.465     albertel 8187:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8188: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8189: 	if ($hostname eq $name) {
1.844     albertel 8190: 	    push(@domains,&host_domain($id));
1.465     albertel 8191: 	}
                   8192:     }
                   8193:     return @domains;
                   8194: }
                   8195: 
                   8196: sub current_machine_ids {
1.853     albertel 8197:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8198: }
                   8199: 
                   8200: sub machine_ids {
                   8201:     my ($hostname) = @_;
                   8202:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8203:     my @ids;
1.888     albertel 8204:     my %name_to_host = &all_names();
1.889     albertel 8205:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8206: 	return @{ $name_to_host{$hostname} };
                   8207:     }
                   8208:     return;
1.31      www      8209: }
                   8210: 
1.824     raeburn  8211: sub additional_machine_domains {
                   8212:     my @domains;
                   8213:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8214:     while( my $line = <$fh>) {
                   8215:         $line =~ s/\s//g;
                   8216:         push(@domains,$line);
                   8217:     }
                   8218:     return @domains;
                   8219: }
                   8220: 
                   8221: sub default_login_domain {
                   8222:     my $domain = $perlvar{'lonDefDomain'};
                   8223:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8224:     foreach my $posdom (&current_machine_domains(),
                   8225:                         &additional_machine_domains()) {
                   8226:         if (lc($posdom) eq lc($testdomain)) {
                   8227:             $domain=$posdom;
                   8228:             last;
                   8229:         }
                   8230:     }
                   8231:     return $domain;
                   8232: }
                   8233: 
1.31      www      8234: # ------------------------------------------------------------- Declutters URLs
                   8235: 
                   8236: sub declutter {
                   8237:     my $thisfn=shift;
1.569     albertel 8238:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8239:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8240:     $thisfn=~s/^\///;
1.697     albertel 8241:     $thisfn=~s|^adm/wrapper/||;
                   8242:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8243:     $thisfn=~s/^res\///;
1.235     www      8244:     $thisfn=~s/\?.+$//;
1.268     www      8245:     return $thisfn;
                   8246: }
                   8247: 
                   8248: # ------------------------------------------------------------- Clutter up URLs
                   8249: 
                   8250: sub clutter {
                   8251:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8252:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8253: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8254:        $thisfn='/res'.$thisfn; 
                   8255:     }
1.694     albertel 8256:     if ($thisfn !~m|/adm|) {
1.695     albertel 8257: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8258: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8259: 	} else {
                   8260: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8261: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8262: 	    if ($embstyle eq 'ssi'
                   8263: 		|| ($embstyle eq 'hdn')
                   8264: 		|| ($embstyle eq 'rat')
                   8265: 		|| ($embstyle eq 'prv')
                   8266: 		|| ($embstyle eq 'ign')) {
                   8267: 		#do nothing with these
                   8268: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8269: 		|| ($embstyle eq 'emb')
                   8270: 		|| ($embstyle eq 'wrp')) {
                   8271: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8272: 	    } elsif ($embstyle eq 'unk'
                   8273: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8274: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8275: 	    } else {
1.718     www      8276: #		&logthis("Got a blank emb style");
1.695     albertel 8277: 	    }
1.694     albertel 8278: 	}
                   8279:     }
1.31      www      8280:     return $thisfn;
1.12      www      8281: }
                   8282: 
1.787     albertel 8283: sub clutter_with_no_wrapper {
                   8284:     my $uri = &clutter(shift);
                   8285:     if ($uri =~ m-^/adm/-) {
                   8286: 	$uri =~ s-^/adm/wrapper/-/-;
                   8287: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8288:     }
                   8289:     return $uri;
                   8290: }
                   8291: 
1.557     albertel 8292: sub freeze_escape {
                   8293:     my ($value)=@_;
                   8294:     if (ref($value)) {
                   8295: 	$value=&nfreeze($value);
                   8296: 	return '__FROZEN__'.&escape($value);
                   8297:     }
                   8298:     return &escape($value);
                   8299: }
                   8300: 
1.11      www      8301: 
1.557     albertel 8302: sub thaw_unescape {
                   8303:     my ($value)=@_;
                   8304:     if ($value =~ /^__FROZEN__/) {
                   8305: 	substr($value,0,10,undef);
                   8306: 	$value=&unescape($value);
                   8307: 	return &thaw($value);
                   8308:     }
                   8309:     return &unescape($value);
                   8310: }
                   8311: 
1.436     albertel 8312: sub correct_line_ends {
                   8313:     my ($result)=@_;
                   8314:     $$result =~s/\r\n/\n/mg;
                   8315:     $$result =~s/\r/\n/mg;
1.415     albertel 8316: }
1.1       albertel 8317: # ================================================================ Main Program
                   8318: 
1.184     www      8319: sub goodbye {
1.204     albertel 8320:    &logthis("Starting Shut down");
1.443     albertel 8321: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8322:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8323: #converted
1.599     albertel 8324: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8325:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8326: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8327: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8328: #1.1 only
1.870     albertel 8329: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8330: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8331: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8332: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8333:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8334:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8335:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8336:    &flushcourselogs();
                   8337:    &logthis("Shutting down");
                   8338: }
                   8339: 
1.852     albertel 8340: sub get_dns {
1.869     albertel 8341:     my ($url,$func,$ignore_cache) = @_;
                   8342:     if (!$ignore_cache) {
                   8343: 	my ($content,$cached)=
                   8344: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8345: 	if ($cached) {
                   8346: 	    &$func($content);
                   8347: 	    return;
                   8348: 	}
                   8349:     }
                   8350: 
                   8351:     my %alldns;
1.852     albertel 8352:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8353:     foreach my $dns (<$config>) {
                   8354: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8355: 	$alldns{$1} = 1;
                   8356:     }
                   8357:     while (%alldns) {
                   8358: 	my ($dns) = keys(%alldns);
                   8359: 	delete($alldns{$dns});
1.852     albertel 8360: 	my $ua=new LWP::UserAgent;
                   8361: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8362: 	my $response=$ua->request($request);
                   8363: 	next if ($response->is_error());
                   8364: 	my @content = split("\n",$response->content);
1.869     albertel 8365: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8366: 	&$func(\@content);
1.869     albertel 8367: 	return;
1.852     albertel 8368:     }
                   8369:     close($config);
1.871     albertel 8370:     my $which = (split('/',$url))[3];
                   8371:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8372:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8373:     my @content = <$config>;
                   8374:     &$func(\@content);
                   8375:     return;
1.852     albertel 8376: }
1.327     albertel 8377: # ------------------------------------------------------------ Read domain file
                   8378: {
1.852     albertel 8379:     my $loaded;
1.846     albertel 8380:     my %domain;
                   8381: 
1.852     albertel 8382:     sub parse_domain_tab {
                   8383: 	my ($lines) = @_;
                   8384: 	foreach my $line (@$lines) {
                   8385: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8386: 
1.846     albertel 8387: 	    chomp($line);
1.852     albertel 8388: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8389: 	    my %this_domain;
                   8390: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8391: 			       'lang_def', 'city', 'longi', 'lati',
                   8392: 			       'primary') {
                   8393: 		$this_domain{$field} = shift(@elements);
                   8394: 	    }
                   8395: 	    $domain{$name} = \%this_domain;
1.852     albertel 8396: 	}
                   8397:     }
1.864     albertel 8398: 
                   8399:     sub reset_domain_info {
                   8400: 	undef($loaded);
                   8401: 	undef(%domain);
                   8402:     }
                   8403: 
1.852     albertel 8404:     sub load_domain_tab {
1.869     albertel 8405: 	my ($ignore_cache) = @_;
                   8406: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8407: 	my $fh;
                   8408: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8409: 	    my @lines = <$fh>;
                   8410: 	    &parse_domain_tab(\@lines);
1.448     albertel 8411: 	}
1.852     albertel 8412: 	close($fh);
                   8413: 	$loaded = 1;
1.327     albertel 8414:     }
1.846     albertel 8415: 
                   8416:     sub domain {
1.852     albertel 8417: 	&load_domain_tab() if (!$loaded);
                   8418: 
1.846     albertel 8419: 	my ($name,$what) = @_;
                   8420: 	return if ( !exists($domain{$name}) );
                   8421: 
                   8422: 	if (!$what) {
                   8423: 	    return $domain{$name}{'description'};
                   8424: 	}
                   8425: 	return $domain{$name}{$what};
                   8426:     }
1.327     albertel 8427: }
                   8428: 
                   8429: 
1.1       albertel 8430: # ------------------------------------------------------------- Read hosts file
                   8431: {
1.838     albertel 8432:     my %hostname;
1.844     albertel 8433:     my %hostdom;
1.845     albertel 8434:     my %libserv;
1.852     albertel 8435:     my $loaded;
1.888     albertel 8436:     my %name_to_host;
1.852     albertel 8437: 
                   8438:     sub parse_hosts_tab {
                   8439: 	my ($file) = @_;
                   8440: 	foreach my $configline (@$file) {
                   8441: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8442: 	    next if ($configline =~ /^\^/);
                   8443: 	    chomp($configline);
                   8444: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8445: 	    $name=~s/\s//g;
                   8446: 	    if ($id && $domain && $role && $name) {
                   8447: 		$hostname{$id}=$name;
1.888     albertel 8448: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8449: 		$hostdom{$id}=$domain;
                   8450: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8451: 	    }
                   8452: 	}
                   8453:     }
1.864     albertel 8454:     
                   8455:     sub reset_hosts_info {
1.897     albertel 8456: 	&purge_remembered();
1.864     albertel 8457: 	&reset_domain_info();
                   8458: 	&reset_hosts_ip_info();
1.892     albertel 8459: 	undef(%name_to_host);
1.864     albertel 8460: 	undef(%hostname);
                   8461: 	undef(%hostdom);
                   8462: 	undef(%libserv);
                   8463: 	undef($loaded);
                   8464:     }
1.1       albertel 8465: 
1.852     albertel 8466:     sub load_hosts_tab {
1.869     albertel 8467: 	my ($ignore_cache) = @_;
                   8468: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8469: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8470: 	my @config = <$config>;
                   8471: 	&parse_hosts_tab(\@config);
                   8472: 	close($config);
                   8473: 	$loaded=1;
1.1       albertel 8474:     }
1.852     albertel 8475: 
1.838     albertel 8476:     sub hostname {
1.852     albertel 8477: 	&load_hosts_tab() if (!$loaded);
                   8478: 
1.838     albertel 8479: 	my ($lonid) = @_;
                   8480: 	return $hostname{$lonid};
                   8481:     }
1.845     albertel 8482: 
1.838     albertel 8483:     sub all_hostnames {
1.852     albertel 8484: 	&load_hosts_tab() if (!$loaded);
                   8485: 
1.838     albertel 8486: 	return %hostname;
                   8487:     }
1.845     albertel 8488: 
1.888     albertel 8489:     sub all_names {
                   8490: 	&load_hosts_tab() if (!$loaded);
                   8491: 
                   8492: 	return %name_to_host;
                   8493:     }
                   8494: 
1.845     albertel 8495:     sub is_library {
1.852     albertel 8496: 	&load_hosts_tab() if (!$loaded);
                   8497: 
1.845     albertel 8498: 	return exists($libserv{$_[0]});
                   8499:     }
                   8500: 
                   8501:     sub all_library {
1.852     albertel 8502: 	&load_hosts_tab() if (!$loaded);
                   8503: 
1.845     albertel 8504: 	return %libserv;
                   8505:     }
                   8506: 
1.841     albertel 8507:     sub get_servers {
1.852     albertel 8508: 	&load_hosts_tab() if (!$loaded);
                   8509: 
1.841     albertel 8510: 	my ($domain,$type) = @_;
                   8511: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8512: 	                                          : %hostname;
                   8513: 	my %result;
1.842     albertel 8514: 	if (ref($domain) eq 'ARRAY') {
                   8515: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8516: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8517: 		    $result{$host} = $hostname;
                   8518: 		}
                   8519: 	    }
                   8520: 	} else {
                   8521: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8522: 		if ($hostdom{$host} eq $domain) {
                   8523: 		    $result{$host} = $hostname;
                   8524: 		}
1.841     albertel 8525: 	    }
                   8526: 	}
                   8527: 	return %result;
                   8528:     }
1.845     albertel 8529: 
1.844     albertel 8530:     sub host_domain {
1.852     albertel 8531: 	&load_hosts_tab() if (!$loaded);
                   8532: 
1.844     albertel 8533: 	my ($lonid) = @_;
                   8534: 	return $hostdom{$lonid};
                   8535:     }
                   8536: 
1.841     albertel 8537:     sub all_domains {
1.852     albertel 8538: 	&load_hosts_tab() if (!$loaded);
                   8539: 
1.841     albertel 8540: 	my %seen;
                   8541: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8542: 	return @uniq;
                   8543:     }
1.1       albertel 8544: }
                   8545: 
1.847     albertel 8546: { 
                   8547:     my %iphost;
1.856     albertel 8548:     my %name_to_ip;
                   8549:     my %lonid_to_ip;
1.869     albertel 8550: 
1.847     albertel 8551:     sub get_hosts_from_ip {
                   8552: 	my ($ip) = @_;
                   8553: 	my %iphosts = &get_iphost();
                   8554: 	if (ref($iphosts{$ip})) {
                   8555: 	    return @{$iphosts{$ip}};
                   8556: 	}
                   8557: 	return;
1.839     albertel 8558:     }
1.864     albertel 8559:     
                   8560:     sub reset_hosts_ip_info {
                   8561: 	undef(%iphost);
                   8562: 	undef(%name_to_ip);
                   8563: 	undef(%lonid_to_ip);
                   8564:     }
1.856     albertel 8565: 
                   8566:     sub get_host_ip {
                   8567: 	my ($lonid) = @_;
                   8568: 	if (exists($lonid_to_ip{$lonid})) {
                   8569: 	    return $lonid_to_ip{$lonid};
                   8570: 	}
                   8571: 	my $name=&hostname($lonid);
                   8572:    	my $ip = gethostbyname($name);
                   8573: 	return if (!$ip || length($ip) ne 4);
                   8574: 	$ip=inet_ntoa($ip);
                   8575: 	$name_to_ip{$name}   = $ip;
                   8576: 	$lonid_to_ip{$lonid} = $ip;
                   8577: 	return $ip;
                   8578:     }
1.847     albertel 8579:     
                   8580:     sub get_iphost {
1.869     albertel 8581: 	my ($ignore_cache) = @_;
1.894     albertel 8582: 
1.869     albertel 8583: 	if (!$ignore_cache) {
                   8584: 	    if (%iphost) {
                   8585: 		return %iphost;
                   8586: 	    }
                   8587: 	    my ($ip_info,$cached)=
                   8588: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8589: 	    if ($cached) {
                   8590: 		%iphost      = %{$ip_info->[0]};
                   8591: 		%name_to_ip  = %{$ip_info->[1]};
                   8592: 		%lonid_to_ip = %{$ip_info->[2]};
                   8593: 		return %iphost;
                   8594: 	    }
                   8595: 	}
1.894     albertel 8596: 
                   8597: 	# get yesterday's info for fallback
                   8598: 	my %old_name_to_ip;
                   8599: 	my ($ip_info,$cached)=
                   8600: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8601: 	if ($cached) {
                   8602: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8603: 	}
                   8604: 
1.888     albertel 8605: 	my %name_to_host = &all_names();
                   8606: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8607: 	    my $ip;
                   8608: 	    if (!exists($name_to_ip{$name})) {
                   8609: 		$ip = gethostbyname($name);
                   8610: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8611: 		    if (defined($old_name_to_ip{$name})) {
                   8612: 			$ip = $old_name_to_ip{$name};
                   8613: 			&logthis("Can't find $name defaulting to old $ip");
                   8614: 		    } else {
                   8615: 			&logthis("Name $name no IP found");
                   8616: 			next;
                   8617: 		    }
                   8618: 		} else {
                   8619: 		    $ip=inet_ntoa($ip);
1.847     albertel 8620: 		}
                   8621: 		$name_to_ip{$name} = $ip;
                   8622: 	    } else {
                   8623: 		$ip = $name_to_ip{$name};
1.653     albertel 8624: 	    }
1.888     albertel 8625: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8626: 		$lonid_to_ip{$id} = $ip;
                   8627: 	    }
                   8628: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8629: 	}
1.869     albertel 8630: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8631: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8632: 				      48*60*60);
1.869     albertel 8633: 
1.847     albertel 8634: 	return %iphost;
1.598     albertel 8635:     }
                   8636: }
                   8637: 
1.862     albertel 8638: BEGIN {
                   8639: 
                   8640: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8641:     unless ($readit) {
                   8642: {
                   8643:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8644:     %perlvar = (%perlvar,%{$configvars});
                   8645: }
                   8646: 
                   8647: 
1.1       albertel 8648: # ------------------------------------------------------ Read spare server file
                   8649: {
1.448     albertel 8650:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8651: 
                   8652:     while (my $configline=<$config>) {
                   8653:        chomp($configline);
1.284     matthew  8654:        if ($configline) {
1.784     albertel 8655: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8656: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8657: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8658:        }
                   8659:     }
1.448     albertel 8660:     close($config);
1.1       albertel 8661: }
1.11      www      8662: # ------------------------------------------------------------ Read permissions
                   8663: {
1.448     albertel 8664:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8665: 
                   8666:     while (my $configline=<$config>) {
1.448     albertel 8667: 	chomp($configline);
                   8668: 	if ($configline) {
                   8669: 	    my ($role,$perm)=split(/ /,$configline);
                   8670: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8671: 	}
1.11      www      8672:     }
1.448     albertel 8673:     close($config);
1.11      www      8674: }
                   8675: 
                   8676: # -------------------------------------------- Read plain texts for permissions
                   8677: {
1.448     albertel 8678:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8679: 
                   8680:     while (my $configline=<$config>) {
1.448     albertel 8681: 	chomp($configline);
                   8682: 	if ($configline) {
1.742     raeburn  8683: 	    my ($short,@plain)=split(/:/,$configline);
                   8684:             %{$prp{$short}} = ();
                   8685: 	    if (@plain > 0) {
                   8686:                 $prp{$short}{'std'} = $plain[0];
                   8687:                 for (my $i=1; $i<@plain; $i++) {
                   8688:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8689:                 }
                   8690:             }
1.448     albertel 8691: 	}
1.135     www      8692:     }
1.448     albertel 8693:     close($config);
1.135     www      8694: }
                   8695: 
                   8696: # ---------------------------------------------------------- Read package table
                   8697: {
1.448     albertel 8698:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8699: 
                   8700:     while (my $configline=<$config>) {
1.483     albertel 8701: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8702: 	chomp($configline);
                   8703: 	my ($short,$plain)=split(/:/,$configline);
                   8704: 	my ($pack,$name)=split(/\&/,$short);
                   8705: 	if ($plain ne '') {
                   8706: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8707: 	    $packagetab{$short}=$plain; 
                   8708: 	}
1.11      www      8709:     }
1.448     albertel 8710:     close($config);
1.329     matthew  8711: }
                   8712: 
                   8713: # ------------- set up temporary directory
                   8714: {
                   8715:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8716: 
1.11      www      8717: }
                   8718: 
1.794     albertel 8719: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8720: 				'compress_threshold'=> 20_000,
                   8721:  			        });
1.185     www      8722: 
1.281     www      8723: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8724: $dumpcount=0;
1.22      www      8725: 
1.163     harris41 8726: &logtouch();
1.672     albertel 8727: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8728: $readit=1;
1.564     albertel 8729:     {
                   8730: 	use integer;
                   8731: 	my $test=(2**32)+1;
1.568     albertel 8732: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8733: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8734:     }
1.195     www      8735: }
1.1       albertel 8736: }
1.179     www      8737: 
1.1       albertel 8738: 1;
1.191     harris41 8739: __END__
                   8740: 
1.243     albertel 8741: =pod
                   8742: 
1.191     harris41 8743: =head1 NAME
                   8744: 
1.243     albertel 8745: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8746: 
                   8747: =head1 SYNOPSIS
                   8748: 
1.243     albertel 8749: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8750: 
                   8751:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8752: 
1.243     albertel 8753: Common parameters:
                   8754: 
                   8755: =over 4
                   8756: 
                   8757: =item *
                   8758: 
                   8759: $uname : an internal username (if $cname expecting a course Id specifically)
                   8760: 
                   8761: =item *
                   8762: 
                   8763: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8764: 
                   8765: =item *
                   8766: 
                   8767: $symb : a resource instance identifier
                   8768: 
                   8769: =item *
                   8770: 
                   8771: $namespace : the name of a .db file that contains the data needed or
                   8772: being set.
                   8773: 
                   8774: =back
                   8775: 
1.394     bowersj2 8776: =head1 OVERVIEW
1.191     harris41 8777: 
1.394     bowersj2 8778: lonnet provides subroutines which interact with the
                   8779: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8780: about classes, users, and resources.
1.243     albertel 8781: 
                   8782: For many of these objects you can also use this to store data about
                   8783: them or modify them in various ways.
1.191     harris41 8784: 
1.394     bowersj2 8785: =head2 Symbs
1.191     harris41 8786: 
1.394     bowersj2 8787: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8788: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8789: map, the resource number of the resource in the map, and the URL of
                   8790: the resource itself. The latter is somewhat redundant, but might help
                   8791: if maps change.
                   8792: 
                   8793: An example is
                   8794: 
                   8795:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8796: 
                   8797: The respective map entry is
                   8798: 
                   8799:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8800:   title="Problem 2">
                   8801:  </resource>
                   8802: 
                   8803: Symbs are used by the random number generator, as well as to store and
                   8804: restore data specific to a certain instance of for example a problem.
                   8805: 
                   8806: =head2 Storing And Retrieving Data
                   8807: 
                   8808: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8809: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8810: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8811: is is the non-critical message twin of cstore. These functions are for
                   8812: handlers to store a perl hash to a user's permanent data space in an
                   8813: easy manner, and to retrieve it again on another call. It is expected
                   8814: that a handler would use this once at the beginning to retrieve data,
                   8815: and then again once at the end to send only the new data back.
                   8816: 
                   8817: The data is stored in the user's data directory on the user's
                   8818: homeserver under the ID of the course.
                   8819: 
                   8820: The hash that is returned by restore will have all of the previous
                   8821: value for all of the elements of the hash.
                   8822: 
                   8823: Example:
                   8824: 
                   8825:  #creating a hash
                   8826:  my %hash;
                   8827:  $hash{'foo'}='bar';
                   8828: 
                   8829:  #storing it
                   8830:  &Apache::lonnet::cstore(\%hash);
                   8831: 
                   8832:  #changing a value
                   8833:  $hash{'foo'}='notbar';
                   8834: 
                   8835:  #adding a new value
                   8836:  $hash{'bar'}='foo';
                   8837:  &Apache::lonnet::cstore(\%hash);
                   8838: 
                   8839:  #retrieving the hash
                   8840:  my %history=&Apache::lonnet::restore();
                   8841: 
                   8842:  #print the hash
                   8843:  foreach my $key (sort(keys(%history))) {
                   8844:    print("\%history{$key} = $history{$key}");
                   8845:  }
                   8846: 
                   8847: Will print out:
1.191     harris41 8848: 
1.394     bowersj2 8849:  %history{1:foo} = bar
                   8850:  %history{1:keys} = foo:timestamp
                   8851:  %history{1:timestamp} = 990455579
                   8852:  %history{2:bar} = foo
                   8853:  %history{2:foo} = notbar
                   8854:  %history{2:keys} = foo:bar:timestamp
                   8855:  %history{2:timestamp} = 990455580
                   8856:  %history{bar} = foo
                   8857:  %history{foo} = notbar
                   8858:  %history{timestamp} = 990455580
                   8859:  %history{version} = 2
                   8860: 
                   8861: Note that the special hash entries C<keys>, C<version> and
                   8862: C<timestamp> were added to the hash. C<version> will be equal to the
                   8863: total number of versions of the data that have been stored. The
                   8864: C<timestamp> attribute will be the UNIX time the hash was
                   8865: stored. C<keys> is available in every historical section to list which
                   8866: keys were added or changed at a specific historical revision of a
                   8867: hash.
                   8868: 
                   8869: B<Warning>: do not store the hash that restore returns directly. This
                   8870: will cause a mess since it will restore the historical keys as if the
                   8871: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8872: 
1.394     bowersj2 8873: Calling convention:
1.191     harris41 8874: 
1.394     bowersj2 8875:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8876:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8877: 
1.394     bowersj2 8878: For more detailed information, see lonnet specific documentation.
1.191     harris41 8879: 
1.394     bowersj2 8880: =head1 RETURN MESSAGES
1.191     harris41 8881: 
1.394     bowersj2 8882: =over 4
1.191     harris41 8883: 
1.394     bowersj2 8884: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8885: 
1.394     bowersj2 8886: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8887: when the connection is brought back up
1.191     harris41 8888: 
1.394     bowersj2 8889: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8890: for later delivery
1.191     harris41 8891: 
1.394     bowersj2 8892: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8893: 
1.394     bowersj2 8894: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8895: that was requested
1.191     harris41 8896: 
1.243     albertel 8897: =back
1.191     harris41 8898: 
1.243     albertel 8899: =head1 PUBLIC SUBROUTINES
1.191     harris41 8900: 
1.243     albertel 8901: =head2 Session Environment Functions
1.191     harris41 8902: 
1.243     albertel 8903: =over 4
1.191     harris41 8904: 
1.394     bowersj2 8905: =item * 
                   8906: X<appenv()>
1.949     raeburn  8907: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8908: the user envirnoment file, and will be restored for each access this
1.620     albertel 8909: user makes during this session, also modifies the %env for the current
1.949     raeburn  8910: process. Optional rolesarrayref - if defined contains a reference to an array
                   8911: of roles which are exempt from the restriction on modifying user.role entries 
                   8912: in the user's environment.db and in %env.    
1.191     harris41 8913: 
                   8914: =item *
1.394     bowersj2 8915: X<delenv()>
                   8916: B<delenv($regexp)>: removes all items from the session
                   8917: environment file that matches the regular expression in $regexp. The
1.620     albertel 8918: values are also delted from the current processes %env.
1.191     harris41 8919: 
1.795     albertel 8920: =item * get_env_multiple($name) 
                   8921: 
                   8922: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8923: values may be defined and end up as an array ref.
                   8924: 
                   8925: returns an array of values
                   8926: 
1.243     albertel 8927: =back
                   8928: 
                   8929: =head2 User Information
1.191     harris41 8930: 
1.243     albertel 8931: =over 4
1.191     harris41 8932: 
                   8933: =item *
1.394     bowersj2 8934: X<queryauthenticate()>
                   8935: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8936: authentication scheme
                   8937: 
                   8938: =item *
1.394     bowersj2 8939: X<authenticate()>
                   8940: B<authenticate($uname,$upass,$udom)>: try to
                   8941: authenticate user from domain's lib servers (first use the current
                   8942: one). C<$upass> should be the users password.
1.191     harris41 8943: 
                   8944: =item *
1.394     bowersj2 8945: X<homeserver()>
                   8946: B<homeserver($uname,$udom)>: find the server which has
                   8947: the user's directory and files (there must be only one), this caches
                   8948: the answer, and also caches if there is a borken connection.
1.191     harris41 8949: 
                   8950: =item *
1.394     bowersj2 8951: X<idget()>
                   8952: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8953: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8954: username, and only 1 username per ID in a specific domain) (returns
                   8955: hash: id=>name,id=>name)
1.191     harris41 8956: 
                   8957: =item *
1.394     bowersj2 8958: X<idrget()>
                   8959: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8960: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8961: 
                   8962: =item *
1.394     bowersj2 8963: X<idput()>
                   8964: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8965: 
                   8966: =item *
1.394     bowersj2 8967: X<rolesinit()>
                   8968: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8969: 
                   8970: =item *
1.551     albertel 8971: X<getsection()>
                   8972: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8973: course $cname, return section name/number or '' for "not in course"
                   8974: and '-1' for "no section"
                   8975: 
                   8976: =item *
1.394     bowersj2 8977: X<userenvironment()>
                   8978: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8979: passed in @what from the requested user's environment, returns a hash
                   8980: 
1.858     raeburn  8981: =item * 
                   8982: X<userlog_query()>
1.859     albertel 8983: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8984: activity.log file. %filters defines filters applied when parsing the
                   8985: log file. These can be start or end timestamps, or the type of action
                   8986: - log to look for Login or Logout events, check for Checkin or
                   8987: Checkout, role for role selection. The response is in the form
                   8988: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8989: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8990: 
1.243     albertel 8991: =back
                   8992: 
                   8993: =head2 User Roles
                   8994: 
                   8995: =over 4
                   8996: 
                   8997: =item *
                   8998: 
1.810     raeburn  8999: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9000:  F: full access
                   9001:  U,I,K: authentication modes (cxx only)
                   9002:  '': forbidden
                   9003:  1: user needs to choose course
                   9004:  2: browse allowed
1.766     albertel 9005:  A: passphrase authentication needed
1.243     albertel 9006: 
                   9007: =item *
                   9008: 
                   9009: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9010: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9011: and course level
                   9012: 
                   9013: =item *
                   9014: 
                   9015: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9016: explanation of a user role term
                   9017: 
1.832     raeburn  9018: =item *
                   9019: 
1.935     raeburn  9020: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9021: All arguments are optional. Returns a hash of a roles, either for
                   9022: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9023: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9024: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9025: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9026: For each key, value is set to colon-separated start and end times for
                   9027: the role.  If no username and domain are specified, will default to
1.934     raeburn  9028: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9029: of role statuses (active, future or previous), roles 
                   9030: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9031: to restrict the list of roles reported. If no array ref is 
                   9032: provided for types, will default to return only active roles.
1.834     albertel 9033: 
1.243     albertel 9034: =back
                   9035: 
                   9036: =head2 User Modification
                   9037: 
                   9038: =over 4
                   9039: 
                   9040: =item *
                   9041: 
                   9042: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   9043: user for the level given by URL.  Optional start and end dates (leave empty
                   9044: string or zero for "no date")
1.191     harris41 9045: 
                   9046: =item *
                   9047: 
1.243     albertel 9048: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9049: change a users, password, possible return values are: ok,
                   9050: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9051: refused
1.191     harris41 9052: 
                   9053: =item *
                   9054: 
1.243     albertel 9055: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9056: 
                   9057: =item *
                   9058: 
1.243     albertel 9059: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9060: modify user
1.191     harris41 9061: 
                   9062: =item *
                   9063: 
1.286     matthew  9064: modifystudent
                   9065: 
                   9066: modify a students enrollment and identification information.
                   9067: The course id is resolved based on the current users environment.  
                   9068: This means the envoking user must be a course coordinator or otherwise
                   9069: associated with a course.
                   9070: 
1.297     matthew  9071: This call is essentially a wrapper for lonnet::modifyuser and
                   9072: lonnet::modify_student_enrollment
1.286     matthew  9073: 
                   9074: Inputs: 
                   9075: 
                   9076: =over 4
                   9077: 
                   9078: =item B<$udom> Students loncapa domain
                   9079: 
                   9080: =item B<$uname> Students loncapa login name
                   9081: 
                   9082: =item B<$uid> Students id/student number
                   9083: 
                   9084: =item B<$umode> Students authentication mode
                   9085: 
                   9086: =item B<$upass> Students password
                   9087: 
                   9088: =item B<$first> Students first name
                   9089: 
                   9090: =item B<$middle> Students middle name
                   9091: 
                   9092: =item B<$last> Students last name
                   9093: 
                   9094: =item B<$gene> Students generation
                   9095: 
                   9096: =item B<$usec> Students section in course
                   9097: 
                   9098: =item B<$end> Unix time of the roles expiration
                   9099: 
                   9100: =item B<$start> Unix time of the roles start date
                   9101: 
                   9102: =item B<$forceid> If defined, allow $uid to be changed
                   9103: 
                   9104: =item B<$desiredhome> server to use as home server for student
                   9105: 
                   9106: =back
1.297     matthew  9107: 
                   9108: =item *
                   9109: 
                   9110: modify_student_enrollment
                   9111: 
                   9112: Change a students enrollment status in a class.  The environment variable
                   9113: 'role.request.course' must be defined for this function to proceed.
                   9114: 
                   9115: Inputs:
                   9116: 
                   9117: =over 4
                   9118: 
                   9119: =item $udom, students domain
                   9120: 
                   9121: =item $uname, students name
                   9122: 
                   9123: =item $uid, students user id
                   9124: 
                   9125: =item $first, students first name
                   9126: 
                   9127: =item $middle
                   9128: 
                   9129: =item $last
                   9130: 
                   9131: =item $gene
                   9132: 
                   9133: =item $usec
                   9134: 
                   9135: =item $end
                   9136: 
                   9137: =item $start
                   9138: 
                   9139: =back
                   9140: 
1.191     harris41 9141: 
                   9142: =item *
                   9143: 
1.243     albertel 9144: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9145: custom role; give a custom role to a user for the level given by URL.  Specify
                   9146: name and domain of role author, and role name
1.191     harris41 9147: 
                   9148: =item *
                   9149: 
1.243     albertel 9150: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9151: 
                   9152: =item *
                   9153: 
1.243     albertel 9154: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9155: 
                   9156: =back
                   9157: 
                   9158: =head2 Course Infomation
                   9159: 
                   9160: =over 4
1.191     harris41 9161: 
                   9162: =item *
                   9163: 
1.631     albertel 9164: coursedescription($courseid) : returns a hash of information about the
                   9165: specified course id, including all environment settings for the
                   9166: course, the description of the course will be in the hash under the
                   9167: key 'description'
1.191     harris41 9168: 
                   9169: =item *
                   9170: 
1.624     albertel 9171: resdata($name,$domain,$type,@which) : request for current parameter
                   9172: setting for a specific $type, where $type is either 'course' or 'user',
                   9173: @what should be a list of parameters to ask about. This routine caches
                   9174: answers for 5 minutes.
1.243     albertel 9175: 
1.877     foxr     9176: =item *
                   9177: 
                   9178: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9179: data base, returning a hash that is keyed by the resource name and has
                   9180: values that are the resource value.  I believe that the timestamps and
                   9181: versions are also returned.
                   9182: 
                   9183: 
1.243     albertel 9184: =back
                   9185: 
                   9186: =head2 Course Modification
                   9187: 
                   9188: =over 4
1.191     harris41 9189: 
                   9190: =item *
                   9191: 
1.243     albertel 9192: writecoursepref($courseid,%prefs) : write preferences (environment
                   9193: database) for a course
1.191     harris41 9194: 
                   9195: =item *
                   9196: 
1.243     albertel 9197: createcourse($udom,$description,$url) : make/modify course
                   9198: 
                   9199: =back
                   9200: 
                   9201: =head2 Resource Subroutines
                   9202: 
                   9203: =over 4
1.191     harris41 9204: 
                   9205: =item *
                   9206: 
1.243     albertel 9207: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9208: 
                   9209: =item *
                   9210: 
1.243     albertel 9211: repcopy($filename) : subscribes to the requested file, and attempts to
                   9212: replicate from the owning library server, Might return
1.607     raeburn  9213: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9214: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9215: resource. Expects the local filesystem pathname
                   9216: (/home/httpd/html/res/....)
                   9217: 
                   9218: =back
                   9219: 
                   9220: =head2 Resource Information
                   9221: 
                   9222: =over 4
1.191     harris41 9223: 
                   9224: =item *
                   9225: 
1.243     albertel 9226: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9227: a vairety of different possible values, $varname should be a request
                   9228: string, and the other parameters can be used to specify who and what
                   9229: one is asking about.
                   9230: 
                   9231: Possible values for $varname are environment.lastname (or other item
                   9232: from the envirnment hash), user.name (or someother aspect about the
                   9233: user), resource.0.maxtries (or some other part and parameter of a
                   9234: resource)
1.204     albertel 9235: 
                   9236: =item *
                   9237: 
1.243     albertel 9238: directcondval($number) : get current value of a condition; reads from a state
                   9239: string
1.204     albertel 9240: 
                   9241: =item *
                   9242: 
1.243     albertel 9243: condval($condidx) : value of condition index based on state
1.204     albertel 9244: 
                   9245: =item *
                   9246: 
1.243     albertel 9247: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9248: resource's metadata, $what should be either a specific key, or either
                   9249: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9250: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9251: 
                   9252: this function automatically caches all requests
1.191     harris41 9253: 
                   9254: =item *
                   9255: 
1.243     albertel 9256: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9257: network of library servers; returns file handle of where SQL and regex results
                   9258: will be stored for query
1.191     harris41 9259: 
                   9260: =item *
                   9261: 
1.243     albertel 9262: symbread($filename) : return symbolic list entry (filename argument optional);
                   9263: returns the data handle
1.191     harris41 9264: 
                   9265: =item *
                   9266: 
1.243     albertel 9267: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9268: a possible symb for the URL in $thisfn, and if is an encryypted
                   9269: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9270: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9271: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9272: 
1.191     harris41 9273: 
                   9274: =item *
                   9275: 
1.243     albertel 9276: symbclean($symb) : removes versions numbers from a symb, returns the
                   9277: cleaned symb
1.191     harris41 9278: 
                   9279: =item *
                   9280: 
1.243     albertel 9281: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9282: course map, user must be in a course for it to work.
1.191     harris41 9283: 
                   9284: =item *
                   9285: 
1.243     albertel 9286: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9287: 
                   9288: =item *
                   9289: 
1.243     albertel 9290: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9291: a random seed, all arguments are optional, if they aren't sent it uses the
                   9292: environment to derive them. Note: if symb isn't sent and it can't get one
                   9293: from &symbread it will use the current time as its return value
1.191     harris41 9294: 
                   9295: =item *
                   9296: 
1.243     albertel 9297: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9298: unfakeable, receipt
1.191     harris41 9299: 
                   9300: =item *
                   9301: 
1.620     albertel 9302: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9303: 
                   9304: =item *
                   9305: 
1.243     albertel 9306: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9307: 
                   9308: =item *
                   9309: 
1.243     albertel 9310: 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 9311: 
                   9312: =item *
                   9313: 
1.243     albertel 9314: 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 9315: 
                   9316: =item *
                   9317: 
1.243     albertel 9318: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9319: 
                   9320: =item *
                   9321: 
1.243     albertel 9322: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9323: forcing spreadsheet to reevaluate the resource scores next time.
                   9324: 
                   9325: =back
                   9326: 
                   9327: =head2 Storing/Retreiving Data
                   9328: 
                   9329: =over 4
1.191     harris41 9330: 
                   9331: =item *
                   9332: 
1.243     albertel 9333: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9334: for this url; hashref needs to be given and should be a \%hashname; the
                   9335: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9336: be derived from the env
1.191     harris41 9337: 
                   9338: =item *
                   9339: 
1.243     albertel 9340: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9341: uses critical subroutine
1.191     harris41 9342: 
                   9343: =item *
                   9344: 
1.243     albertel 9345: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9346: all args are optional
1.191     harris41 9347: 
                   9348: =item *
                   9349: 
1.717     albertel 9350: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9351: dumps the complete (or key matching regexp) namespace into a hash
                   9352: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9353: normally &store()ed into
                   9354: 
                   9355: $range should be either an integer '100' (give me the first 100
                   9356:                                            matching records)
                   9357:               or be  two integers sperated by a - with no spaces
                   9358:                  '30-50' (give me the 30th through the 50th matching
                   9359:                           records)
                   9360: 
                   9361: 
                   9362: =item *
                   9363: 
                   9364: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9365: replaces a &store() version of data with a replacement set of data
                   9366: for a particular resource in a namespace passed in the $storehash hash 
                   9367: reference
                   9368: 
                   9369: =item *
                   9370: 
1.243     albertel 9371: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9372: works very similar to store/cstore, but all data is stored in a
                   9373: temporary location and can be reset using tmpreset, $storehash should
                   9374: be a hash reference, returns nothing on success
1.191     harris41 9375: 
                   9376: =item *
                   9377: 
1.243     albertel 9378: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9379: similar to restore, but all data is stored in a temporary location and
                   9380: can be reset using tmpreset. Returns a hash of values on success,
                   9381: error string otherwise.
1.191     harris41 9382: 
                   9383: =item *
                   9384: 
1.243     albertel 9385: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9386: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9387: 
                   9388: =item *
                   9389: 
1.243     albertel 9390: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9391: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9392: 
                   9393: =item *
                   9394: 
1.243     albertel 9395: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9396: namesp ($udom and $uname are optional)
1.191     harris41 9397: 
                   9398: =item *
                   9399: 
1.702     albertel 9400: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9401: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9402: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9403: 
1.702     albertel 9404: $range should be either an integer '100' (give me the first 100
                   9405:                                            matching records)
                   9406:               or be  two integers sperated by a - with no spaces
                   9407:                  '30-50' (give me the 30th through the 50th matching
                   9408:                           records)
1.449     matthew  9409: =item *
                   9410: 
                   9411: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9412: $store can be a scalar, an array reference, or if the amount to be 
                   9413: incremented is > 1, a hash reference.
                   9414: 
                   9415: ($udom and $uname are optional)
1.191     harris41 9416: 
                   9417: =item *
                   9418: 
1.243     albertel 9419: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9420: ($udom and $uname are optional)
1.191     harris41 9421: 
                   9422: =item *
                   9423: 
1.243     albertel 9424: cput($namespace,$storehash,$udom,$uname) : critical put
                   9425: ($udom and $uname are optional)
1.191     harris41 9426: 
                   9427: =item *
                   9428: 
1.748     albertel 9429: newput($namespace,$storehash,$udom,$uname) :
                   9430: 
                   9431: Attempts to store the items in the $storehash, but only if they don't
                   9432: currently exist, if this succeeds you can be certain that you have 
                   9433: successfully created a new key value pair in the $namespace db.
                   9434: 
                   9435: 
                   9436: Args:
                   9437:  $namespace: name of database to store values to
                   9438:  $storehash: hashref to store to the db
                   9439:  $udom: (optional) domain of user containing the db
                   9440:  $uname: (optional) name of user caontaining the db
                   9441: 
                   9442: Returns:
                   9443:  'ok' -> succeeded in storing all keys of $storehash
                   9444:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9445:                         least <key> already existed in the db (other
                   9446:                         requested keys may also already exist)
                   9447:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9448:  'con_lost' -> unable to contact request server
                   9449:  'refused' -> action was not allowed by remote machine
                   9450: 
                   9451: 
                   9452: =item *
                   9453: 
1.243     albertel 9454: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9455: reference filled in from namesp (encrypts the return communication)
                   9456: ($udom and $uname are optional)
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9461: critical subroutine
                   9462: 
1.806     raeburn  9463: =item *
                   9464: 
1.860     raeburn  9465: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9466: array reference filled in from namespace found in domain level on either
                   9467: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9468: 
                   9469: =item *
                   9470: 
1.860     raeburn  9471: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9472: domain level either on specified domain server ($uhome) or primary domain 
                   9473: server ($udom and $uhome are optional)
1.806     raeburn  9474: 
1.943     raeburn  9475: =item * 
                   9476: 
                   9477: get_domain_defaults($target_domain) : returns hash with defaults for
                   9478: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9479: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9480: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9481: Values are retrieved from cache (if current), or from domain's configuration.db
                   9482: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9483: or lonTabs/domain.tab. 
                   9484: 
                   9485: %domdefaults = &get_auth_defaults($target_domain);
                   9486: 
1.243     albertel 9487: =back
                   9488: 
                   9489: =head2 Network Status Functions
                   9490: 
                   9491: =over 4
1.191     harris41 9492: 
                   9493: =item *
                   9494: 
                   9495: dirlist($uri) : return directory list based on URI
                   9496: 
                   9497: =item *
                   9498: 
1.243     albertel 9499: spareserver() : find server with least workload from spare.tab
                   9500: 
                   9501: =back
                   9502: 
                   9503: =head2 Apache Request
                   9504: 
                   9505: =over 4
1.191     harris41 9506: 
                   9507: =item *
                   9508: 
1.243     albertel 9509: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9510: localhost, posts hash
                   9511: 
                   9512: =back
                   9513: 
                   9514: =head2 Data to String to Data
                   9515: 
                   9516: =over 4
1.191     harris41 9517: 
                   9518: =item *
                   9519: 
1.243     albertel 9520: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9521: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9522: 
                   9523: =item *
                   9524: 
1.243     albertel 9525: hashref2str($hashref) : convert a hashref into a string complete with
                   9526: escaping and '=' and '&' separators, supports elements that are
                   9527: arrayrefs and hashrefs
1.191     harris41 9528: 
                   9529: =item *
                   9530: 
1.243     albertel 9531: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9532: with escaping and '&' separators, supports elements that are arrayrefs
                   9533: and hashrefs
1.191     harris41 9534: 
                   9535: =item *
                   9536: 
1.243     albertel 9537: str2hash($string) : convert string to hash using unescaping and
                   9538: splitting on '=' and '&', supports elements that are arrayrefs and
                   9539: hashrefs
1.191     harris41 9540: 
                   9541: =item *
                   9542: 
1.243     albertel 9543: str2array($string) : convert string to hash using unescaping and
                   9544: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9545: 
                   9546: =back
                   9547: 
                   9548: =head2 Logging Routines
                   9549: 
                   9550: =over 4
                   9551: 
                   9552: These routines allow one to make log messages in the lonnet.log and
                   9553: lonnet.perm logfiles.
1.191     harris41 9554: 
                   9555: =item *
                   9556: 
1.243     albertel 9557: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9558: 
                   9559: =item *
                   9560: 
1.243     albertel 9561: logthis() : append message to the normal lonnet.log file, it gets
                   9562: preiodically rolled over and deleted.
1.191     harris41 9563: 
                   9564: =item *
                   9565: 
1.243     albertel 9566: logperm() : append a permanent message to lonnet.perm.log, this log
                   9567: file never gets deleted by any automated portion of the system, only
                   9568: messages of critical importance should go in here.
                   9569: 
                   9570: =back
                   9571: 
                   9572: =head2 General File Helper Routines
                   9573: 
                   9574: =over 4
1.191     harris41 9575: 
                   9576: =item *
                   9577: 
1.481     raeburn  9578: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9579: (a) files in /uploaded
                   9580:   (i) If a local copy of the file exists - 
                   9581:       compares modification date of local copy with last-modified date for 
                   9582:       definitive version stored on home server for course. If local copy is 
                   9583:       stale, requests a new version from the home server and stores it. 
                   9584:       If the original has been removed from the home server, then local copy 
                   9585:       is unlinked.
                   9586:   (ii) If local copy does not exist -
                   9587:       requests the file from the home server and stores it. 
                   9588:   
                   9589:   If $caller is 'uploadrep':  
                   9590:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9591:     for request for files originally uploaded via DOCS. 
                   9592:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9593:   
                   9594:   Otherwise:
                   9595:      This indicates a call from the content generation phase of the request.
                   9596:      -  returns the entire contents of the file or -1.
                   9597:      
                   9598: (b) files in /res
                   9599:    - returns the entire contents of a file or -1; 
                   9600:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9601: 
1.712     albertel 9602: 
                   9603: =item *
                   9604: 
                   9605: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9606:                   reference
                   9607: 
                   9608: returns either a stat() list of data about the file or an empty list
                   9609: if the file doesn't exist or couldn't find out about it (connection
                   9610: problems or user unknown)
                   9611: 
1.191     harris41 9612: =item *
                   9613: 
1.243     albertel 9614: filelocation($dir,$file) : returns file system location of a file
                   9615: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9616: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9617: and a file of ../bob will become /a/bob)
1.191     harris41 9618: 
                   9619: =item *
                   9620: 
                   9621: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9622: filelocation except for hrefs
                   9623: 
                   9624: =item *
                   9625: 
                   9626: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9627: 
1.243     albertel 9628: =back
                   9629: 
1.608     albertel 9630: =head2 Usererfile file routines (/uploaded*)
                   9631: 
                   9632: =over 4
                   9633: 
                   9634: =item *
                   9635: 
                   9636: userfileupload(): main rotine for putting a file in a user or course's
                   9637:                   filespace, arguments are,
                   9638: 
1.620     albertel 9639:  formname - required - this is the name of the element in $env where the
1.608     albertel 9640:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9641:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9642:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9643:  coursedoc - if true, store the file in the course of the active role
                   9644:              of the current user
                   9645:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9646:          if undefined, it will be placed in "unknown"
                   9647: 
                   9648:  (This routine calls clean_filename() to remove any dangerous
                   9649:  characters from the filename, and then calls finuserfileupload() to
                   9650:  complete the transaction)
                   9651: 
                   9652:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9653:  and /adm/notfound.html if unsuccessful
                   9654: 
                   9655: =item *
                   9656: 
                   9657: clean_filename(): routine for cleaing a filename up for storage in
                   9658:                  userfile space, argument is:
                   9659: 
                   9660:  filename - proposed filename
                   9661: 
                   9662: returns: the new clean filename
                   9663: 
                   9664: =item *
                   9665: 
                   9666: finishuserfileupload(): routine that creaes and sends the file to
                   9667: userspace, probably shouldn't be called directly
                   9668: 
                   9669:   docuname: username or courseid of destination for the file
                   9670:   docudom: domain of user/course of destination for the file
                   9671:   formname: same as for userfileupload()
                   9672:   fname: filename (inculding subdirectories) for the file
                   9673: 
                   9674:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9675:  and /adm/notfound.html if unsuccessful
                   9676: 
                   9677: =item *
                   9678: 
                   9679: renameuserfile(): renames an existing userfile to a new name
                   9680: 
                   9681:   Args:
                   9682:    docuname: username or courseid of destination for the file
                   9683:    docudom: domain of user/course of destination for the file
                   9684:    old: current file name (including any subdirs under userfiles)
                   9685:    new: desired file name (including any subdirs under userfiles)
                   9686: 
                   9687: =item *
                   9688: 
                   9689: mkdiruserfile(): creates a directory is a userfiles dir
                   9690: 
                   9691:   Args:
                   9692:    docuname: username or courseid of destination for the file
                   9693:    docudom: domain of user/course of destination for the file
                   9694:    dir: dir to create (including any subdirs under userfiles)
                   9695: 
                   9696: =item *
                   9697: 
                   9698: removeuserfile(): removes a file that exists in userfiles
                   9699: 
                   9700:   Args:
                   9701:    docuname: username or courseid of destination for the file
                   9702:    docudom: domain of user/course of destination for the file
                   9703:    fname: filname to delete (including any subdirs under userfiles)
                   9704: 
                   9705: =item *
                   9706: 
                   9707: removeuploadedurl(): convience function for removeuserfile()
                   9708: 
                   9709:   Args:
                   9710:    url:  a full /uploaded/... url to delete
                   9711: 
1.747     albertel 9712: =item * 
                   9713: 
                   9714: get_portfile_permissions():
                   9715:   Args:
                   9716:     domain: domain of user or course contain the portfolio files
                   9717:     user: name of user or num of course contain the portfolio files
                   9718:   Returns:
                   9719:     hashref of a dump of the proper file_permissions.db
                   9720:    
                   9721: 
                   9722: =item * 
                   9723: 
                   9724: get_access_controls():
                   9725: 
                   9726: Args:
                   9727:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9728:   group: (optional) the group you want the files associated with
                   9729:   file: (optional) the file you want access info on
                   9730: 
                   9731: Returns:
1.749     raeburn  9732:     a hash (keys are file names) of hashes containing
                   9733:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9734:         values are XML containing access control settings (see below) 
1.747     albertel 9735: 
                   9736: Internal notes:
                   9737: 
1.749     raeburn  9738:  access controls are stored in file_permissions.db as key=value pairs.
                   9739:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9740:         where scope -> public,guest,course,group,domains or users.
                   9741:               end -> UNIX time for end of access (0 -> no end date)
                   9742:               start -> UNIX time for start of access
                   9743: 
                   9744:     value -> XML description of access control
                   9745:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9746:             <start></start>
                   9747:             <end></end>
                   9748: 
                   9749:             <password></password>  for scope type = guest
                   9750: 
                   9751:             <domain></domain>     for scope type = course or group
                   9752:             <number></number>
                   9753:             <roles id="">
                   9754:              <role></role>
                   9755:              <access></access>
                   9756:              <section></section>
                   9757:              <group></group>
                   9758:             </roles>
                   9759: 
                   9760:             <dom></dom>         for scope type = domains
                   9761: 
                   9762:             <users>             for scope type = users
                   9763:              <user>
                   9764:               <uname></uname>
                   9765:               <udom></udom>
                   9766:              </user>
                   9767:             </users>
                   9768:            </scope> 
                   9769:               
                   9770:  Access data is also aggregated for each file in an additional key=value pair:
                   9771:  key -> path to file/file_name\0accesscontrol 
                   9772:  value -> reference to hash
                   9773:           hash contains key = value pairs
                   9774:           where key = uniqueID:scope_end_start
                   9775:                 value = UNIX time record was last updated
                   9776: 
                   9777:           Used to improve speed of look-ups of access controls for each file.  
                   9778:  
                   9779:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9780: 
                   9781: modify_access_controls():
                   9782: 
                   9783: Modifies access controls for a portfolio file
                   9784: Args
                   9785: 1. file name
                   9786: 2. reference to hash of required changes,
                   9787: 3. domain
                   9788: 4. username
                   9789:   where domain,username are the domain of the portfolio owner 
                   9790:   (either a user or a course) 
                   9791: 
                   9792: Returns:
                   9793: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9794: 2. result of deletions ('ok' or 'error', with error message).
                   9795: 3. reference to hash of any new or updated access controls.
                   9796: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9797:    key = integer (inbound ID)
                   9798:    value = uniqueID  
1.747     albertel 9799: 
1.608     albertel 9800: =back
                   9801: 
1.243     albertel 9802: =head2 HTTP Helper Routines
                   9803: 
                   9804: =over 4
                   9805: 
1.191     harris41 9806: =item *
                   9807: 
                   9808: escape() : unpack non-word characters into CGI-compatible hex codes
                   9809: 
                   9810: =item *
                   9811: 
                   9812: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9813: 
1.243     albertel 9814: =back
                   9815: 
                   9816: =head1 PRIVATE SUBROUTINES
                   9817: 
                   9818: =head2 Underlying communication routines (Shouldn't call)
                   9819: 
                   9820: =over 4
                   9821: 
                   9822: =item *
                   9823: 
                   9824: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9825: 
                   9826: =item *
                   9827: 
                   9828: reply() : uses subreply to send a message to remote machine, logs all failures
                   9829: 
                   9830: =item *
                   9831: 
                   9832: critical() : passes a critical message to another server; if cannot
                   9833: get through then place message in connection buffer directory and
                   9834: returns con_delayed, if incapable of saving message, returns
                   9835: con_failed
                   9836: 
                   9837: =item *
                   9838: 
                   9839: reconlonc() : tries to reconnect lonc client processes.
                   9840: 
                   9841: =back
                   9842: 
                   9843: =head2 Resource Access Logging
                   9844: 
                   9845: =over 4
                   9846: 
                   9847: =item *
                   9848: 
                   9849: flushcourselogs() : flush (save) buffer logs and access logs
                   9850: 
                   9851: =item *
                   9852: 
                   9853: courselog($what) : save message for course in hash
                   9854: 
                   9855: =item *
                   9856: 
                   9857: courseacclog($what) : save message for course using &courselog().  Perform
                   9858: special processing for specific resource types (problems, exams, quizzes, etc).
                   9859: 
1.191     harris41 9860: =item *
                   9861: 
                   9862: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9863: as a PerlChildExitHandler
1.243     albertel 9864: 
                   9865: =back
                   9866: 
                   9867: =head2 Other
                   9868: 
                   9869: =over 4
                   9870: 
                   9871: =item *
                   9872: 
                   9873: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9874: 
                   9875: =back
                   9876: 
                   9877: =cut
1.877     foxr     9878: 

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