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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.983   ! raeburn     4: # $Id: lonnet.pm,v 1.982 2009/01/02 22:45:43 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.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.486     www        78: # use Date::Parse;
1.871     albertel   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    80:             $_64bit %env %protocol);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.977     amueller  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    153: 	print $fh "$local ($$): $message\n";
                    154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983   ! raeburn   184: sub get_server_timezone {
        !           185:     my ($cnum,$cdom) = @_;
        !           186:     my $home=&homeserver($cnum,$cdom);
        !           187:     if ($home ne 'no_host') {
        !           188:         my $cachetime = 24*3600;
        !           189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
        !           190:         if (defined($cached)) {
        !           191:             return $timezone;
        !           192:         } else {
        !           193:             my $timezone = &reply('servertimezone',$home);
        !           194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
        !           195:         }
        !           196:     }
        !           197: }
1.850     albertel  198: 
1.1       albertel  199: # -------------------------------------------------- Non-critical communication
                    200: sub subreply {
                    201:     my ($cmd,$server)=@_;
1.838     albertel  202:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      203:     #
                    204:     #  With loncnew process trimming, there's a timing hole between lonc server
                    205:     #  process exit and the master server picking up the listen on the AF_UNIX
                    206:     #  socket.  In that time interval, a lock file will exist:
                    207: 
                    208:     my $lockfile=$peerfile.".lock";
                    209:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    210: 	sleep(1);
                    211:     }
                    212:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      213:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      214:     #
1.550     foxr      215:     #   We'll give the connection a few tries before abandoning it.  If
                    216:     #   connection is not possible, we'll con_lost back to the client.
                    217:     #   
                    218:     my $client;
                    219:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    220: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    221: 				      Type    => SOCK_STREAM,
                    222: 				      Timeout => 10);
1.869     albertel  223: 	if ($client) {
1.550     foxr      224: 	    last;		# Connected!
1.850     albertel  225: 	} else {
1.853     albertel  226: 	    &create_connection(&hostname($server),$server);
1.550     foxr      227: 	}
1.850     albertel  228:         sleep(1);		# Try again later if failed connection.
1.550     foxr      229:     }
                    230:     my $answer;
                    231:     if ($client) {
1.704     albertel  232: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      233: 	$answer=<$client>;
                    234: 	if (!$answer) { $answer="con_lost"; }
                    235: 	chomp($answer);
                    236:     } else {
                    237: 	$answer = 'con_lost';	# Failed connection.
                    238:     }
1.1       albertel  239:     return $answer;
                    240: }
                    241: 
                    242: sub reply {
                    243:     my ($cmd,$server)=@_;
1.838     albertel  244:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  245:     my $answer=subreply($cmd,$server);
1.65      www       246:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  247:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       248:                 " $cmd to $server returned $answer</font>");
                    249:     }
1.1       albertel  250:     return $answer;
                    251: }
                    252: 
                    253: # ----------------------------------------------------------- Send USR1 to lonc
                    254: 
                    255: sub reconlonc {
1.891     albertel  256:     my ($lonid) = @_;
                    257:     my $hostname = &hostname($lonid);
                    258:     if ($lonid) {
                    259: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    260: 	if ($hostname && -e $peerfile) {
                    261: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    262: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    263: 					     Type    => SOCK_STREAM,
                    264: 					     Timeout => 10);
                    265: 	    if ($client) {
                    266: 		print $client ("reset_retries\n");
                    267: 		my $answer=<$client>;
                    268: 		#reset just this one.
                    269: 	    }
                    270: 	}
                    271: 	return;
                    272:     }
                    273: 
1.836     www       274:     &logthis("Trying to reconnect lonc");
1.1       albertel  275:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  276:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  277: 	my $loncpid=<$fh>;
                    278:         chomp($loncpid);
                    279:         if (kill 0 => $loncpid) {
                    280: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    281:             kill USR1 => $loncpid;
                    282:             sleep 1;
1.836     www       283:          } else {
1.12      www       284: 	    &logthis(
1.672     albertel  285:                "<font color=\"blue\">WARNING:".
1.12      www       286:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  287:         }
                    288:     } else {
1.836     www       289: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  290:     }
                    291: }
                    292: 
                    293: # ------------------------------------------------------ Critical communication
1.12      www       294: 
1.1       albertel  295: sub critical {
                    296:     my ($cmd,$server)=@_;
1.838     albertel  297:     unless (&hostname($server)) {
1.672     albertel  298:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       299:                " Critical message to unknown server ($server)</font>");
                    300:         return 'no_such_host';
                    301:     }
1.1       albertel  302:     my $answer=reply($cmd,$server);
                    303:     if ($answer eq 'con_lost') {
                    304: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  305: 	my $answer=reply($cmd,$server);
1.1       albertel  306:         if ($answer eq 'con_lost') {
                    307:             my $now=time;
                    308:             my $middlename=$cmd;
1.5       www       309:             $middlename=substr($middlename,0,16);
1.1       albertel  310:             $middlename=~s/\W//g;
                    311:             my $dfilename=
1.305     www       312:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    313:             $dumpcount++;
1.1       albertel  314:             {
1.448     albertel  315: 		my $dfh;
                    316: 		if (open($dfh,">$dfilename")) {
                    317: 		    print $dfh "$cmd\n"; 
                    318: 		    close($dfh);
                    319: 		}
1.1       albertel  320:             }
                    321:             sleep 2;
                    322:             my $wcmd='';
                    323:             {
1.448     albertel  324: 		my $dfh;
                    325: 		if (open($dfh,"<$dfilename")) {
                    326: 		    $wcmd=<$dfh>; 
                    327: 		    close($dfh);
                    328: 		}
1.1       albertel  329:             }
                    330:             chomp($wcmd);
1.7       www       331:             if ($wcmd eq $cmd) {
1.672     albertel  332: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       333:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  334:                 &logperm("D:$server:$cmd");
                    335: 	        return 'con_delayed';
                    336:             } else {
1.672     albertel  337:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       338:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  339:                 &logperm("F:$server:$cmd");
                    340:                 return 'con_failed';
                    341:             }
                    342:         }
                    343:     }
                    344:     return $answer;
1.405     albertel  345: }
                    346: 
1.755     albertel  347: # ------------------------------------------- check if return value is an error
                    348: 
                    349: sub error {
                    350:     my ($result) = @_;
1.756     albertel  351:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  352: 	if ($2 == 2) { return undef; }
                    353: 	return $1;
                    354:     }
                    355:     return undef;
                    356: }
                    357: 
1.783     albertel  358: sub convert_and_load_session_env {
                    359:     my ($lonidsdir,$handle)=@_;
                    360:     my @profile;
                    361:     {
1.917     albertel  362: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    363: 	if (!$opened) {
1.915     albertel  364: 	    return 0;
                    365: 	}
1.783     albertel  366: 	flock($idf,LOCK_SH);
                    367: 	@profile=<$idf>;
                    368: 	close($idf);
                    369:     }
                    370:     my %temp_env;
                    371:     foreach my $line (@profile) {
1.786     albertel  372: 	if ($line !~ m/=/) {
                    373: 	    return 0;
                    374: 	}
1.783     albertel  375: 	chomp($line);
                    376: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    377: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    378:     }
                    379:     unlink("$lonidsdir/$handle.id");
                    380:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    381: 	    0640)) {
                    382: 	%disk_env = %temp_env;
                    383: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    384: 	untie(%disk_env);
                    385:     }
1.786     albertel  386:     return 1;
1.783     albertel  387: }
                    388: 
1.374     www       389: # ------------------------------------------- Transfer profile into environment
1.780     albertel  390: my $env_loaded;
                    391: sub transfer_profile_to_env {
1.788     albertel  392:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    393:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       394: 
1.720     albertel  395:     if (!defined($lonidsdir)) {
                    396: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    397:     }
                    398:     if (!defined($handle)) {
                    399:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    400:     }
                    401: 
1.786     albertel  402:     my $convert;
                    403:     {
1.917     albertel  404:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    405: 	if (!$opened) {
1.915     albertel  406: 	    return;
                    407: 	}
1.786     albertel  408: 	flock($idf,LOCK_SH);
                    409: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    410: 		&GDBM_READER(),0640)) {
                    411: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    412: 	    untie(%disk_env);
                    413: 	} else {
                    414: 	    $convert = 1;
                    415: 	}
                    416:     }
                    417:     if ($convert) {
                    418: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    419: 	    &logthis("Failed to load session, or convert session.");
                    420: 	}
1.374     www       421:     }
1.783     albertel  422: 
1.786     albertel  423:     my %remove;
1.783     albertel  424:     while ( my $envname = each(%env) ) {
1.433     matthew   425:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    426:             if ($time < time-300) {
1.783     albertel  427:                 $remove{$key}++;
1.433     matthew   428:             }
                    429:         }
                    430:     }
1.783     albertel  431: 
1.619     albertel  432:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  433:     $env_loaded=1;
1.783     albertel  434:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   435:         &delenv($expired_key);
1.374     www       436:     }
1.1       albertel  437: }
                    438: 
1.916     albertel  439: # ---------------------------------------------------- Check for valid session 
                    440: sub check_for_valid_session {
                    441:     my ($r) = @_;
                    442:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    443:     my $lonid=$cookies{'lonID'};
                    444:     return undef if (!$lonid);
                    445: 
                    446:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    447:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    448:     return undef if (!-e "$lonidsdir/$handle.id");
                    449: 
1.917     albertel  450:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    451:     return undef if (!$opened);
1.916     albertel  452: 
                    453:     flock($idf,LOCK_SH);
                    454:     my %disk_env;
                    455:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    456: 	    &GDBM_READER(),0640)) {
                    457: 	return undef;	
                    458:     }
                    459: 
                    460:     if (!defined($disk_env{'user.name'})
                    461: 	|| !defined($disk_env{'user.domain'})) {
                    462: 	return undef;
                    463:     }
                    464:     return $handle;
                    465: }
                    466: 
1.830     albertel  467: sub timed_flock {
                    468:     my ($file,$lock_type) = @_;
                    469:     my $failed=0;
                    470:     eval {
                    471: 	local $SIG{__DIE__}='DEFAULT';
                    472: 	local $SIG{ALRM}=sub {
                    473: 	    $failed=1;
                    474: 	    die("failed lock");
                    475: 	};
                    476: 	alarm(13);
                    477: 	flock($file,$lock_type);
                    478: 	alarm(0);
                    479:     };
                    480:     if ($failed) {
                    481: 	return undef;
                    482:     } else {
                    483: 	return 1;
                    484:     }
                    485: }
                    486: 
1.5       www       487: # ---------------------------------------------------------- Append Environment
                    488: 
                    489: sub appenv {
1.949     raeburn   490:     my ($newenv,$roles) = @_;
                    491:     if (ref($newenv) eq 'HASH') {
                    492:         foreach my $key (keys(%{$newenv})) {
                    493:             my $refused = 0;
                    494: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    495:                 $refused = 1;
                    496:                 if (ref($roles) eq 'ARRAY') {
                    497:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    498:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    499:                         $refused = 0;
                    500:                     }
                    501:                 }
                    502:             }
                    503:             if ($refused) {
                    504:                 &logthis("<font color=\"blue\">WARNING: ".
                    505:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    506:                          .'</font>');
                    507: 	        delete($newenv->{$key});
                    508:             } else {
                    509:                 $env{$key}=$newenv->{$key};
                    510:             }
                    511:         }
                    512:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    513:         if ($opened
                    514: 	    && &timed_flock($env_file,LOCK_EX)
                    515: 	    &&
                    516: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    517: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    518: 	    while (my ($key,$value) = each(%{$newenv})) {
                    519: 	        $disk_env{$key} = $value;
                    520: 	    }
                    521: 	    untie(%disk_env);
1.35      www       522:         }
1.191     harris41  523:     }
1.56      www       524:     return 'ok';
                    525: }
                    526: # ----------------------------------------------------- Delete from Environment
                    527: 
                    528: sub delenv {
                    529:     my $delthis=shift;
                    530:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  531:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       532:                 "Attempt to delete from environment ".$delthis);
                    533:         return 'error';
                    534:     }
1.917     albertel  535:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    536:     if ($opened
1.915     albertel  537: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  538: 	&&
                    539: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    540: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  541: 	foreach my $key (keys(%disk_env)) {
1.981     raeburn   542: 	    if ($key=~/^\Q$delthis\E/) { 
1.915     albertel  543: 		delete($env{$key});
                    544: 		delete($disk_env{$key});
                    545: 	    }
1.448     albertel  546: 	}
1.783     albertel  547: 	untie(%disk_env);
1.5       www       548:     }
                    549:     return 'ok';
1.369     albertel  550: }
                    551: 
1.790     albertel  552: sub get_env_multiple {
                    553:     my ($name) = @_;
                    554:     my @values;
                    555:     if (defined($env{$name})) {
                    556:         # exists is it an array
                    557:         if (ref($env{$name})) {
                    558:             @values=@{ $env{$name} };
                    559:         } else {
                    560:             $values[0]=$env{$name};
                    561:         }
                    562:     }
                    563:     return(@values);
                    564: }
                    565: 
1.958     www       566: # ------------------------------------------------------------------- Locking
                    567: 
                    568: sub set_lock {
                    569:     my ($text)=@_;
                    570:     $locknum++;
                    571:     my $id=$$.'-'.$locknum;
                    572:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    573:              'session.lock.'.$id => $text});
                    574:     return $id;
                    575: }
                    576: 
                    577: sub get_locks {
                    578:     my $num=0;
                    579:     my %texts=();
                    580:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    581:        if ($lock=~/\w/) {
                    582:           $num++;
                    583:           $texts{$lock}=$env{'session.lock.'.$lock};
                    584:        }
                    585:    }
                    586:    return ($num,%texts);
                    587: }
                    588: 
                    589: sub remove_lock {
                    590:     my ($id)=@_;
                    591:     my $newlocks='';
                    592:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    593:        if (($lock=~/\w/) && ($lock ne $id)) {
                    594:           $newlocks.=','.$lock;
                    595:        }
                    596:     }
                    597:     &appenv({'session.locks' => $newlocks});
                    598:     &delenv('session.lock.'.$id);
                    599: }
                    600: 
                    601: sub remove_all_locks {
                    602:     my $activelocks=$env{'session.locks'};
                    603:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    604:        if ($lock=~/\w/) {
                    605:           &remove_lock($lock);
                    606:        }
                    607:     }
                    608: }
                    609: 
                    610: 
1.369     albertel  611: # ------------------------------------------ Find out current server userload
                    612: sub userload {
                    613:     my $numusers=0;
                    614:     {
                    615: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    616: 	my $filename;
                    617: 	my $curtime=time;
                    618: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  619: 	    next if ($filename eq '.' || $filename eq '..');
                    620: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  621: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  622: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  623: 	}
                    624: 	closedir(LONIDS);
                    625:     }
                    626:     my $userloadpercent=0;
                    627:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    628:     if ($maxuserload) {
1.371     albertel  629: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  630:     }
1.372     albertel  631:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  632:     return $userloadpercent;
1.283     www       633: }
                    634: 
                    635: # ------------------------------------------ Fight off request when overloaded
                    636: 
                    637: sub overloaderror {
                    638:     my ($r,$checkserver)=@_;
                    639:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    640:     my $loadavg;
                    641:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  642:        open(my $loadfile,'/proc/loadavg');
1.283     www       643:        $loadavg=<$loadfile>;
                    644:        $loadavg =~ s/\s.*//g;
1.285     matthew   645:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  646:        close($loadfile);
1.283     www       647:     } else {
                    648:        $loadavg=&reply('load',$checkserver);
                    649:     }
1.285     matthew   650:     my $overload=$loadavg-100;
1.283     www       651:     if ($overload>0) {
1.285     matthew   652: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       653:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       654:         return 413;
1.283     www       655:     }    
                    656:     return '';
1.5       www       657: }
1.1       albertel  658: 
                    659: # ------------------------------ Find server with least workload from spare.tab
1.11      www       660: 
1.1       albertel  661: sub spareserver {
1.670     albertel  662:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  663:     my $spare_server;
1.370     albertel  664:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  665:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    666:                                                      :  $userloadpercent;
                    667:     
                    668:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    669: 	($spare_server, $lowest_load) =
                    670: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    671:     }
                    672: 
                    673:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    674: 
                    675:     if (!$found_server) {
                    676: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    677: 	    ($spare_server, $lowest_load) =
                    678: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    679: 	}
                    680:     }
                    681: 
                    682:     if (!$want_server_name) {
1.968     raeburn   683:         my $protocol = 'http';
                    684:         if ($protocol{$spare_server} eq 'https') {
                    685:             $protocol = $protocol{$spare_server};
                    686:         }
                    687: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  688:     }
                    689:     return $spare_server;
                    690: }
                    691: 
                    692: sub compare_server_load {
                    693:     my ($try_server, $spare_server, $lowest_load) = @_;
                    694: 
                    695:     my $loadans     = &reply('load',    $try_server);
                    696:     my $userloadans = &reply('userload',$try_server);
                    697: 
                    698:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    699: 	next; #didn't get a number from the server
                    700:     }
                    701: 
                    702:     my $load;
                    703:     if ($loadans =~ /\d/) {
                    704: 	if ($userloadans =~ /\d/) {
                    705: 	    #both are numbers, pick the bigger one
                    706: 	    $load = ($loadans > $userloadans) ? $loadans 
                    707: 		                              : $userloadans;
1.411     albertel  708: 	} else {
1.784     albertel  709: 	    $load = $loadans;
1.411     albertel  710: 	}
1.784     albertel  711:     } else {
                    712: 	$load = $userloadans;
                    713:     }
                    714: 
                    715:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    716: 	$spare_server = $try_server;
                    717: 	$lowest_load  = $load;
1.370     albertel  718:     }
1.784     albertel  719:     return ($spare_server,$lowest_load);
1.202     matthew   720: }
1.914     albertel  721: 
                    722: # --------------------------- ask offload servers if user already has a session
                    723: sub find_existing_session {
                    724:     my ($udom,$uname) = @_;
                    725:     foreach my $try_server (@{ $spareid{'primary'} },
                    726: 			    @{ $spareid{'default'} }) {
                    727: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    728:     }
                    729:     return;
                    730: }
                    731: 
                    732: # -------------------------------- ask if server already has a session for user
                    733: sub has_user_session {
                    734:     my ($lonid,$udom,$uname) = @_;
                    735:     my $result = &reply(join(':','userhassession',
                    736: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    737:     return 1 if ($result eq 'ok');
                    738: 
                    739:     return 0;
                    740: }
                    741: 
1.202     matthew   742: # --------------------------------------------- Try to change a user's password
                    743: 
                    744: sub changepass {
1.799     raeburn   745:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   746:     $currentpass = &escape($currentpass);
                    747:     $newpass     = &escape($newpass);
1.799     raeburn   748:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   749: 		       $server);
                    750:     if (! $answer) {
                    751: 	&logthis("No reply on password change request to $server ".
                    752: 		 "by $uname in domain $udom.");
                    753:     } elsif ($answer =~ "^ok") {
                    754:         &logthis("$uname in $udom successfully changed their password ".
                    755: 		 "on $server.");
                    756:     } elsif ($answer =~ "^pwchange_failure") {
                    757: 	&logthis("$uname in $udom was unable to change their password ".
                    758: 		 "on $server.  The action was blocked by either lcpasswd ".
                    759: 		 "or pwchange");
                    760:     } elsif ($answer =~ "^non_authorized") {
                    761:         &logthis("$uname in $udom did not get their password correct when ".
                    762: 		 "attempting to change it on $server.");
                    763:     } elsif ($answer =~ "^auth_mode_error") {
                    764:         &logthis("$uname in $udom attempted to change their password despite ".
                    765: 		 "not being locally or internally authenticated on $server.");
                    766:     } elsif ($answer =~ "^unknown_user") {
                    767:         &logthis("$uname in $udom attempted to change their password ".
                    768: 		 "on $server but were unable to because $server is not ".
                    769: 		 "their home server.");
                    770:     } elsif ($answer =~ "^refused") {
                    771: 	&logthis("$server refused to change $uname in $udom password because ".
                    772: 		 "it was sent an unencrypted request to change the password.");
                    773:     }
                    774:     return $answer;
1.1       albertel  775: }
                    776: 
1.169     harris41  777: # ----------------------- Try to determine user's current authentication scheme
                    778: 
                    779: sub queryauthenticate {
                    780:     my ($uname,$udom)=@_;
1.456     albertel  781:     my $uhome=&homeserver($uname,$udom);
                    782:     if (!$uhome) {
                    783: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    784: 	return 'no_host';
                    785:     }
                    786:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    787:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    788: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  789:     }
1.456     albertel  790:     return $answer;
1.169     harris41  791: }
                    792: 
1.1       albertel  793: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       794: 
1.1       albertel  795: sub authenticate {
1.952     raeburn   796:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  797:     $upass=&escape($upass);
                    798:     $uname= &LONCAPA::clean_username($uname);
1.836     www       799:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   800:     my $newhome;
1.836     www       801:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    802: # Maybe the machine was offline and only re-appeared again recently?
                    803:         &reconlonc();
                    804: # One more
1.952     raeburn   805: 	$uhome=&homeserver($uname,$udom,1);
                    806:         if (($uhome eq 'no_host') && $checkdefauth) {
                    807:             if (defined(&domain($udom,'primary'))) {
                    808:                 $newhome=&domain($udom,'primary');
                    809:             }
                    810:             if ($newhome ne '') {
                    811:                 $uhome = $newhome;
                    812:             }
                    813:         }
1.836     www       814: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    815: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   816: 	    return 'no_host';
                    817:         }
1.1       albertel  818:     }
1.952     raeburn   819:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  820:     if ($answer eq 'authorized') {
1.952     raeburn   821:         if ($newhome) {
                    822:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    823:             return 'no_account_on_host'; 
                    824:         } else {
                    825:             &logthis("User $uname at $udom authorized by $uhome");
                    826:             return $uhome;
                    827:         }
1.471     albertel  828:     }
                    829:     if ($answer eq 'non_authorized') {
                    830: 	&logthis("User $uname at $udom rejected by $uhome");
                    831: 	return 'no_host'; 
1.9       www       832:     }
1.471     albertel  833:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  834:     return 'no_host';
                    835: }
                    836: 
                    837: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       838: 
1.599     albertel  839: my %homecache;
1.1       albertel  840: sub homeserver {
1.230     stredwic  841:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  842:     my $index="$uname:$udom";
1.426     albertel  843: 
1.599     albertel  844:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  845: 
                    846:     my %servers = &get_servers($udom,'library');
                    847:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  848:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  849: 		 exists($badServerCache{$tryserver}));
1.841     albertel  850: 
                    851: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    852: 	if ($answer eq 'found') {
                    853: 	    delete($badServerCache{$tryserver}); 
                    854: 	    return $homecache{$index}=$tryserver;
                    855: 	} elsif ($answer eq 'no_host') {
                    856: 	    $badServerCache{$tryserver}=1;
                    857: 	}
1.1       albertel  858:     }    
                    859:     return 'no_host';
1.70      www       860: }
                    861: 
                    862: # ------------------------------------- Find the usernames behind a list of IDs
                    863: 
                    864: sub idget {
                    865:     my ($udom,@ids)=@_;
                    866:     my %returnhash=();
                    867:     
1.841     albertel  868:     my %servers = &get_servers($udom,'library');
                    869:     foreach my $tryserver (keys(%servers)) {
                    870: 	my $idlist=join('&',@ids);
                    871: 	$idlist=~tr/A-Z/a-z/; 
                    872: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    873: 	my @answer=();
                    874: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    875: 	    @answer=split(/\&/,$reply);
                    876: 	}                    ;
                    877: 	my $i;
                    878: 	for ($i=0;$i<=$#ids;$i++) {
                    879: 	    if ($answer[$i]) {
                    880: 		$returnhash{$ids[$i]}=$answer[$i];
                    881: 	    } 
                    882: 	}
                    883:     } 
1.70      www       884:     return %returnhash;
                    885: }
                    886: 
                    887: # ------------------------------------- Find the IDs behind a list of usernames
                    888: 
                    889: sub idrget {
                    890:     my ($udom,@unames)=@_;
                    891:     my %returnhash=();
1.800     albertel  892:     foreach my $uname (@unames) {
                    893:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  894:     }
1.70      www       895:     return %returnhash;
                    896: }
                    897: 
                    898: # ------------------------------- Store away a list of names and associated IDs
                    899: 
                    900: sub idput {
                    901:     my ($udom,%ids)=@_;
                    902:     my %servers=();
1.800     albertel  903:     foreach my $uname (keys(%ids)) {
                    904: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    905:         my $uhom=&homeserver($uname,$udom);
1.70      www       906:         if ($uhom ne 'no_host') {
1.800     albertel  907:             my $id=&escape($ids{$uname});
1.70      www       908:             $id=~tr/A-Z/a-z/;
1.800     albertel  909:             my $esc_unam=&escape($uname);
1.70      www       910: 	    if ($servers{$uhom}) {
1.800     albertel  911: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       912:             } else {
1.800     albertel  913:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       914:             }
                    915:         }
1.191     harris41  916:     }
1.800     albertel  917:     foreach my $server (keys(%servers)) {
                    918:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  919:     }
1.344     www       920: }
                    921: 
1.806     raeburn   922: # ------------------------------------------- get items from domain db files   
                    923: 
                    924: sub get_dom {
1.860     raeburn   925:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   926:     my $items='';
                    927:     foreach my $item (@$storearr) {
                    928:         $items.=&escape($item).'&';
                    929:     }
                    930:     $items=~s/\&$//;
1.860     raeburn   931:     if (!$udom) {
                    932:         $udom=$env{'user.domain'};
                    933:         if (defined(&domain($udom,'primary'))) {
                    934:             $uhome=&domain($udom,'primary');
                    935:         } else {
1.874     albertel  936:             undef($uhome);
1.860     raeburn   937:         }
                    938:     } else {
                    939:         if (!$uhome) {
                    940:             if (defined(&domain($udom,'primary'))) {
                    941:                 $uhome=&domain($udom,'primary');
                    942:             }
                    943:         }
                    944:     }
                    945:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   946:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   947:         my %returnhash;
1.875     albertel  948:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   949:             return %returnhash;
                    950:         }
1.806     raeburn   951:         my @pairs=split(/\&/,$rep);
                    952:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    953:             return @pairs;
                    954:         }
                    955:         my $i=0;
                    956:         foreach my $item (@$storearr) {
                    957:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    958:             $i++;
                    959:         }
                    960:         return %returnhash;
                    961:     } else {
1.880     banghart  962:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   963:     }
                    964: }
                    965: 
                    966: # -------------------------------------------- put items in domain db files 
                    967: 
                    968: sub put_dom {
1.860     raeburn   969:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    970:     if (!$udom) {
                    971:         $udom=$env{'user.domain'};
                    972:         if (defined(&domain($udom,'primary'))) {
                    973:             $uhome=&domain($udom,'primary');
                    974:         } else {
1.874     albertel  975:             undef($uhome);
1.860     raeburn   976:         }
                    977:     } else {
                    978:         if (!$uhome) {
                    979:             if (defined(&domain($udom,'primary'))) {
                    980:                 $uhome=&domain($udom,'primary');
                    981:             }
                    982:         }
                    983:     } 
                    984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   985:         my $items='';
                    986:         foreach my $item (keys(%$storehash)) {
                    987:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    988:         }
                    989:         $items=~s/\&$//;
                    990:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    991:     } else {
1.860     raeburn   992:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   993:     }
                    994: }
                    995: 
1.837     raeburn   996: sub retrieve_inst_usertypes {
                    997:     my ($udom) = @_;
                    998:     my (%returnhash,@order);
1.846     albertel  999:     if (defined(&domain($udom,'primary'))) {
                   1000:         my $uhome=&domain($udom,'primary');
1.837     raeburn  1001:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn  1002:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1003:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1004:             return (\%returnhash,\@order);
                   1005:         }
1.837     raeburn  1006:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1007:         my @pairs=split(/\&/,$hashitems);
                   1008:         foreach my $item (@pairs) {
                   1009:             my ($key,$value)=split(/=/,$item,2);
                   1010:             $key = &unescape($key);
                   1011:             next if ($key =~ /^error: 2 /);
                   1012:             $returnhash{$key}=&thaw_unescape($value);
                   1013:         }
                   1014:         my @esc_order = split(/\&/,$orderitems);
                   1015:         foreach my $item (@esc_order) {
                   1016:             push(@order,&unescape($item));
                   1017:         }
                   1018:     } else {
                   1019:         &logthis("get_dom failed - no primary domain server for $udom");
                   1020:     }
                   1021:     return (\%returnhash,\@order);
                   1022: }
                   1023: 
1.868     raeburn  1024: sub is_domainimage {
                   1025:     my ($url) = @_;
                   1026:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1027:         if (&domain($1) ne '') {
                   1028:             return '1';
                   1029:         }
                   1030:     }
                   1031:     return;
                   1032: }
                   1033: 
1.899     raeburn  1034: sub inst_directory_query {
                   1035:     my ($srch) = @_;
                   1036:     my $udom = $srch->{'srchdomain'};
                   1037:     my %results;
                   1038:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1039:     my $outcome;
1.899     raeburn  1040:     if ($homeserver ne '') {
1.904     albertel 1041: 	my $queryid=&reply("querysend:instdirsearch:".
                   1042: 			   &escape($srch->{'srchby'}).':'.
                   1043: 			   &escape($srch->{'srchterm'}).':'.
                   1044: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1045: 	my $host=&hostname($homeserver);
                   1046: 	if ($queryid !~/^\Q$host\E\_/) {
                   1047: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1048: 	    return;
                   1049: 	}
                   1050: 	my $response = &get_query_reply($queryid);
                   1051: 	my $maxtries = 5;
                   1052: 	my $tries = 1;
                   1053: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1054: 	    $response = &get_query_reply($queryid);
                   1055: 	    $tries ++;
                   1056: 	}
                   1057: 
                   1058:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1059:             if ($response eq 'unavailable') {
                   1060:                 $outcome = $response;
                   1061:             } else {
                   1062:                 $outcome = 'ok';
                   1063:                 my @matches = split(/\n/,$response);
                   1064:                 foreach my $match (@matches) {
                   1065:                     my ($key,$value) = split(/=/,$match);
                   1066:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1067:                 }
1.899     raeburn  1068:             }
                   1069:         }
                   1070:     }
1.909     raeburn  1071:     return ($outcome,%results);
1.899     raeburn  1072: }
                   1073: 
                   1074: sub usersearch {
                   1075:     my ($srch) = @_;
                   1076:     my $dom = $srch->{'srchdomain'};
                   1077:     my %results;
                   1078:     my %libserv = &all_library();
                   1079:     my $query = 'usersearch';
                   1080:     foreach my $tryserver (keys(%libserv)) {
                   1081:         if (&host_domain($tryserver) eq $dom) {
                   1082:             my $host=&hostname($tryserver);
                   1083:             my $queryid=
1.911     raeburn  1084:                 &reply("querysend:".&escape($query).':'.
                   1085:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1086:                        &escape($srch->{'srchtype'}).':'.
                   1087:                        &escape($srch->{'srchterm'}),$tryserver);
                   1088:             if ($queryid !~/^\Q$host\E\_/) {
                   1089:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1090:                 next;
1.899     raeburn  1091:             }
                   1092:             my $reply = &get_query_reply($queryid);
                   1093:             my $maxtries = 1;
                   1094:             my $tries = 1;
                   1095:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1096:                 $reply = &get_query_reply($queryid);
                   1097:                 $tries ++;
                   1098:             }
                   1099:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1100:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1101:             } else {
1.911     raeburn  1102:                 my @matches;
                   1103:                 if ($reply =~ /\n/) {
                   1104:                     @matches = split(/\n/,$reply);
                   1105:                 } else {
                   1106:                     @matches = split(/\&/,$reply);
                   1107:                 }
1.899     raeburn  1108:                 foreach my $match (@matches) {
                   1109:                     my ($uname,$udom,%userhash);
1.911     raeburn  1110:                     foreach my $entry (split(/:/,$match)) {
                   1111:                         my ($key,$value) =
                   1112:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1113:                         $userhash{$key} = $value;
                   1114:                         if ($key eq 'username') {
                   1115:                             $uname = $value;
                   1116:                         } elsif ($key eq 'domain') {
                   1117:                             $udom = $value;
1.911     raeburn  1118:                         }
1.899     raeburn  1119:                     }
                   1120:                     $results{$uname.':'.$udom} = \%userhash;
                   1121:                 }
                   1122:             }
                   1123:         }
                   1124:     }
                   1125:     return %results;
                   1126: }
                   1127: 
1.912     raeburn  1128: sub get_instuser {
                   1129:     my ($udom,$uname,$id) = @_;
                   1130:     my $homeserver = &domain($udom,'primary');
                   1131:     my ($outcome,%results);
                   1132:     if ($homeserver ne '') {
                   1133:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1134:                            &escape($id).':'.&escape($udom),$homeserver);
                   1135:         my $host=&hostname($homeserver);
                   1136:         if ($queryid !~/^\Q$host\E\_/) {
                   1137:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1138:             return;
                   1139:         }
                   1140:         my $response = &get_query_reply($queryid);
                   1141:         my $maxtries = 5;
                   1142:         my $tries = 1;
                   1143:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1144:             $response = &get_query_reply($queryid);
                   1145:             $tries ++;
                   1146:         }
                   1147:         if (!&error($response) && $response ne 'refused') {
                   1148:             if ($response eq 'unavailable') {
                   1149:                 $outcome = $response;
                   1150:             } else {
                   1151:                 $outcome = 'ok';
                   1152:                 my @matches = split(/\n/,$response);
                   1153:                 foreach my $match (@matches) {
                   1154:                     my ($key,$value) = split(/=/,$match);
                   1155:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1156:                 }
                   1157:             }
                   1158:         }
                   1159:     }
                   1160:     my %userinfo;
                   1161:     if (ref($results{$uname}) eq 'HASH') {
                   1162:         %userinfo = %{$results{$uname}};
                   1163:     } 
                   1164:     return ($outcome,%userinfo);
                   1165: }
                   1166: 
                   1167: sub inst_rulecheck {
1.923     raeburn  1168:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1169:     my %returnhash;
                   1170:     if ($udom ne '') {
                   1171:         if (ref($rules) eq 'ARRAY') {
                   1172:             @{$rules} = map {&escape($_);} (@{$rules});
                   1173:             my $rulestr = join(':',@{$rules});
                   1174:             my $homeserver=&domain($udom,'primary');
                   1175:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1176:                 my $response;
                   1177:                 if ($item eq 'username') {                
                   1178:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1179:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1180:                                               $homeserver));
1.923     raeburn  1181:                 } elsif ($item eq 'id') {
                   1182:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1183:                                               ':'.&escape($id).':'.$rulestr,
                   1184:                                               $homeserver));
1.945     raeburn  1185:                 } elsif ($item eq 'selfcreate') {
                   1186:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1187:                                                &escape($udom).':'.&escape($uname).
                   1188:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1189:                 }
1.912     raeburn  1190:                 if ($response ne 'refused') {
                   1191:                     my @pairs=split(/\&/,$response);
                   1192:                     foreach my $item (@pairs) {
                   1193:                         my ($key,$value)=split(/=/,$item,2);
                   1194:                         $key = &unescape($key);
                   1195:                         next if ($key =~ /^error: 2 /);
                   1196:                         $returnhash{$key}=&thaw_unescape($value);
                   1197:                     }
                   1198:                 }
                   1199:             }
                   1200:         }
                   1201:     }
                   1202:     return %returnhash;
                   1203: }
                   1204: 
                   1205: sub inst_userrules {
1.923     raeburn  1206:     my ($udom,$check) = @_;
1.912     raeburn  1207:     my (%ruleshash,@ruleorder);
                   1208:     if ($udom ne '') {
                   1209:         my $homeserver=&domain($udom,'primary');
                   1210:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1211:             my $response;
                   1212:             if ($check eq 'id') {
                   1213:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1214:                                  $homeserver);
1.943     raeburn  1215:             } elsif ($check eq 'email') {
                   1216:                 $response=&reply('instemailrules:'.&escape($udom),
                   1217:                                  $homeserver);
1.923     raeburn  1218:             } else {
                   1219:                 $response=&reply('instuserrules:'.&escape($udom),
                   1220:                                  $homeserver);
                   1221:             }
1.912     raeburn  1222:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1223:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1224:                 ($response ne 'no_such_host')) {
                   1225:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1226:                 my @pairs=split(/\&/,$hashitems);
                   1227:                 foreach my $item (@pairs) {
                   1228:                     my ($key,$value)=split(/=/,$item,2);
                   1229:                     $key = &unescape($key);
                   1230:                     next if ($key =~ /^error: 2 /);
                   1231:                     $ruleshash{$key}=&thaw_unescape($value);
                   1232:                 }
                   1233:                 my @esc_order = split(/\&/,$orderitems);
                   1234:                 foreach my $item (@esc_order) {
                   1235:                     push(@ruleorder,&unescape($item));
                   1236:                 }
                   1237:             }
                   1238:         }
                   1239:     }
                   1240:     return (\%ruleshash,\@ruleorder);
                   1241: }
                   1242: 
1.976     raeburn  1243: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1244: 
                   1245: sub get_domain_defaults {
                   1246:     my ($domain) = @_;
                   1247:     my $cachetime = 60*60*24;
                   1248:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1249:     if (defined($cached)) {
                   1250:         if (ref($result) eq 'HASH') {
                   1251:             return %{$result};
                   1252:         }
                   1253:     }
                   1254:     my %domdefaults;
                   1255:     my %domconfig =
1.976     raeburn  1256:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1257:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1258:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1259:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1260:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1261:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
                   1262:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'}
1.943     raeburn  1263:     } else {
                   1264:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1265:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1266:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1267:     }
1.976     raeburn  1268:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1269:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1270:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1271:         } else {
                   1272:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1273:         } 
                   1274:         my @usertools = ('aboutme','blog','portfolio');
                   1275:         foreach my $item (@usertools) {
                   1276:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1277:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1278:             }
                   1279:         }
                   1280:     }
1.943     raeburn  1281:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1282:                                   $cachetime);
                   1283:     return %domdefaults;
                   1284: }
                   1285: 
1.344     www      1286: # --------------------------------------------------- Assign a key to a student
                   1287: 
                   1288: sub assign_access_key {
1.364     www      1289: #
                   1290: # a valid key looks like uname:udom#comments
                   1291: # comments are being appended
                   1292: #
1.498     www      1293:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1294:     $kdom=
1.620     albertel 1295:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1296:     $knum=
1.620     albertel 1297:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1298:     $cdom=
1.620     albertel 1299:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1300:     $cnum=
1.620     albertel 1301:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1302:     $udom=$env{'user.name'} unless (defined($udom));
                   1303:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1304:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1305:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1306:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1307:                                                   # assigned to this person
                   1308:                                                   # - this should not happen,
1.345     www      1309:                                                   # unless something went wrong
                   1310:                                                   # the first time around
                   1311: # ready to assign
1.364     www      1312:         $logentry=$1.'; '.$logentry;
1.496     www      1313:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1314:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1315: # key now belongs to user
1.346     www      1316: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1317:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1318:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1319:                 return 'ok';
                   1320:             } else {
                   1321:                 return 
                   1322:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1323: 	    }
                   1324:         } else {
                   1325:             return 'error: Could not assign key, try again later.';
                   1326:         }
1.364     www      1327:     } elsif (!$existing{$ckey}) {
1.345     www      1328: # the key does not exist
                   1329: 	return 'error: The key does not exist';
                   1330:     } else {
                   1331: # the key is somebody else's
                   1332: 	return 'error: The key is already in use';
                   1333:     }
1.344     www      1334: }
                   1335: 
1.364     www      1336: # ------------------------------------------ put an additional comment on a key
                   1337: 
                   1338: sub comment_access_key {
                   1339: #
                   1340: # a valid key looks like uname:udom#comments
                   1341: # comments are being appended
                   1342: #
                   1343:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1344:     $cdom=
1.620     albertel 1345:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1346:     $cnum=
1.620     albertel 1347:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1348:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1349:     if ($existing{$ckey}) {
                   1350:         $existing{$ckey}.='; '.$logentry;
                   1351: # ready to assign
1.367     www      1352:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1353:                                                  $cdom,$cnum) eq 'ok') {
                   1354: 	    return 'ok';
                   1355:         } else {
                   1356: 	    return 'error: Count not store comment.';
                   1357:         }
                   1358:     } else {
                   1359: # the key does not exist
                   1360: 	return 'error: The key does not exist';
                   1361:     }
                   1362: }
                   1363: 
1.344     www      1364: # ------------------------------------------------------ Generate a set of keys
                   1365: 
                   1366: sub generate_access_keys {
1.364     www      1367:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1368:     $cdom=
1.620     albertel 1369:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1370:     $cnum=
1.620     albertel 1371:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1372:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1373:     unless (($cdom) && ($cnum)) { return 0; }
                   1374:     if ($number>10000) { return 0; }
                   1375:     sleep(2); # make sure don't get same seed twice
                   1376:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1377:     my $total=0;
                   1378:     for (my $i=1;$i<=$number;$i++) {
                   1379:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1380:                   sprintf("%lx",int(100000*rand)).'-'.
                   1381:                   sprintf("%lx",int(100000*rand));
                   1382:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1383:        $newkey=~s/0/h/g; # and also 0 and O
                   1384:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1385:        if ($existing{$newkey}) {
                   1386:            $i--;
                   1387:        } else {
1.364     www      1388: 	  if (&put('accesskeys',
                   1389:               { $newkey => '# generated '.localtime().
1.620     albertel 1390:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1391:                            '; '.$logentry },
                   1392: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1393:               $total++;
                   1394: 	  }
                   1395:        }
                   1396:     }
1.620     albertel 1397:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1398:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1399:     return $total;
                   1400: }
                   1401: 
                   1402: # ------------------------------------------------------- Validate an accesskey
                   1403: 
                   1404: sub validate_access_key {
                   1405:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1406:     $cdom=
1.620     albertel 1407:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1408:     $cnum=
1.620     albertel 1409:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1410:     $udom=$env{'user.domain'} unless (defined($udom));
                   1411:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1412:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1413:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1414: }
                   1415: 
                   1416: # ------------------------------------- Find the section of student in a course
1.652     albertel 1417: sub devalidate_getsection_cache {
                   1418:     my ($udom,$unam,$courseid)=@_;
                   1419:     my $hashid="$udom:$unam:$courseid";
                   1420:     &devalidate_cache_new('getsection',$hashid);
                   1421: }
1.298     matthew  1422: 
1.815     albertel 1423: sub courseid_to_courseurl {
                   1424:     my ($courseid) = @_;
                   1425:     #already url style courseid
                   1426:     return $courseid if ($courseid =~ m{^/});
                   1427: 
                   1428:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1429: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1430: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1431: 	return "/$cdom/$cnum";
                   1432:     }
                   1433: 
                   1434:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1435:     if (exists($courseinfo{'num'})) {
                   1436: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1437:     }
                   1438: 
                   1439:     return undef;
                   1440: }
                   1441: 
1.298     matthew  1442: sub getsection {
                   1443:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1444:     my $cachetime=1800;
1.551     albertel 1445: 
                   1446:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1447:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1448:     if (defined($cached)) { return $result; }
                   1449: 
1.298     matthew  1450:     my %Pending; 
                   1451:     my %Expired;
                   1452:     #
                   1453:     # Each role can either have not started yet (pending), be active, 
                   1454:     #    or have expired.
                   1455:     #
                   1456:     # If there is an active role, we are done.
                   1457:     #
                   1458:     # If there is more than one role which has not started yet, 
                   1459:     #     choose the one which will start sooner
                   1460:     # If there is one role which has not started yet, return it.
                   1461:     #
                   1462:     # If there is more than one expired role, choose the one which ended last.
                   1463:     # If there is a role which has expired, return it.
                   1464:     #
1.815     albertel 1465:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1466:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1467:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1468:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1469:         my $section=$1;
                   1470:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1471:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1472:         my $now=time;
1.548     albertel 1473:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1474:             $Expired{$end}=$section;
                   1475:             next;
                   1476:         }
1.548     albertel 1477:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1478:             $Pending{$start}=$section;
                   1479:             next;
                   1480:         }
1.599     albertel 1481:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1482:     }
                   1483:     #
                   1484:     # Presumedly there will be few matching roles from the above
                   1485:     # loop and the sorting time will be negligible.
                   1486:     if (scalar(keys(%Pending))) {
                   1487:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1488:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1489:     } 
                   1490:     if (scalar(keys(%Expired))) {
                   1491:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1492:         my $time = pop(@sorted);
1.599     albertel 1493:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1494:     }
1.599     albertel 1495:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1496: }
1.70      www      1497: 
1.599     albertel 1498: sub save_cache {
                   1499:     &purge_remembered();
1.722     albertel 1500:     #&Apache::loncommon::validate_page();
1.620     albertel 1501:     undef(%env);
1.780     albertel 1502:     undef($env_loaded);
1.599     albertel 1503: }
1.452     albertel 1504: 
1.599     albertel 1505: my $to_remember=-1;
                   1506: my %remembered;
                   1507: my %accessed;
                   1508: my $kicks=0;
                   1509: my $hits=0;
1.849     albertel 1510: sub make_key {
                   1511:     my ($name,$id) = @_;
1.872     albertel 1512:     if (length($id) > 65 
                   1513: 	&& length(&escape($id)) > 200) {
                   1514: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1515:     }
1.849     albertel 1516:     return &escape($name.':'.$id);
                   1517: }
                   1518: 
1.599     albertel 1519: sub devalidate_cache_new {
                   1520:     my ($name,$id,$debug) = @_;
                   1521:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1522:     $id=&make_key($name,$id);
1.599     albertel 1523:     $memcache->delete($id);
                   1524:     delete($remembered{$id});
                   1525:     delete($accessed{$id});
                   1526: }
                   1527: 
                   1528: sub is_cached_new {
                   1529:     my ($name,$id,$debug) = @_;
1.849     albertel 1530:     $id=&make_key($name,$id);
1.599     albertel 1531:     if (exists($remembered{$id})) {
                   1532: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1533: 	$accessed{$id}=[&gettimeofday()];
                   1534: 	$hits++;
                   1535: 	return ($remembered{$id},1);
                   1536:     }
                   1537:     my $value = $memcache->get($id);
                   1538:     if (!(defined($value))) {
                   1539: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1540: 	return (undef,undef);
1.416     albertel 1541:     }
1.599     albertel 1542:     if ($value eq '__undef__') {
                   1543: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1544: 	$value=undef;
                   1545:     }
                   1546:     &make_room($id,$value,$debug);
                   1547:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1548:     return ($value,1);
                   1549: }
                   1550: 
                   1551: sub do_cache_new {
                   1552:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1553:     $id=&make_key($name,$id);
1.599     albertel 1554:     my $setvalue=$value;
                   1555:     if (!defined($setvalue)) {
                   1556: 	$setvalue='__undef__';
                   1557:     }
1.623     albertel 1558:     if (!defined($time) ) {
                   1559: 	$time=600;
                   1560:     }
1.599     albertel 1561:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1562:     my $result = $memcache->set($id,$setvalue,$time);
                   1563:     if (! $result) {
1.872     albertel 1564: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1565: 	$memcache->disconnect_all();
1.872     albertel 1566:     }
1.600     albertel 1567:     # need to make a copy of $value
1.919     albertel 1568:     &make_room($id,$value,$debug);
1.599     albertel 1569:     return $value;
                   1570: }
                   1571: 
                   1572: sub make_room {
                   1573:     my ($id,$value,$debug)=@_;
1.919     albertel 1574: 
                   1575:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1576:                                     : $value;
1.599     albertel 1577:     if ($to_remember<0) { return; }
                   1578:     $accessed{$id}=[&gettimeofday()];
                   1579:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1580:     my $to_kick;
                   1581:     my $max_time=0;
                   1582:     foreach my $other (keys(%accessed)) {
                   1583: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1584: 	    $to_kick=$other;
                   1585: 	    $max_time=&tv_interval($accessed{$other});
                   1586: 	}
                   1587:     }
                   1588:     delete($remembered{$to_kick});
                   1589:     delete($accessed{$to_kick});
                   1590:     $kicks++;
                   1591:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1592:     return;
                   1593: }
                   1594: 
1.599     albertel 1595: sub purge_remembered {
1.604     albertel 1596:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1597:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1598:     undef(%remembered);
                   1599:     undef(%accessed);
1.428     albertel 1600: }
1.70      www      1601: # ------------------------------------- Read an entry from a user's environment
                   1602: 
                   1603: sub userenvironment {
                   1604:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1605:     my $items;
                   1606:     foreach my $item (@what) {
                   1607:         $items.=&escape($item).'&';
                   1608:     }
                   1609:     $items=~s/\&$//;
1.70      www      1610:     my %returnhash=();
                   1611:     my @answer=split(/\&/,
1.976     raeburn  1612:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1613:                       &homeserver($unam,$udom)));
                   1614:     my $i;
                   1615:     for ($i=0;$i<=$#what;$i++) {
                   1616: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1617:     }
                   1618:     return %returnhash;
1.1       albertel 1619: }
                   1620: 
1.617     albertel 1621: # ---------------------------------------------------------- Get a studentphoto
                   1622: sub studentphoto {
                   1623:     my ($udom,$unam,$ext) = @_;
                   1624:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1625:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1626:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1627:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1628:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1629:             } else {
                   1630:                 my ($result,$perm_reqd)=
1.707     albertel 1631: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1632:                 if ($result eq 'ok') {
                   1633:                     if (!($perm_reqd eq 'yes')) {
                   1634:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1635:                     }
                   1636:                 }
                   1637:             }
                   1638:         }
                   1639:     } else {
                   1640:         my ($result,$perm_reqd) = 
1.707     albertel 1641: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1642:         if ($result eq 'ok') {
                   1643:             if (!($perm_reqd eq 'yes')) {
                   1644:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1645:             }
                   1646:         }
                   1647:     }
                   1648:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1649: }
                   1650: 
                   1651: sub retrievestudentphoto {
                   1652:     my ($udom,$unam,$ext,$type) = @_;
                   1653:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1654:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1655:     if ($ret eq 'ok') {
                   1656:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1657:         if ($type eq 'thumbnail') {
                   1658:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1659:         }
                   1660:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1661:         return $tokenurl;
                   1662:     } else {
                   1663:         if ($type eq 'thumbnail') {
                   1664:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1665:         } else { 
                   1666:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1667:         }
1.617     albertel 1668:     }
                   1669: }
                   1670: 
1.263     www      1671: # -------------------------------------------------------------------- New chat
                   1672: 
                   1673: sub chatsend {
1.724     raeburn  1674:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1675:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1676:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1677:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1678:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1679: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1680: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1681: }
                   1682: 
                   1683: # ------------------------------------------ Find current version of a resource
                   1684: 
                   1685: sub getversion {
                   1686:     my $fname=&clutter(shift);
                   1687:     unless ($fname=~/^\/res\//) { return -1; }
                   1688:     return &currentversion(&filelocation('',$fname));
                   1689: }
                   1690: 
                   1691: sub currentversion {
                   1692:     my $fname=shift;
1.599     albertel 1693:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1694:     if (defined($cached)) { return $result; }
1.292     www      1695:     my $author=$fname;
                   1696:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1697:     my ($udom,$uname)=split(/\//,$author);
                   1698:     my $home=homeserver($uname,$udom);
                   1699:     if ($home eq 'no_host') { 
                   1700:         return -1; 
                   1701:     }
                   1702:     my $answer=reply("currentversion:$fname",$home);
                   1703:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1704: 	return -1;
                   1705:     }
1.599     albertel 1706:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1707: }
                   1708: 
1.1       albertel 1709: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1710: 
1.1       albertel 1711: sub subscribe {
                   1712:     my $fname=shift;
1.761     raeburn  1713:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1714:     $fname=~s/[\n\r]//g;
1.1       albertel 1715:     my $author=$fname;
                   1716:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1717:     my ($udom,$uname)=split(/\//,$author);
                   1718:     my $home=homeserver($uname,$udom);
1.335     albertel 1719:     if ($home eq 'no_host') {
                   1720:         return 'not_found';
1.1       albertel 1721:     }
                   1722:     my $answer=reply("sub:$fname",$home);
1.64      www      1723:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1724: 	$answer.=' by '.$home;
                   1725:     }
1.1       albertel 1726:     return $answer;
                   1727: }
                   1728:     
1.8       www      1729: # -------------------------------------------------------------- Replicate file
                   1730: 
                   1731: sub repcopy {
                   1732:     my $filename=shift;
1.23      www      1733:     $filename=~s/\/+/\//g;
1.607     raeburn  1734:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1735:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1736:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1737: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1738: 	return &repcopy_userfile($filename);
                   1739:     }
1.532     albertel 1740:     $filename=~s/[\n\r]//g;
1.8       www      1741:     my $transname="$filename.in.transfer";
1.828     www      1742: # FIXME: this should flock
1.607     raeburn  1743:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1744:     my $remoteurl=subscribe($filename);
1.64      www      1745:     if ($remoteurl =~ /^con_lost by/) {
                   1746: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1747:            return 'unavailable';
1.8       www      1748:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1749: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1750: 	   return 'not_found';
1.64      www      1751:     } elsif ($remoteurl =~ /^rejected by/) {
                   1752: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1753:            return 'forbidden';
1.20      www      1754:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1755:            return 'ok';
1.8       www      1756:     } else {
1.290     www      1757:         my $author=$filename;
                   1758:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1759:         my ($udom,$uname)=split(/\//,$author);
                   1760:         my $home=homeserver($uname,$udom);
                   1761:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1762:            my @parts=split(/\//,$filename);
                   1763:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1764:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1765:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1766: 	       return 'bad_request';
1.8       www      1767:            }
                   1768:            my $count;
                   1769:            for ($count=5;$count<$#parts;$count++) {
                   1770:                $path.="/$parts[$count]";
                   1771:                if ((-e $path)!=1) {
                   1772: 		   mkdir($path,0777);
                   1773:                }
                   1774:            }
                   1775:            my $ua=new LWP::UserAgent;
                   1776:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1777:            my $response=$ua->request($request,$transname);
                   1778:            if ($response->is_error()) {
                   1779: 	       unlink($transname);
                   1780:                my $message=$response->status_line;
1.672     albertel 1781:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1782:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1783:                return 'unavailable';
1.8       www      1784:            } else {
1.16      www      1785: 	       if ($remoteurl!~/\.meta$/) {
                   1786:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1787:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1788:                   if ($mresponse->is_error()) {
                   1789: 		      unlink($filename.'.meta');
                   1790:                       &logthis(
1.672     albertel 1791:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1792:                   }
                   1793: 	       }
1.8       www      1794:                rename($transname,$filename);
1.607     raeburn  1795:                return 'ok';
1.8       www      1796:            }
1.290     www      1797:        }
1.8       www      1798:     }
1.330     www      1799: }
                   1800: 
                   1801: # ------------------------------------------------ Get server side include body
                   1802: sub ssi_body {
1.381     albertel 1803:     my ($filelink,%form)=@_;
1.606     matthew  1804:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1805:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1806:     }
1.953     www      1807:     my $output='';
                   1808:     my $response;
1.980     raeburn  1809:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1810:        ($output,$response)=&externalssi($filelink);
1.953     www      1811:     } else {
                   1812:        ($output,$response)=&ssi($filelink,%form);
                   1813:     }
1.778     albertel 1814:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1815:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1816:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1817:     if (wantarray) {
                   1818:         return ($output, $response);
                   1819:     } else {
                   1820:         return $output;
                   1821:     }
1.8       www      1822: }
                   1823: 
1.15      www      1824: # --------------------------------------------------------- Server Side Include
                   1825: 
1.782     albertel 1826: sub absolute_url {
                   1827:     my ($host_name) = @_;
                   1828:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1829:     if ($host_name eq '') {
                   1830: 	$host_name = $ENV{'SERVER_NAME'};
                   1831:     }
                   1832:     return $protocol.$host_name;
                   1833: }
                   1834: 
1.942     foxr     1835: #
                   1836: #   Server side include.
                   1837: # Parameters:
                   1838: #  fn     Possibly encrypted resource name/id.
                   1839: #  form   Hash that describes how the rendering should be done
                   1840: #         and other things.
1.944     foxr     1841: # Returns:
1.950     raeburn  1842: #   Scalar context: The content of the response.
                   1843: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1844: #     
1.15      www      1845: sub ssi {
                   1846: 
1.944     foxr     1847:     my ($fn,%form)=@_;
1.15      www      1848:     my $ua=new LWP::UserAgent;
1.23      www      1849:     my $request;
1.711     albertel 1850: 
                   1851:     $form{'no_update_last_known'}=1;
1.895     albertel 1852:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1853:     if (%form) {
1.782     albertel 1854:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1855:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1856:     } else {
1.782     albertel 1857:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1858:     }
                   1859: 
1.15      www      1860:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1861:     my $response=$ua->request($request);
                   1862: 
1.944     foxr     1863:     if (wantarray) {
                   1864: 	return ($response->content, $response);
                   1865:     } else {
                   1866: 	return $response->content;
1.942     foxr     1867:     }
1.324     www      1868: }
                   1869: 
                   1870: sub externalssi {
                   1871:     my ($url)=@_;
                   1872:     my $ua=new LWP::UserAgent;
                   1873:     my $request=new HTTP::Request('GET',$url);
                   1874:     my $response=$ua->request($request);
1.954     raeburn  1875:     if (wantarray) {
                   1876:         return ($response->content, $response);
                   1877:     } else {
                   1878:         return $response->content;
                   1879:     }
1.15      www      1880: }
1.254     www      1881: 
1.492     albertel 1882: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1883: 
                   1884: sub allowuploaded {
                   1885:     my ($srcurl,$url)=@_;
                   1886:     $url=&clutter(&declutter($url));
                   1887:     my $dir=$url;
                   1888:     $dir=~s/\/[^\/]+$//;
                   1889:     my %httpref=();
                   1890:     my $httpurl=&hreflocation('',$url);
                   1891:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1892:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1893: }
1.477     raeburn  1894: 
1.478     albertel 1895: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1896: # input: action, courseID, current domain, intended
1.637     raeburn  1897: #        path to file, source of file, instruction to parse file for objects,
                   1898: #        ref to hash for embedded objects,
                   1899: #        ref to hash for codebase of java objects.
                   1900: #
1.485     raeburn  1901: # output: url to file (if action was uploaddoc), 
                   1902: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1903: #
1.478     albertel 1904: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1905: # course.
1.477     raeburn  1906: #
1.478     albertel 1907: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1908: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1909: #          course's home server.
1.477     raeburn  1910: #
1.478     albertel 1911: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1912: #          be copied from $source (current location) to 
                   1913: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1914: #         and will then be copied to
                   1915: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1916: #         course's home server.
1.485     raeburn  1917: #
1.481     raeburn  1918: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1919: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1920: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1921: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1922: #         in course's home server.
1.637     raeburn  1923: #
1.477     raeburn  1924: 
                   1925: sub process_coursefile {
1.638     albertel 1926:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1927:     my $fetchresult;
1.638     albertel 1928:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1929:     if ($action eq 'propagate') {
1.638     albertel 1930:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1931: 			     $home);
1.481     raeburn  1932:     } else {
1.477     raeburn  1933:         my $fpath = '';
                   1934:         my $fname = $file;
1.478     albertel 1935:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1936:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1937:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1938:         if ($action eq 'copy') {
                   1939:             if ($source eq '') {
                   1940:                 $fetchresult = 'no source file';
                   1941:                 return $fetchresult;
                   1942:             } else {
                   1943:                 my $destination = $filepath.'/'.$fname;
                   1944:                 rename($source,$destination);
                   1945:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1946:                                  $home);
1.481     raeburn  1947:             }
                   1948:         } elsif ($action eq 'uploaddoc') {
                   1949:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1950:             print $fh $env{'form.'.$source};
1.481     raeburn  1951:             close($fh);
1.637     raeburn  1952:             if ($parser eq 'parse') {
1.961     raeburn  1953:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1954:                 unless ($parse_result eq 'ok') {
                   1955:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1956:                 }
                   1957:             }
1.477     raeburn  1958:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1959:                                  $home);
1.481     raeburn  1960:             if ($fetchresult eq 'ok') {
                   1961:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1962:             } else {
                   1963:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1964:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1965:                 return '/adm/notfound.html';
                   1966:             }
1.477     raeburn  1967:         }
                   1968:     }
1.485     raeburn  1969:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1970:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1971:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1972:     }
                   1973:     return $fetchresult;
                   1974: }
                   1975: 
1.637     raeburn  1976: sub build_filepath {
                   1977:     my ($fpath) = @_;
                   1978:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1979:     unless ($fpath eq '') {
                   1980:         my @parts=split('/',$fpath);
                   1981:         foreach my $part (@parts) {
                   1982:             $filepath.= '/'.$part;
                   1983:             if ((-e $filepath)!=1) {
                   1984:                 mkdir($filepath,0777);
                   1985:             }
                   1986:         }
                   1987:     }
                   1988:     return $filepath;
                   1989: }
                   1990: 
                   1991: sub store_edited_file {
1.638     albertel 1992:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1993:     my $file = $primary_url;
                   1994:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1995:     my $fpath = '';
                   1996:     my $fname = $file;
                   1997:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1998:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1999:     my $filepath = &build_filepath($fpath);
                   2000:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2001:     print $fh $content;
                   2002:     close($fh);
1.638     albertel 2003:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2004:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2005: 			  $home);
1.637     raeburn  2006:     if ($$fetchresult eq 'ok') {
                   2007:         return '/uploaded/'.$fpath.'/'.$fname;
                   2008:     } else {
1.638     albertel 2009:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2010: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2011:         return '/adm/notfound.html';
                   2012:     }
                   2013: }
                   2014: 
1.531     albertel 2015: sub clean_filename {
1.831     albertel 2016:     my ($fname,$args)=@_;
1.315     www      2017: # Replace Windows backslashes by forward slashes
1.257     www      2018:     $fname=~s/\\/\//g;
1.831     albertel 2019:     if (!$args->{'keep_path'}) {
                   2020:         # Get rid of everything but the actual filename
                   2021: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2022:     }
1.315     www      2023: # Replace spaces by underscores
                   2024:     $fname=~s/\s+/\_/g;
                   2025: # Replace all other weird characters by nothing
1.831     albertel 2026:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2027: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2028: # numbers
                   2029:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2030:     return $fname;
                   2031: }
                   2032: 
1.977     amueller 2033: #Wrapper function for userphotoupload
                   2034: sub userphotoupload
                   2035: {
                   2036: 	my($formname,$subdir) = @_;
                   2037: 	$upload_photo_form = 1;
                   2038: 	return &userfileupload($formname,undef,$subdir);
                   2039: }
                   2040: 
1.608     albertel 2041: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2042: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2043: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2044: #        $coursedoc - if true up to the current course
                   2045: #                     if false
                   2046: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2047: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2048: #        $allfiles - reference to hash for embedded objects
                   2049: #        $codebase - reference to hash for codebase of java objects
                   2050: #        $desuname - username for permanent storage of uploaded file
                   2051: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2052: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2053: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2054: # 
1.686     albertel 2055: # output: url of file in userspace, or error: <message> 
                   2056: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2057: 
                   2058: 
1.531     albertel 2059: sub userfileupload {
1.860     raeburn  2060:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2061:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2062:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2063:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2064:     $fname=&clean_filename($fname);
1.315     www      2065: # See if there is anything left
1.257     www      2066:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2067:     chop($env{'form.'.$formname});
1.523     raeburn  2068:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2069:         my $now = time;
                   2070:         my $filepath = 'tmp/helprequests/'.$now;
                   2071:         my @parts=split(/\//,$filepath);
                   2072:         my $fullpath = $perlvar{'lonDaemons'};
                   2073:         for (my $i=0;$i<@parts;$i++) {
                   2074:             $fullpath .= '/'.$parts[$i];
                   2075:             if ((-e $fullpath)!=1) {
                   2076:                 mkdir($fullpath,0777);
                   2077:             }
                   2078:         }
                   2079:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2080:         print $fh $env{'form.'.$formname};
1.523     raeburn  2081:         close($fh);
1.741     raeburn  2082:         return $fullpath.'/'.$fname;
                   2083:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2084:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2085:                        '_'.$env{'user.domain'}.'/pending';
                   2086:         my @parts=split(/\//,$filepath);
                   2087:         my $fullpath = $perlvar{'lonDaemons'};
                   2088:         for (my $i=0;$i<@parts;$i++) {
                   2089:             $fullpath .= '/'.$parts[$i];
                   2090:             if ((-e $fullpath)!=1) {
                   2091:                 mkdir($fullpath,0777);
                   2092:             }
                   2093:         }
                   2094:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2095:         print $fh $env{'form.'.$formname};
                   2096:         close($fh);
                   2097:         return $fullpath.'/'.$fname;
1.523     raeburn  2098:     }
1.719     banghart 2099:     
1.258     www      2100: # Create the directory if not present
1.493     albertel 2101:     $fname="$subdir/$fname";
1.259     www      2102:     if ($coursedoc) {
1.638     albertel 2103: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2104: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2105:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2106:             return &finishuserfileupload($docuname,$docudom,
                   2107: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2108: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2109:         } else {
1.620     albertel 2110:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2111:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2112: 				       $fname,$formname,$parser,
                   2113: 				       $allfiles,$codebase);
1.481     raeburn  2114:         }
1.719     banghart 2115:     } elsif (defined($destuname)) {
                   2116:         my $docuname=$destuname;
                   2117:         my $docudom=$destudom;
1.860     raeburn  2118: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2119: 				     $parser,$allfiles,$codebase,
                   2120:                                      $thumbwidth,$thumbheight);
1.719     banghart 2121:         
1.259     www      2122:     } else {
1.638     albertel 2123:         my $docuname=$env{'user.name'};
                   2124:         my $docudom=$env{'user.domain'};
1.714     raeburn  2125:         if (exists($env{'form.group'})) {
                   2126:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2127:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2128:         }
1.860     raeburn  2129: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2130: 				     $parser,$allfiles,$codebase,
                   2131:                                      $thumbwidth,$thumbheight);
1.259     www      2132:     }
1.271     www      2133: }
                   2134: 
                   2135: sub finishuserfileupload {
1.860     raeburn  2136:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2137:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2138:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2139:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2140:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2141:     $file=$fname;
                   2142:     if ($fname=~m|/|) {
                   2143:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2144: 	$path.=$fnamepath.'/';
                   2145:     }
1.259     www      2146:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2147:     my $count;
                   2148:     for ($count=4;$count<=$#parts;$count++) {
                   2149:         $filepath.="/$parts[$count]";
                   2150:         if ((-e $filepath)!=1) {
                   2151: 	    mkdir($filepath,0777);
                   2152:         }
                   2153:     }
                   2154: # Save the file
                   2155:     {
1.701     albertel 2156: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2157: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2158: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2159: 	    return '/adm/notfound.html';
                   2160: 	}
                   2161: 	if (!print FH ($env{'form.'.$formname})) {
                   2162: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2163: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2164: 	    return '/adm/notfound.html';
                   2165: 	}
1.570     albertel 2166: 	close(FH);
1.977     amueller 2167: 	if($upload_photo_form==1)
                   2168: 	{
                   2169: 		my $ima = Image::Magick->new;                       
                   2170:             	$ima->Read($filepath.'/'.$file);
                   2171: 		if($ima->Get('width') > 300)
                   2172: 		{
                   2173: 			my $factor = $ima->Get('width')/300;
                   2174:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
                   2175: 		}
                   2176: 		if($ima->Get('height') > 400)
                   2177:                 {
                   2178:                         my $factor = $ima->Get('height')/400;
                   2179:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
                   2180:                 }
                   2181:  
                   2182: 		
                   2183: 		$ima->Write($filepath.'/'.$file);
                   2184: 		$upload_photo_form = 0;
                   2185: 	}
1.258     www      2186:     }
1.637     raeburn  2187:     if ($parser eq 'parse') {
1.961     raeburn  2188:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2189: 						   $codebase);
1.637     raeburn  2190:         unless ($parse_result eq 'ok') {
1.638     albertel 2191:             &logthis('Failed to parse '.$filepath.$file.
                   2192: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2193:         }
                   2194:     }
1.860     raeburn  2195:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2196:         my $input = $filepath.'/'.$file;
                   2197:         my $output = $filepath.'/'.'tn-'.$file;
                   2198:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2199:         system("convert -sample $thumbsize $input $output");
                   2200:         if (-e $filepath.'/'.'tn-'.$file) {
                   2201:             $fetchthumb  = 1; 
                   2202:         }
                   2203:     }
1.858     raeburn  2204:  
1.259     www      2205: # Notify homeserver to grep it
                   2206: #
1.638     albertel 2207:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2208:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2209:     if ($fetchresult eq 'ok') {
1.860     raeburn  2210:         if ($fetchthumb) {
                   2211:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2212:             if ($thumbresult ne 'ok') {
                   2213:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2214:                          $docuhome.': '.$thumbresult);
                   2215:             }
                   2216:         }
1.259     www      2217: #
1.258     www      2218: # Return the URL to it
1.494     albertel 2219:         return '/uploaded/'.$path.$file;
1.263     www      2220:     } else {
1.494     albertel 2221:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2222: 		 ': '.$fetchresult);
1.263     www      2223:         return '/adm/notfound.html';
1.858     raeburn  2224:     }
1.493     albertel 2225: }
                   2226: 
1.637     raeburn  2227: sub extract_embedded_items {
1.961     raeburn  2228:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2229:     my @state = ();
                   2230:     my %javafiles = (
                   2231:                       codebase => '',
                   2232:                       code => '',
                   2233:                       archive => ''
                   2234:                     );
                   2235:     my %mediafiles = (
                   2236:                       src => '',
                   2237:                       movie => '',
                   2238:                      );
1.648     raeburn  2239:     my $p;
                   2240:     if ($content) {
                   2241:         $p = HTML::LCParser->new($content);
                   2242:     } else {
1.961     raeburn  2243:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2244:     }
1.641     albertel 2245:     while (my $t=$p->get_token()) {
1.640     albertel 2246: 	if ($t->[0] eq 'S') {
                   2247: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2248: 	    push(@state, $tagname);
1.648     raeburn  2249:             if (lc($tagname) eq 'allow') {
                   2250:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2251:             }
1.640     albertel 2252: 	    if (lc($tagname) eq 'img') {
                   2253: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2254: 	    }
1.886     albertel 2255: 	    if (lc($tagname) eq 'a') {
                   2256: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2257: 	    }
1.645     raeburn  2258:             if (lc($tagname) eq 'script') {
                   2259:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2260:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2261:                 } else {
                   2262:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2263:                 }
                   2264:             }
                   2265:             if (lc($tagname) eq 'link') {
                   2266:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2267:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2268:                 }
                   2269:             }
1.640     albertel 2270: 	    if (lc($tagname) eq 'object' ||
                   2271: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2272: 		foreach my $item (keys(%javafiles)) {
                   2273: 		    $javafiles{$item} = '';
                   2274: 		}
                   2275: 	    }
                   2276: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2277: 		my $name = lc($attr->{'name'});
                   2278: 		foreach my $item (keys(%javafiles)) {
                   2279: 		    if ($name eq $item) {
                   2280: 			$javafiles{$item} = $attr->{'value'};
                   2281: 			last;
                   2282: 		    }
                   2283: 		}
                   2284: 		foreach my $item (keys(%mediafiles)) {
                   2285: 		    if ($name eq $item) {
                   2286: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2287: 			last;
                   2288: 		    }
                   2289: 		}
                   2290: 	    }
                   2291: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2292: 		foreach my $item (keys(%javafiles)) {
                   2293: 		    if ($attr->{$item}) {
                   2294: 			$javafiles{$item} = $attr->{$item};
                   2295: 			last;
                   2296: 		    }
                   2297: 		}
                   2298: 		foreach my $item (keys(%mediafiles)) {
                   2299: 		    if ($attr->{$item}) {
                   2300: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2301: 			last;
                   2302: 		    }
                   2303: 		}
                   2304: 	    }
                   2305: 	} elsif ($t->[0] eq 'E') {
                   2306: 	    my ($tagname) = ($t->[1]);
                   2307: 	    if ($javafiles{'codebase'} ne '') {
                   2308: 		$javafiles{'codebase'} .= '/';
                   2309: 	    }  
                   2310: 	    if (lc($tagname) eq 'applet' ||
                   2311: 		lc($tagname) eq 'object' ||
                   2312: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2313: 		) {
                   2314: 		foreach my $item (keys(%javafiles)) {
                   2315: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2316: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2317: 			&add_filetype($allfiles,$file,$item);
                   2318: 		    }
                   2319: 		}
                   2320: 	    } 
                   2321: 	    pop @state;
                   2322: 	}
                   2323:     }
1.637     raeburn  2324:     return 'ok';
                   2325: }
                   2326: 
1.639     albertel 2327: sub add_filetype {
                   2328:     my ($allfiles,$file,$type)=@_;
                   2329:     if (exists($allfiles->{$file})) {
                   2330: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2331: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2332: 	}
                   2333:     } else {
                   2334: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2335:     }
                   2336: }
                   2337: 
1.493     albertel 2338: sub removeuploadedurl {
                   2339:     my ($url)=@_;
                   2340:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2341:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2342: }
                   2343: 
                   2344: sub removeuserfile {
                   2345:     my ($docuname,$docudom,$fname)=@_;
                   2346:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2347:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2348:     if ($result eq 'ok') {
                   2349:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2350:             my $metafile = $fname.'.meta';
                   2351:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2352: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2353:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2354:             my $sqlresult = 
1.823     albertel 2355:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2356:                                         'portfolio_metadata',$group,
                   2357:                                         'delete');
1.798     raeburn  2358:         }
                   2359:     }
                   2360:     return $result;
1.257     www      2361: }
1.15      www      2362: 
1.530     albertel 2363: sub mkdiruserfile {
                   2364:     my ($docuname,$docudom,$dir)=@_;
                   2365:     my $home=&homeserver($docuname,$docudom);
                   2366:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2367: }
                   2368: 
1.531     albertel 2369: sub renameuserfile {
                   2370:     my ($docuname,$docudom,$old,$new)=@_;
                   2371:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2372:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2373:                         &escape("$old").':'.&escape("$new"),$home);
                   2374:     if ($result eq 'ok') {
                   2375:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2376:             my $oldmeta = $old.'.meta';
                   2377:             my $newmeta = $new.'.meta';
                   2378:             my $metaresult = 
                   2379:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2380: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2381:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2382:             my $sqlresult = 
1.823     albertel 2383:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2384:                                         'portfolio_metadata',$group,
                   2385:                                         'delete');
1.798     raeburn  2386:         }
                   2387:     }
                   2388:     return $result;
1.531     albertel 2389: }
                   2390: 
1.14      www      2391: # ------------------------------------------------------------------------- Log
                   2392: 
                   2393: sub log {
                   2394:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2395:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2396: }
                   2397: 
                   2398: # ------------------------------------------------------------------ Course Log
1.352     www      2399: #
                   2400: # This routine flushes several buffers of non-mission-critical nature
                   2401: #
1.157     www      2402: 
                   2403: sub flushcourselogs {
1.352     www      2404:     &logthis('Flushing log buffers');
                   2405: #
                   2406: # course logs
                   2407: # This is a log of all transactions in a course, which can be used
                   2408: # for data mining purposes
                   2409: #
                   2410: # It also collects the courseid database, which lists last transaction
                   2411: # times and course titles for all courseids
                   2412: #
                   2413:     my %courseidbuffer=();
1.921     raeburn  2414:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2415:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2416: 		          &escape($courselogs{$crsid}),
                   2417: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2418: 	    delete $courselogs{$crsid};
                   2419:         } else {
                   2420:             &logthis('Failed to flush log buffer for '.$crsid);
                   2421:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2422:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2423:                         " exceeded maximum size, deleting.</font>");
                   2424:                delete $courselogs{$crsid};
                   2425:             }
1.352     www      2426:         }
1.920     raeburn  2427:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2428:             'description' => $coursedescrbuf{$crsid},
                   2429:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2430:             'type'        => $coursetypebuf{$crsid},
                   2431:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2432:         };
1.191     harris41 2433:     }
1.352     www      2434: #
                   2435: # Write course id database (reverse lookup) to homeserver of courses 
                   2436: # Is used in pickcourse
                   2437: #
1.840     albertel 2438:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2439:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2440:                                     $courseidbuffer{$crs_home},
                   2441:                                     $crs_home,'timeonly');
1.352     www      2442:     }
                   2443: #
                   2444: # File accesses
                   2445: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2446: #
1.449     matthew  2447:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2448:         if ($entry =~ /___count$/) {
                   2449:             my ($dom,$name);
1.807     albertel 2450:             ($dom,$name,undef)=
1.811     albertel 2451: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2452:             if (! defined($dom) || $dom eq '' || 
                   2453:                 ! defined($name) || $name eq '') {
1.620     albertel 2454:                 my $cid = $env{'request.course.id'};
                   2455:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2456:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2457:             }
1.450     matthew  2458:             my $value = $accesshash{$entry};
                   2459:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2460:             my %temphash=($url => $value);
1.449     matthew  2461:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2462:             if ($result eq 'ok') {
                   2463:                 delete $accesshash{$entry};
                   2464:             } elsif ($result eq 'unknown_cmd') {
                   2465:                 # Target server has old code running on it.
1.450     matthew  2466:                 my %temphash=($entry => $value);
1.449     matthew  2467:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2468:                     delete $accesshash{$entry};
                   2469:                 }
                   2470:             }
                   2471:         } else {
1.811     albertel 2472:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2473:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2474:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2475:                 delete $accesshash{$entry};
                   2476:             }
1.185     www      2477:         }
1.191     harris41 2478:     }
1.352     www      2479: #
                   2480: # Roles
                   2481: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2482: #
1.800     albertel 2483:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2484:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2485: 	    split(/\:/,$entry);
                   2486:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2487:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2488:                 $rudom,$runame) eq 'ok') {
                   2489: 	    delete $userrolehash{$entry};
                   2490:         }
                   2491:     }
1.662     raeburn  2492: #
                   2493: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2494: #
                   2495:     my %domrolebuffer = ();
                   2496:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2497:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2498:         if ($domrolebuffer{$rudom}) {
                   2499:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2500:                       '='.&escape($domainrolehash{$entry});
                   2501:         } else {
                   2502:             $domrolebuffer{$rudom}.=&escape($entry).
                   2503:                       '='.&escape($domainrolehash{$entry});
                   2504:         }
                   2505:         delete $domainrolehash{$entry};
                   2506:     }
                   2507:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2508: 	my %servers = &get_servers($dom,'library');
                   2509: 	foreach my $tryserver (keys(%servers)) {
                   2510: 	    unless (&reply('domroleput:'.$dom.':'.
                   2511: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2512: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2513: 	    }
1.662     raeburn  2514:         }
                   2515:     }
1.186     www      2516:     $dumpcount++;
1.157     www      2517: }
                   2518: 
                   2519: sub courselog {
                   2520:     my $what=shift;
1.158     www      2521:     $what=time.':'.$what;
1.620     albertel 2522:     unless ($env{'request.course.id'}) { return ''; }
                   2523:     $coursedombuf{$env{'request.course.id'}}=
                   2524:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2525:     $coursenumbuf{$env{'request.course.id'}}=
                   2526:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2527:     $coursehombuf{$env{'request.course.id'}}=
                   2528:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2529:     $coursedescrbuf{$env{'request.course.id'}}=
                   2530:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2531:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2532:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2533:     $courseownerbuf{$env{'request.course.id'}}=
                   2534:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2535:     $coursetypebuf{$env{'request.course.id'}}=
                   2536:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2537:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2538: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2539:     } else {
1.620     albertel 2540: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2541:     }
1.620     albertel 2542:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2543: 	&flushcourselogs();
                   2544:     }
1.158     www      2545: }
                   2546: 
                   2547: sub courseacclog {
                   2548:     my $fnsymb=shift;
1.620     albertel 2549:     unless ($env{'request.course.id'}) { return ''; }
                   2550:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2551:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2552:         $what.=':POST';
1.583     matthew  2553:         # FIXME: Probably ought to escape things....
1.800     albertel 2554: 	foreach my $key (keys(%env)) {
                   2555:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2556:                 my $formitem = $1;
                   2557:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2558:                     $what.=':'.$formitem.'='.$env{$key};
                   2559:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2560:                     $what.=':'.$formitem.'='.$env{$key};
                   2561:                 }
1.158     www      2562:             }
1.191     harris41 2563:         }
1.583     matthew  2564:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2565:         # FIXME: We should not be depending on a form parameter that someone
                   2566:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2567:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2568:             $what.= ':POST';
                   2569:             # FIXME: Probably ought to escape things....
                   2570:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2571:                                  'crsdiscuss') {
1.620     albertel 2572:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2573:             }
                   2574:         }
1.158     www      2575:     }
                   2576:     &courselog($what);
1.149     www      2577: }
                   2578: 
1.185     www      2579: sub countacc {
                   2580:     my $url=&declutter(shift);
1.458     matthew  2581:     return if (! defined($url) || $url eq '');
1.620     albertel 2582:     unless ($env{'request.course.id'}) { return ''; }
                   2583:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2584:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2585:     $accesshash{$key}++;
1.185     www      2586: }
1.349     www      2587: 
1.361     www      2588: sub linklog {
                   2589:     my ($from,$to)=@_;
                   2590:     $from=&declutter($from);
                   2591:     $to=&declutter($to);
                   2592:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2593:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2594: }
                   2595:   
1.349     www      2596: sub userrolelog {
                   2597:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2598:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2599:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2600:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2601:         ($trole=~/^ta/)) {
1.350     www      2602:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2603:        $userrolehash
                   2604:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2605:                     =$tend.':'.$tstart;
1.662     raeburn  2606:     }
1.898     albertel 2607:     if (($env{'request.role'} =~ /dc\./) &&
                   2608: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2609: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2610: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2611:        $userrolehash
                   2612:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2613:                     =$tend.':'.$tstart;
                   2614:     }
1.662     raeburn  2615:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2616:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2617:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2618:         ($trole=~/^sc/)) {
                   2619:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2620:        $domainrolehash
                   2621:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2622:                     = $tend.':'.$tstart;
                   2623:     }
1.351     www      2624: }
                   2625: 
1.957     raeburn  2626: sub courserolelog {
                   2627:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2628:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2629:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2630:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2631:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2632:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2633:             my $cdom = $1;
                   2634:             my $cnum = $2;
                   2635:             my $sec = $3;
                   2636:             my $namespace = 'rolelog';
                   2637:             my %storehash = (
                   2638:                                role    => $trole,
                   2639:                                start   => $tstart,
                   2640:                                end     => $tend,
                   2641:                                selfenroll => $selfenroll,
                   2642:                                context    => $context,
                   2643:                             );
                   2644:             if ($trole eq 'gr') {
                   2645:                 $namespace = 'groupslog';
                   2646:                 $storehash{'group'} = $sec;
                   2647:             } else {
                   2648:                 $storehash{'section'} = $sec;
                   2649:             }
                   2650:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2651:         }
                   2652:     }
                   2653:     return;
                   2654: }
                   2655: 
1.351     www      2656: sub get_course_adv_roles {
1.948     raeburn  2657:     my ($cid,$codes) = @_;
1.620     albertel 2658:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2659:     my %coursehash=&coursedescription($cid);
1.470     www      2660:     my %nothide=();
1.800     albertel 2661:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2662:         if ($user !~ /:/) {
                   2663: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2664:         } else {
                   2665:             $nothide{$user}=1;
                   2666:         }
1.470     www      2667:     }
1.351     www      2668:     my %returnhash=();
                   2669:     my %dumphash=
                   2670:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2671:     my $now=time;
1.800     albertel 2672:     foreach my $entry (keys %dumphash) {
                   2673: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2674:         if (($tstart) && ($tstart<0)) { next; }
                   2675:         if (($tend) && ($tend<$now)) { next; }
                   2676:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2677:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2678: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2679: 	if ((&privileged($username,$domain)) && 
                   2680: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2681: 	if ($role eq 'cr') { next; }
1.948     raeburn  2682:         if ($codes) {
                   2683:             if ($section) { $role .= ':'.$section; }
                   2684:             if ($returnhash{$role}) {
                   2685:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2686:             } else {
                   2687:                 $returnhash{$role}=$username.':'.$domain;
                   2688:             }
1.351     www      2689:         } else {
1.948     raeburn  2690:             my $key=&plaintext($role);
1.973     bisitz   2691:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2692:             if ($returnhash{$key}) {
                   2693: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2694:             } else {
                   2695:                 $returnhash{$key}=$username.':'.$domain;
                   2696:             }
1.351     www      2697:         }
1.948     raeburn  2698:     }
1.400     www      2699:     return %returnhash;
                   2700: }
                   2701: 
                   2702: sub get_my_roles {
1.937     raeburn  2703:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2704:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2705:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2706:     my (%dumphash,%nothide);
1.858     raeburn  2707:     if ($context eq 'userroles') { 
                   2708:         %dumphash = &dump('roles',$udom,$uname);
                   2709:     } else {
                   2710:         %dumphash=
1.400     www      2711:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2712:         if ($hidepriv) {
                   2713:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2714:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2715:                 if ($user !~ /:/) {
                   2716:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2717:                 } else {
                   2718:                     $nothide{$user} = 1;
                   2719:                 }
                   2720:             }
                   2721:         }
1.858     raeburn  2722:     }
1.400     www      2723:     my %returnhash=();
                   2724:     my $now=time;
1.800     albertel 2725:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2726:         my ($role,$tend,$tstart);
                   2727:         if ($context eq 'userroles') {
                   2728: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2729:         } else {
                   2730:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2731:         }
1.400     www      2732:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2733:         my $status = 'active';
1.939     raeburn  2734:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2735:             $status = 'previous';
                   2736:         } 
                   2737:         if (($tstart) && ($now<$tstart)) {
                   2738:             $status = 'future';
                   2739:         }
                   2740:         if (ref($types) eq 'ARRAY') {
                   2741:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2742:                 next;
                   2743:             } 
                   2744:         } else {
                   2745:             if ($status ne 'active') {
                   2746:                 next;
                   2747:             }
                   2748:         }
1.867     raeburn  2749:         my ($rolecode,$username,$domain,$section,$area);
                   2750:         if ($context eq 'userroles') {
                   2751:             ($area,$rolecode) = split(/_/,$entry);
                   2752:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2753:         } else {
                   2754:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2755:         }
1.832     raeburn  2756:         if (ref($roledoms) eq 'ARRAY') {
                   2757:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2758:                 next;
                   2759:             }
                   2760:         }
                   2761:         if (ref($roles) eq 'ARRAY') {
                   2762:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2763:                 if ($role =~ /^cr\//) {
                   2764:                     if (!grep(/^cr$/,@{$roles})) {
                   2765:                         next;
                   2766:                     }
                   2767:                 } else {
                   2768:                     next;
                   2769:                 }
1.832     raeburn  2770:             }
1.867     raeburn  2771:         }
1.937     raeburn  2772:         if ($hidepriv) {
                   2773:             if ((&privileged($username,$domain)) &&
                   2774:                 (!$nothide{$username.':'.$domain})) { 
                   2775:                 next;
                   2776:             }
                   2777:         }
1.933     raeburn  2778:         if ($withsec) {
                   2779:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2780:                 $tstart.':'.$tend;
                   2781:         } else {
                   2782:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2783:         }
1.832     raeburn  2784:     }
1.373     www      2785:     return %returnhash;
1.399     www      2786: }
                   2787: 
                   2788: # ----------------------------------------------------- Frontpage Announcements
                   2789: #
                   2790: #
                   2791: 
                   2792: sub postannounce {
                   2793:     my ($server,$text)=@_;
1.844     albertel 2794:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2795:     unless ($text=~/\w/) { $text=''; }
                   2796:     return &reply('setannounce:'.&escape($text),$server);
                   2797: }
                   2798: 
                   2799: sub getannounce {
1.448     albertel 2800: 
                   2801:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2802: 	my $announcement='';
1.800     albertel 2803: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2804: 	close($fh);
1.399     www      2805: 	if ($announcement=~/\w/) { 
                   2806: 	    return 
                   2807:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2808:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2809: 	} else {
                   2810: 	    return '';
                   2811: 	}
                   2812:     } else {
                   2813: 	return '';
                   2814:     }
1.351     www      2815: }
1.353     www      2816: 
                   2817: # ---------------------------------------------------------- Course ID routines
                   2818: # Deal with domain's nohist_courseid.db files
                   2819: #
                   2820: 
                   2821: sub courseidput {
1.921     raeburn  2822:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2823:     my $outcome;
                   2824:     if ($caller eq 'timeonly') {
                   2825:         my $cids = '';
                   2826:         foreach my $item (keys(%$storehash)) {
                   2827:             $cids.=&escape($item).'&';
                   2828:         }
                   2829:         $cids=~s/\&$//;
                   2830:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2831:                           $coursehome);       
                   2832:     } else {
                   2833:         my $items = '';
                   2834:         foreach my $item (keys(%$storehash)) {
                   2835:             $items.= &escape($item).'='.
                   2836:                      &freeze_escape($$storehash{$item}).'&';
                   2837:         }
                   2838:         $items=~s/\&$//;
                   2839:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2840:                           $coursehome);
1.918     raeburn  2841:     }
                   2842:     if ($outcome eq 'unknown_cmd') {
                   2843:         my $what;
                   2844:         foreach my $cid (keys(%$storehash)) {
                   2845:             $what .= &escape($cid).'=';
1.921     raeburn  2846:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2847:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2848:             }
                   2849:             $what =~ s/\:$/&/;
                   2850:         }
                   2851:         $what =~ s/\&$//;  
                   2852:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2853:     } else {
                   2854:         return $outcome;
                   2855:     }
1.353     www      2856: }
                   2857: 
                   2858: sub courseiddump {
1.921     raeburn  2859:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2860:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2861:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2862:     my $as_hash = 1;
                   2863:     my %returnhash;
                   2864:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2865:     my %libserv = &all_library();
                   2866:     foreach my $tryserver (keys(%libserv)) {
                   2867:         if ( (  $hostidflag == 1 
                   2868: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2869: 	     || (!defined($hostidflag)) ) {
                   2870: 
1.918     raeburn  2871: 	    if (($domfilter eq '') ||
                   2872: 		(&host_domain($tryserver) eq $domfilter)) {
                   2873:                 my $rep = 
                   2874:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2875:                          $sincefilter.':'.&escape($descfilter).':'.
                   2876:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2877:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2878:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2879:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2880:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2881:                 my @pairs=split(/\&/,$rep);
                   2882:                 foreach my $item (@pairs) {
                   2883:                     my ($key,$value)=split(/\=/,$item,2);
                   2884:                     $key = &unescape($key);
                   2885:                     next if ($key =~ /^error: 2 /);
                   2886:                     my $result = &thaw_unescape($value);
                   2887:                     if (ref($result) eq 'HASH') {
                   2888:                         $returnhash{$key}=$result;
                   2889:                     } else {
1.921     raeburn  2890:                         my @responses = split(/:/,$value);
                   2891:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2892:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2893:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2894:                         }
                   2895:                     } 
1.353     www      2896:                 }
                   2897:             }
                   2898:         }
                   2899:     }
                   2900:     return %returnhash;
                   2901: }
                   2902: 
1.658     raeburn  2903: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2904: 
                   2905: sub dcmailput {
1.685     raeburn  2906:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2907:     my $status = &Apache::lonnet::critical(
1.740     www      2908:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2909:        &escape($message),$server);
1.662     raeburn  2910:     return $status;
                   2911: }
                   2912: 
1.658     raeburn  2913: sub dcmaildump {
                   2914:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2915:     my %returnhash=();
1.846     albertel 2916: 
                   2917:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2918:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2919:                                                          &escape($enddate).':';
                   2920: 	my @esc_senders=map { &escape($_)} @$senders;
                   2921: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2922: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2923:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2924:             if (($key) && ($value)) {
                   2925:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2926:             }
                   2927:         }
                   2928:     }
                   2929:     return %returnhash;
                   2930: }
1.662     raeburn  2931: # ---------------------------------------------------------- Domain roles
                   2932: 
                   2933: sub get_domain_roles {
                   2934:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2935:     if (undef($startdate) || $startdate eq '') {
                   2936:         $startdate = '.';
                   2937:     }
                   2938:     if (undef($enddate) || $enddate eq '') {
                   2939:         $enddate = '.';
                   2940:     }
1.922     raeburn  2941:     my $rolelist;
                   2942:     if (ref($roles) eq 'ARRAY') {
                   2943:         $rolelist = join(':',@{$roles});
                   2944:     }
1.662     raeburn  2945:     my %personnel = ();
1.841     albertel 2946: 
                   2947:     my %servers = &get_servers($dom,'library');
                   2948:     foreach my $tryserver (keys(%servers)) {
                   2949: 	%{$personnel{$tryserver}}=();
                   2950: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2951: 					    &escape($startdate).':'.
                   2952: 					    &escape($enddate).':'.
                   2953: 					    &escape($rolelist), $tryserver))) {
                   2954: 	    my ($key,$value) = split(/\=/,$line,2);
                   2955: 	    if (($key) && ($value)) {
                   2956: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2957: 	    }
                   2958: 	}
1.662     raeburn  2959:     }
                   2960:     return %personnel;
                   2961: }
1.658     raeburn  2962: 
1.149     www      2963: # ----------------------------------------------------------- Check out an item
                   2964: 
1.504     albertel 2965: sub get_first_access {
                   2966:     my ($type,$argsymb)=@_;
1.790     albertel 2967:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2968:     if ($argsymb) { $symb=$argsymb; }
                   2969:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2970:     if ($type eq 'course') {
                   2971: 	$res='course';
                   2972:     } elsif ($type eq 'map') {
1.588     albertel 2973: 	$res=&symbread($map);
                   2974:     } else {
                   2975: 	$res=$symb;
                   2976:     }
                   2977:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2978:     return $times{"$courseid\0$res"};
1.504     albertel 2979: }
                   2980: 
                   2981: sub set_first_access {
                   2982:     my ($type)=@_;
1.790     albertel 2983:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2984:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2985:     if ($type eq 'course') {
                   2986: 	$res='course';
                   2987:     } elsif ($type eq 'map') {
1.588     albertel 2988: 	$res=&symbread($map);
                   2989:     } else {
                   2990: 	$res=$symb;
                   2991:     }
                   2992:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2993:     if (!$firstaccess) {
1.588     albertel 2994: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2995:     }
                   2996:     return 'already_set';
1.504     albertel 2997: }
                   2998: 
1.149     www      2999: sub checkout {
                   3000:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3001:     my $now=time;
                   3002:     my $lonhost=$perlvar{'lonHostID'};
                   3003:     my $infostr=&escape(
1.234     www      3004:                  'CHECKOUTTOKEN&'.
1.149     www      3005:                  $tuname.'&'.
                   3006:                  $tudom.'&'.
                   3007:                  $tcrsid.'&'.
                   3008:                  $symb.'&'.
                   3009: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3010:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3011:     if ($token=~/^error\:/) { 
1.672     albertel 3012:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3013:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3014:                  "</font>");
                   3015:         return ''; 
                   3016:     }
                   3017: 
1.149     www      3018:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3019:     $token=~tr/a-z/A-Z/;
                   3020: 
1.153     www      3021:     my %infohash=('resource.0.outtoken' => $token,
                   3022:                   'resource.0.checkouttime' => $now,
                   3023:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3024: 
                   3025:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3026:        return '';
1.151     www      3027:     } else {
1.672     albertel 3028:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3029:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3030:                  "</font>");
1.149     www      3031:     }    
                   3032: 
                   3033:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3034:                          &escape('Checkout '.$infostr.' - '.
                   3035:                                                  $token)) ne 'ok') {
                   3036: 	return '';
1.151     www      3037:     } else {
1.672     albertel 3038:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3039:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3040:                  "</font>");
1.149     www      3041:     }
1.151     www      3042:     return $token;
1.149     www      3043: }
                   3044: 
                   3045: # ------------------------------------------------------------ Check in an item
                   3046: 
                   3047: sub checkin {
                   3048:     my $token=shift;
1.150     www      3049:     my $now=time;
                   3050:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3051:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3052:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3053:     $dtoken=~s/\W/\_/g;
1.234     www      3054:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3055:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3056: 
1.154     www      3057:     unless (($tuname) && ($tudom)) {
                   3058:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3059:         return '';
                   3060:     }
                   3061:     
                   3062:     unless (&allowed('mgr',$tcrsid)) {
                   3063:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3064:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3065:         return '';
                   3066:     }
                   3067: 
1.153     www      3068:     my %infohash=('resource.0.intoken' => $token,
                   3069:                   'resource.0.checkintime' => $now,
                   3070:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3071: 
                   3072:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3073:        return '';
                   3074:     }    
                   3075: 
                   3076:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3077:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3078: 	return '';
                   3079:     }
                   3080: 
                   3081:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3082: }
                   3083: 
                   3084: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3085: 
                   3086: sub expirespread {
                   3087:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3088:     my $cid=$env{'request.course.id'}; 
1.110     www      3089:     if ($cid) {
                   3090:        my $now=time;
                   3091:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3092:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3093:                             $env{'course.'.$cid.'.num'}.
1.110     www      3094: 	        	    ':nohist_expirationdates:'.
                   3095:                             &escape($key).'='.$now,
1.620     albertel 3096:                             $env{'course.'.$cid.'.home'})
1.110     www      3097:     }
                   3098:     return 'ok';
1.14      www      3099: }
                   3100: 
1.109     www      3101: # ----------------------------------------------------- Devalidate Spreadsheets
                   3102: 
                   3103: sub devalidate {
1.325     www      3104:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3105:     my $cid=$env{'request.course.id'}; 
1.109     www      3106:     if ($cid) {
1.391     matthew  3107:         # delete the stored spreadsheets for
                   3108:         # - the student level sheet of this user in course's homespace
                   3109:         # - the assessment level sheet for this resource 
                   3110:         #   for this user in user's homespace
1.553     albertel 3111: 	# - current conditional state info
1.325     www      3112: 	my $key=$uname.':'.$udom.':';
1.109     www      3113:         my $status=
1.299     matthew  3114: 	    &del('nohist_calculatedsheets',
1.391     matthew  3115: 		 [$key.'studentcalc:'],
1.620     albertel 3116: 		 $env{'course.'.$cid.'.domain'},
                   3117: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3118: 		.' '.
                   3119: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3120: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3121:         unless ($status eq 'ok ok') {
                   3122:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3123:                     $uname.' at '.$udom.' for '.
1.109     www      3124: 		    $symb.': '.$status);
1.133     albertel 3125:         }
1.553     albertel 3126: 	&delenv('user.state.'.$cid);
1.109     www      3127:     }
                   3128: }
                   3129: 
1.265     albertel 3130: sub get_scalar {
                   3131:     my ($string,$end) = @_;
                   3132:     my $value;
                   3133:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3134: 	$value = $1;
                   3135:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3136: 	$value = $1;
                   3137:     }
                   3138:     return &unescape($value);
                   3139: }
                   3140: 
                   3141: sub array2str {
                   3142:   my (@array) = @_;
                   3143:   my $result=&arrayref2str(\@array);
                   3144:   $result=~s/^__ARRAY_REF__//;
                   3145:   $result=~s/__END_ARRAY_REF__$//;
                   3146:   return $result;
                   3147: }
                   3148: 
1.204     albertel 3149: sub arrayref2str {
                   3150:   my ($arrayref) = @_;
1.265     albertel 3151:   my $result='__ARRAY_REF__';
1.204     albertel 3152:   foreach my $elem (@$arrayref) {
1.265     albertel 3153:     if(ref($elem) eq 'ARRAY') {
                   3154:       $result.=&arrayref2str($elem).'&';
                   3155:     } elsif(ref($elem) eq 'HASH') {
                   3156:       $result.=&hashref2str($elem).'&';
                   3157:     } elsif(ref($elem)) {
                   3158:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3159:     } else {
                   3160:       $result.=&escape($elem).'&';
                   3161:     }
                   3162:   }
                   3163:   $result=~s/\&$//;
1.265     albertel 3164:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3165:   return $result;
                   3166: }
                   3167: 
1.168     albertel 3168: sub hash2str {
1.204     albertel 3169:   my (%hash) = @_;
                   3170:   my $result=&hashref2str(\%hash);
1.265     albertel 3171:   $result=~s/^__HASH_REF__//;
                   3172:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3173:   return $result;
                   3174: }
                   3175: 
                   3176: sub hashref2str {
                   3177:   my ($hashref)=@_;
1.265     albertel 3178:   my $result='__HASH_REF__';
1.800     albertel 3179:   foreach my $key (sort(keys(%$hashref))) {
                   3180:     if (ref($key) eq 'ARRAY') {
                   3181:       $result.=&arrayref2str($key).'=';
                   3182:     } elsif (ref($key) eq 'HASH') {
                   3183:       $result.=&hashref2str($key).'=';
                   3184:     } elsif (ref($key)) {
1.265     albertel 3185:       $result.='=';
1.800     albertel 3186:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3187:     } else {
1.800     albertel 3188: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3189:     }
                   3190: 
1.800     albertel 3191:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3192:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3193:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3194:       $result.=&hashref2str($hashref->{$key}).'&';
                   3195:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3196:        $result.='&';
1.800     albertel 3197:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3198:     } else {
1.800     albertel 3199:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3200:     }
                   3201:   }
1.168     albertel 3202:   $result=~s/\&$//;
1.265     albertel 3203:   $result .= '__END_HASH_REF__';
1.168     albertel 3204:   return $result;
                   3205: }
                   3206: 
                   3207: sub str2hash {
1.265     albertel 3208:     my ($string)=@_;
                   3209:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3210:     return %$hash;
                   3211: }
                   3212: 
                   3213: sub str2hashref {
1.168     albertel 3214:   my ($string) = @_;
1.265     albertel 3215: 
                   3216:   my %hash;
                   3217: 
                   3218:   if($string !~ /^__HASH_REF__/) {
                   3219:       if (! ($string eq '' || !defined($string))) {
                   3220: 	  $hash{'error'}='Not hash reference';
                   3221:       }
                   3222:       return (\%hash, $string);
                   3223:   }
                   3224: 
                   3225:   $string =~ s/^__HASH_REF__//;
                   3226: 
                   3227:   while($string !~ /^__END_HASH_REF__/) {
                   3228:       #key
                   3229:       my $key='';
                   3230:       if($string =~ /^__HASH_REF__/) {
                   3231:           ($key, $string)=&str2hashref($string);
                   3232:           if(defined($key->{'error'})) {
                   3233:               $hash{'error'}='Bad data';
                   3234:               return (\%hash, $string);
                   3235:           }
                   3236:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3237:           ($key, $string)=&str2arrayref($string);
                   3238:           if($key->[0] eq 'Array reference error') {
                   3239:               $hash{'error'}='Bad data';
                   3240:               return (\%hash, $string);
                   3241:           }
                   3242:       } else {
                   3243:           $string =~ s/^(.*?)=//;
1.267     albertel 3244: 	  $key=&unescape($1);
1.265     albertel 3245:       }
                   3246:       $string =~ s/^=//;
                   3247: 
                   3248:       #value
                   3249:       my $value='';
                   3250:       if($string =~ /^__HASH_REF__/) {
                   3251:           ($value, $string)=&str2hashref($string);
                   3252:           if(defined($value->{'error'})) {
                   3253:               $hash{'error'}='Bad data';
                   3254:               return (\%hash, $string);
                   3255:           }
                   3256:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3257:           ($value, $string)=&str2arrayref($string);
                   3258:           if($value->[0] eq 'Array reference error') {
                   3259:               $hash{'error'}='Bad data';
                   3260:               return (\%hash, $string);
                   3261:           }
                   3262:       } else {
                   3263: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3264:       }
                   3265:       $string =~ s/^&//;
                   3266: 
                   3267:       $hash{$key}=$value;
1.204     albertel 3268:   }
1.265     albertel 3269: 
                   3270:   $string =~ s/^__END_HASH_REF__//;
                   3271: 
                   3272:   return (\%hash, $string);
1.204     albertel 3273: }
                   3274: 
                   3275: sub str2array {
1.265     albertel 3276:     my ($string)=@_;
                   3277:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3278:     return @$array;
                   3279: }
                   3280: 
                   3281: sub str2arrayref {
1.204     albertel 3282:   my ($string) = @_;
1.265     albertel 3283:   my @array;
                   3284: 
                   3285:   if($string !~ /^__ARRAY_REF__/) {
                   3286:       if (! ($string eq '' || !defined($string))) {
                   3287: 	  $array[0]='Array reference error';
                   3288:       }
                   3289:       return (\@array, $string);
                   3290:   }
                   3291: 
                   3292:   $string =~ s/^__ARRAY_REF__//;
                   3293: 
                   3294:   while($string !~ /^__END_ARRAY_REF__/) {
                   3295:       my $value='';
                   3296:       if($string =~ /^__HASH_REF__/) {
                   3297:           ($value, $string)=&str2hashref($string);
                   3298:           if(defined($value->{'error'})) {
                   3299:               $array[0] ='Array reference error';
                   3300:               return (\@array, $string);
                   3301:           }
                   3302:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3303:           ($value, $string)=&str2arrayref($string);
                   3304:           if($value->[0] eq 'Array reference error') {
                   3305:               $array[0] ='Array reference error';
                   3306:               return (\@array, $string);
                   3307:           }
                   3308:       } else {
                   3309: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3310:       }
                   3311:       $string =~ s/^&//;
                   3312: 
                   3313:       push(@array, $value);
1.191     harris41 3314:   }
1.265     albertel 3315: 
                   3316:   $string =~ s/^__END_ARRAY_REF__//;
                   3317: 
                   3318:   return (\@array, $string);
1.168     albertel 3319: }
                   3320: 
1.167     albertel 3321: # -------------------------------------------------------------------Temp Store
                   3322: 
1.168     albertel 3323: sub tmpreset {
                   3324:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3325:   if (!$symb) {
                   3326:     $symb=&symbread();
1.620     albertel 3327:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3328:   }
                   3329:   $symb=escape($symb);
                   3330: 
1.620     albertel 3331:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3332:   $namespace=~s/\//\_/g;
                   3333:   $namespace=~s/\W//g;
                   3334: 
1.620     albertel 3335:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3336:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3337:   if ($domain eq 'public' && $stuname eq 'public') {
                   3338:       $stuname=$ENV{'REMOTE_ADDR'};
                   3339:   }
1.168     albertel 3340:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3341:   my %hash;
                   3342:   if (tie(%hash,'GDBM_File',
                   3343: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3344: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3345:     foreach my $key (keys %hash) {
1.180     albertel 3346:       if ($key=~ /:$symb/) {
1.168     albertel 3347: 	delete($hash{$key});
                   3348:       }
                   3349:     }
                   3350:   }
                   3351: }
                   3352: 
1.167     albertel 3353: sub tmpstore {
1.168     albertel 3354:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3355: 
                   3356:   if (!$symb) {
                   3357:     $symb=&symbread();
1.620     albertel 3358:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3359:   }
                   3360:   $symb=escape($symb);
                   3361: 
                   3362:   if (!$namespace) {
                   3363:     # I don't think we would ever want to store this for a course.
                   3364:     # it seems this will only be used if we don't have a course.
1.620     albertel 3365:     #$namespace=$env{'request.course.id'};
1.168     albertel 3366:     #if (!$namespace) {
1.620     albertel 3367:       $namespace=$env{'request.state'};
1.168     albertel 3368:     #}
                   3369:   }
                   3370:   $namespace=~s/\//\_/g;
                   3371:   $namespace=~s/\W//g;
1.620     albertel 3372:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3373:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3374:   if ($domain eq 'public' && $stuname eq 'public') {
                   3375:       $stuname=$ENV{'REMOTE_ADDR'};
                   3376:   }
1.168     albertel 3377:   my $now=time;
                   3378:   my %hash;
                   3379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3380:   if (tie(%hash,'GDBM_File',
                   3381: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3382: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3383:     $hash{"version:$symb"}++;
                   3384:     my $version=$hash{"version:$symb"};
                   3385:     my $allkeys=''; 
                   3386:     foreach my $key (keys(%$storehash)) {
                   3387:       $allkeys.=$key.':';
1.591     albertel 3388:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3389:     }
                   3390:     $hash{"$version:$symb:timestamp"}=$now;
                   3391:     $allkeys.='timestamp';
                   3392:     $hash{"$version:keys:$symb"}=$allkeys;
                   3393:     if (untie(%hash)) {
                   3394:       return 'ok';
                   3395:     } else {
                   3396:       return "error:$!";
                   3397:     }
                   3398:   } else {
                   3399:     return "error:$!";
                   3400:   }
                   3401: }
1.167     albertel 3402: 
1.168     albertel 3403: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3404: 
1.168     albertel 3405: sub tmprestore {
                   3406:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3407: 
1.168     albertel 3408:   if (!$symb) {
                   3409:     $symb=&symbread();
1.620     albertel 3410:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3411:   }
                   3412:   $symb=escape($symb);
                   3413: 
1.620     albertel 3414:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3415: 
1.620     albertel 3416:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3417:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3418:   if ($domain eq 'public' && $stuname eq 'public') {
                   3419:       $stuname=$ENV{'REMOTE_ADDR'};
                   3420:   }
1.168     albertel 3421:   my %returnhash;
                   3422:   $namespace=~s/\//\_/g;
                   3423:   $namespace=~s/\W//g;
                   3424:   my %hash;
                   3425:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3426:   if (tie(%hash,'GDBM_File',
                   3427: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3428: 	  &GDBM_READER(),0640)) {
1.168     albertel 3429:     my $version=$hash{"version:$symb"};
                   3430:     $returnhash{'version'}=$version;
                   3431:     my $scope;
                   3432:     for ($scope=1;$scope<=$version;$scope++) {
                   3433:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3434:       my @keys=split(/:/,$vkeys);
                   3435:       my $key;
                   3436:       $returnhash{"$scope:keys"}=$vkeys;
                   3437:       foreach $key (@keys) {
1.591     albertel 3438: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3439: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3440:       }
                   3441:     }
1.168     albertel 3442:     if (!(untie(%hash))) {
                   3443:       return "error:$!";
                   3444:     }
                   3445:   } else {
                   3446:     return "error:$!";
                   3447:   }
                   3448:   return %returnhash;
1.167     albertel 3449: }
                   3450: 
1.9       www      3451: # ----------------------------------------------------------------------- Store
                   3452: 
                   3453: sub store {
1.124     www      3454:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3455:     my $home='';
                   3456: 
1.168     albertel 3457:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3458: 
1.213     www      3459:     $symb=&symbclean($symb);
1.122     albertel 3460:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3461: 
1.620     albertel 3462:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3463:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3464: 
                   3465:     &devalidate($symb,$stuname,$domain);
1.109     www      3466: 
                   3467:     $symb=escape($symb);
1.187     www      3468:     if (!$namespace) { 
1.620     albertel 3469:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3470:           return ''; 
                   3471:        } 
                   3472:     }
1.620     albertel 3473:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3474: 
                   3475:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3476:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3477: 
1.12      www      3478:     my $namevalue='';
1.800     albertel 3479:     foreach my $key (keys(%$storehash)) {
                   3480:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3481:     }
1.12      www      3482:     $namevalue=~s/\&$//;
1.187     www      3483:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3484:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3485: }
                   3486: 
1.47      www      3487: # -------------------------------------------------------------- Critical Store
                   3488: 
                   3489: sub cstore {
1.124     www      3490:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3491:     my $home='';
                   3492: 
1.168     albertel 3493:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3494: 
1.213     www      3495:     $symb=&symbclean($symb);
1.122     albertel 3496:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3497: 
1.620     albertel 3498:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3499:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3500: 
                   3501:     &devalidate($symb,$stuname,$domain);
1.109     www      3502: 
                   3503:     $symb=escape($symb);
1.187     www      3504:     if (!$namespace) { 
1.620     albertel 3505:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3506:           return ''; 
                   3507:        } 
                   3508:     }
1.620     albertel 3509:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3510: 
                   3511:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3512:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3513: 
1.47      www      3514:     my $namevalue='';
1.800     albertel 3515:     foreach my $key (keys(%$storehash)) {
                   3516:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3517:     }
1.47      www      3518:     $namevalue=~s/\&$//;
1.187     www      3519:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3520:     return critical
                   3521:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3522: }
                   3523: 
1.9       www      3524: # --------------------------------------------------------------------- Restore
                   3525: 
                   3526: sub restore {
1.124     www      3527:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3528:     my $home='';
                   3529: 
1.168     albertel 3530:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3531: 
1.122     albertel 3532:     if (!$symb) {
                   3533:       unless ($symb=escape(&symbread())) { return ''; }
                   3534:     } else {
1.213     www      3535:       $symb=&escape(&symbclean($symb));
1.122     albertel 3536:     }
1.188     www      3537:     if (!$namespace) { 
1.620     albertel 3538:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3539:           return ''; 
                   3540:        } 
                   3541:     }
1.620     albertel 3542:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3543:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3544:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3545:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3546: 
1.12      www      3547:     my %returnhash=();
1.800     albertel 3548:     foreach my $line (split(/\&/,$answer)) {
                   3549: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3550:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3551:     }
1.75      www      3552:     my $version;
                   3553:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3554:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3555:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3556:        }
1.75      www      3557:     }
1.13      www      3558:     return %returnhash;
1.34      www      3559: }
                   3560: 
                   3561: # ---------------------------------------------------------- Course Description
                   3562: 
                   3563: sub coursedescription {
1.731     albertel 3564:     my ($courseid,$args)=@_;
1.34      www      3565:     $courseid=~s/^\///;
1.49      www      3566:     $courseid=~s/\_/\//g;
1.34      www      3567:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3568:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3569:     my $normalid=$cdomain.'_'.$cnum;
                   3570:     # need to always cache even if we get errors otherwise we keep 
                   3571:     # trying and trying and trying to get the course description.
                   3572:     my %envhash=();
                   3573:     my %returnhash=();
1.731     albertel 3574:     
                   3575:     my $expiretime=600;
                   3576:     if ($env{'request.course.id'} eq $normalid) {
                   3577: 	$expiretime=120;
                   3578:     }
                   3579: 
                   3580:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3581:     if (!$args->{'freshen_cache'}
                   3582: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3583: 	foreach my $key (keys(%env)) {
                   3584: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3585: 	    my ($setting) = $1;
                   3586: 	    $returnhash{$setting} = $env{$key};
                   3587: 	}
                   3588: 	return %returnhash;
                   3589:     }
                   3590: 
                   3591:     # get the data agin
                   3592:     if (!$args->{'one_time'}) {
                   3593: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3594:     }
1.811     albertel 3595: 
1.34      www      3596:     if ($chome ne 'no_host') {
1.302     albertel 3597:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3598:        if (!exists($returnhash{'con_lost'})) {
                   3599:            $returnhash{'home'}= $chome;
                   3600: 	   $returnhash{'domain'} = $cdomain;
                   3601: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3602:            if (!defined($returnhash{'type'})) {
                   3603:                $returnhash{'type'} = 'Course';
                   3604:            }
1.130     albertel 3605:            while (my ($name,$value) = each %returnhash) {
1.53      www      3606:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3607:            }
1.270     www      3608:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3609:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3610: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3611:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3612:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3613:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3614:        }
                   3615:     }
1.731     albertel 3616:     if (!$args->{'one_time'}) {
1.949     raeburn  3617: 	&appenv(\%envhash);
1.731     albertel 3618:     }
1.302     albertel 3619:     return %returnhash;
1.461     www      3620: }
                   3621: 
                   3622: # -------------------------------------------------See if a user is privileged
                   3623: 
                   3624: sub privileged {
                   3625:     my ($username,$domain)=@_;
                   3626:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3627: 			&homeserver($username,$domain));
                   3628:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3629:     my $now=time;
                   3630:     if ($rolesdump ne '') {
1.800     albertel 3631:         foreach my $entry (split(/&/,$rolesdump)) {
                   3632: 	    if ($entry!~/^rolesdef_/) {
                   3633: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3634: 		$area=~s/\_\w\w$//;
                   3635: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3636: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3637: 		    my $active=1;
                   3638: 		    if ($tend) {
                   3639: 			if ($tend<$now) { $active=0; }
                   3640: 		    }
                   3641: 		    if ($tstart) {
                   3642: 			if ($tstart>$now) { $active=0; }
                   3643: 		    }
                   3644: 		    if ($active) { return 1; }
                   3645: 		}
                   3646: 	    }
                   3647: 	}
                   3648:     }
                   3649:     return 0;
1.9       www      3650: }
1.1       albertel 3651: 
1.103     harris41 3652: # -------------------------------------------------------- Get user privileges
1.11      www      3653: 
                   3654: sub rolesinit {
                   3655:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3656:     my %userroles;
1.11      www      3657:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3658:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3659:     my %allroles=();
1.678     raeburn  3660:     my %allgroups=();   
1.11      www      3661:     my $now=time;
1.966     raeburn  3662:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3663:     my $group_privs;
1.11      www      3664: 
                   3665:     if ($rolesdump ne '') {
1.800     albertel 3666:         foreach my $entry (split(/&/,$rolesdump)) {
                   3667: 	  if ($entry!~/^rolesdef_/) {
                   3668:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3669: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3670:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3671: 	    if ($role=~/^cr/) { 
1.807     albertel 3672: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3673: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3674: 		    ($tend,$tstart)=split('_',$trest);
                   3675: 		} else {
                   3676: 		    $trole=$role;
                   3677: 		}
1.678     raeburn  3678:             } elsif ($role =~ m|^gr/|) {
                   3679:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3680:                 ($trole,$group_privs) = split(/\//,$trole);
                   3681:                 $group_privs = &unescape($group_privs);
1.587     albertel 3682: 	    } else {
                   3683: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3684: 	    }
1.743     albertel 3685: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3686: 					 $username);
                   3687: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3688:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3689:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3690:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3691: 		my $spec=$trole.'.'.$area;
                   3692: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3693: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3694:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3695:                 } elsif ($trole eq 'gr') {
                   3696:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3697: 		} else {
1.567     raeburn  3698:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3699: 		}
1.12      www      3700:             }
1.662     raeburn  3701:           }
1.191     harris41 3702:         }
1.743     albertel 3703:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3704:         $userroles{'user.adv'}    = $adv;
                   3705: 	$userroles{'user.author'} = $author;
1.620     albertel 3706:         $env{'user.adv'}=$adv;
1.11      www      3707:     }
1.743     albertel 3708:     return \%userroles;  
1.11      www      3709: }
                   3710: 
1.567     raeburn  3711: sub set_arearole {
                   3712:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3713: # log the associated role with the area
                   3714:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3715:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3716: }
                   3717: 
                   3718: sub custom_roleprivs {
                   3719:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3720:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3721:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3722:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3723:         my ($rdummy,$roledef)=
                   3724:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3725:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3726:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3727:             if (defined($syspriv)) {
                   3728:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3729:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3730:             }
                   3731:             if ($tdomain ne '') {
                   3732:                 if (defined($dompriv)) {
                   3733:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3734:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3735:                 }
                   3736:                 if (($trest ne '') && (defined($coursepriv))) {
                   3737:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3738:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3739:                 }
                   3740:             }
                   3741:         }
                   3742:     }
                   3743: }
                   3744: 
1.678     raeburn  3745: sub group_roleprivs {
                   3746:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3747:     my $access = 1;
                   3748:     my $now = time;
                   3749:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3750:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3751:     if ($access) {
1.811     albertel 3752:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3753:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3754:     }
                   3755: }
1.567     raeburn  3756: 
                   3757: sub standard_roleprivs {
                   3758:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3759:     if (defined($pr{$trole.':s'})) {
                   3760:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3761:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3762:     }
                   3763:     if ($tdomain ne '') {
                   3764:         if (defined($pr{$trole.':d'})) {
                   3765:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3766:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3767:         }
                   3768:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3769:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3770:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3771:         }
                   3772:     }
                   3773: }
                   3774: 
                   3775: sub set_userprivs {
1.678     raeburn  3776:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3777:     my $author=0;
                   3778:     my $adv=0;
1.678     raeburn  3779:     my %grouproles = ();
                   3780:     if (keys(%{$allgroups}) > 0) {
                   3781:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3782:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3783:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3784:                 $trole = $1;
                   3785:                 $area = $2;
1.681     raeburn  3786:                 $sec = $3;
                   3787:                 $extendedarea = $area.$sec;
                   3788:                 if (exists($$allgroups{$area})) {
                   3789:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3790:                         my $spec = $trole.'.'.$extendedarea;
                   3791:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3792:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3793:                     }
                   3794:                 }
                   3795:             }
                   3796:         }
                   3797:     }
1.800     albertel 3798:     foreach my $group (keys(%grouproles)) {
                   3799:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3800:     }
1.800     albertel 3801:     foreach my $role (keys(%{$allroles})) {
                   3802:         my %thesepriv;
1.941     raeburn  3803:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3804:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3805:             if ($item ne '') {
                   3806:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3807:                 if ($restrictions eq '') {
                   3808:                     $thesepriv{$privilege}='F';
                   3809:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3810:                     $thesepriv{$privilege}.=$restrictions;
                   3811:                 }
                   3812:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3813:             }
                   3814:         }
                   3815:         my $thesestr='';
1.800     albertel 3816:         foreach my $priv (keys(%thesepriv)) {
                   3817: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3818: 	}
                   3819:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3820:     }
                   3821:     return ($author,$adv);
                   3822: }
                   3823: 
1.12      www      3824: # --------------------------------------------------------------- get interface
                   3825: 
                   3826: sub get {
1.131     albertel 3827:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3828:    my $items='';
1.800     albertel 3829:    foreach my $item (@$storearr) {
                   3830:        $items.=&escape($item).'&';
1.191     harris41 3831:    }
1.12      www      3832:    $items=~s/\&$//;
1.620     albertel 3833:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3834:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3835:    my $uhome=&homeserver($uname,$udomain);
                   3836: 
1.133     albertel 3837:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3838:    my @pairs=split(/\&/,$rep);
1.273     albertel 3839:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3840:      return @pairs;
                   3841:    }
1.15      www      3842:    my %returnhash=();
1.42      www      3843:    my $i=0;
1.800     albertel 3844:    foreach my $item (@$storearr) {
                   3845:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3846:       $i++;
1.191     harris41 3847:    }
1.15      www      3848:    return %returnhash;
1.27      www      3849: }
                   3850: 
                   3851: # --------------------------------------------------------------- del interface
                   3852: 
                   3853: sub del {
1.133     albertel 3854:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3855:    my $items='';
1.800     albertel 3856:    foreach my $item (@$storearr) {
                   3857:        $items.=&escape($item).'&';
1.191     harris41 3858:    }
1.27      www      3859:    $items=~s/\&$//;
1.620     albertel 3860:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3861:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3862:    my $uhome=&homeserver($uname,$udomain);
                   3863: 
                   3864:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3865: }
                   3866: 
                   3867: # -------------------------------------------------------------- dump interface
                   3868: 
                   3869: sub dump {
1.755     albertel 3870:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3871:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3872:     if (!$uname) { $uname=$env{'user.name'}; }
                   3873:     my $uhome=&homeserver($uname,$udomain);
                   3874:     if ($regexp) {
                   3875: 	$regexp=&escape($regexp);
                   3876:     } else {
                   3877: 	$regexp='.';
                   3878:     }
                   3879:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3880:     my @pairs=split(/\&/,$rep);
                   3881:     my %returnhash=();
                   3882:     foreach my $item (@pairs) {
                   3883: 	my ($key,$value)=split(/=/,$item,2);
                   3884: 	$key = &unescape($key);
                   3885: 	next if ($key =~ /^error: 2 /);
                   3886: 	$returnhash{$key}=&thaw_unescape($value);
                   3887:     }
                   3888:     return %returnhash;
1.407     www      3889: }
                   3890: 
1.717     albertel 3891: # --------------------------------------------------------- dumpstore interface
                   3892: 
                   3893: sub dumpstore {
                   3894:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3896:    if (!$uname) { $uname=$env{'user.name'}; }
                   3897:    my $uhome=&homeserver($uname,$udomain);
                   3898:    if ($regexp) {
                   3899:        $regexp=&escape($regexp);
                   3900:    } else {
                   3901:        $regexp='.';
                   3902:    }
                   3903:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3904:    my @pairs=split(/\&/,$rep);
                   3905:    my %returnhash=();
                   3906:    foreach my $item (@pairs) {
                   3907:        my ($key,$value)=split(/=/,$item,2);
                   3908:        next if ($key =~ /^error: 2 /);
                   3909:        $returnhash{$key}=&thaw_unescape($value);
                   3910:    }
                   3911:    return %returnhash;
1.717     albertel 3912: }
                   3913: 
1.407     www      3914: # -------------------------------------------------------------- keys interface
                   3915: 
                   3916: sub getkeys {
                   3917:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3918:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3919:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3920:    my $uhome=&homeserver($uname,$udomain);
                   3921:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3922:    my @keyarray=();
1.800     albertel 3923:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3924:       next if ($key =~ /^error: 2 /);
1.800     albertel 3925:       push(@keyarray,&unescape($key));
1.407     www      3926:    }
                   3927:    return @keyarray;
1.318     matthew  3928: }
                   3929: 
1.319     matthew  3930: # --------------------------------------------------------------- currentdump
                   3931: sub currentdump {
1.328     matthew  3932:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3933:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3934:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3935:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3936:    my $uhome = &homeserver($sname,$sdom);
                   3937:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3938:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3939:    #
1.318     matthew  3940:    my %returnhash=();
1.319     matthew  3941:    #
                   3942:    if ($rep eq "unknown_cmd") { 
                   3943:        # an old lond will not know currentdump
                   3944:        # Do a dump and make it look like a currentdump
1.822     albertel 3945:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3946:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3947:        my %hash = @tmp;
                   3948:        @tmp=();
1.424     matthew  3949:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3950:    } else {
                   3951:        my @pairs=split(/\&/,$rep);
1.800     albertel 3952:        foreach my $pair (@pairs) {
                   3953:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3954:            my ($symb,$param) = split(/:/,$key);
                   3955:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3956:                                                         &thaw_unescape($value);
1.319     matthew  3957:        }
1.191     harris41 3958:    }
1.12      www      3959:    return %returnhash;
1.424     matthew  3960: }
                   3961: 
                   3962: sub convert_dump_to_currentdump{
                   3963:     my %hash = %{shift()};
                   3964:     my %returnhash;
                   3965:     # Code ripped from lond, essentially.  The only difference
                   3966:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3967:     # we might run in to problems with parameter names =~ /^v\./
                   3968:     while (my ($key,$value) = each(%hash)) {
                   3969:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3970: 	$symb  = &unescape($symb);
                   3971: 	$param = &unescape($param);
1.424     matthew  3972:         next if ($v eq 'version' || $symb eq 'keys');
                   3973:         next if (exists($returnhash{$symb}) &&
                   3974:                  exists($returnhash{$symb}->{$param}) &&
                   3975:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3976:         $returnhash{$symb}->{$param}=$value;
                   3977:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3978:     }
                   3979:     #
                   3980:     # Remove all of the keys in the hashes which keep track of
                   3981:     # the version of the parameter.
                   3982:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3983:         # use a foreach because we are going to delete from the hash.
                   3984:         foreach my $key (keys(%$param_hash)) {
                   3985:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3986:         }
                   3987:     }
                   3988:     return \%returnhash;
1.12      www      3989: }
                   3990: 
1.627     albertel 3991: # ------------------------------------------------------ critical inc interface
                   3992: 
                   3993: sub cinc {
                   3994:     return &inc(@_,'critical');
                   3995: }
                   3996: 
1.449     matthew  3997: # --------------------------------------------------------------- inc interface
                   3998: 
                   3999: sub inc {
1.627     albertel 4000:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4001:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4002:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4003:     my $uhome=&homeserver($uname,$udomain);
                   4004:     my $items='';
                   4005:     if (! ref($store)) {
                   4006:         # got a single value, so use that instead
                   4007:         $items = &escape($store).'=&';
                   4008:     } elsif (ref($store) eq 'SCALAR') {
                   4009:         $items = &escape($$store).'=&';        
                   4010:     } elsif (ref($store) eq 'ARRAY') {
                   4011:         $items = join('=&',map {&escape($_);} @{$store});
                   4012:     } elsif (ref($store) eq 'HASH') {
                   4013:         while (my($key,$value) = each(%{$store})) {
                   4014:             $items.= &escape($key).'='.&escape($value).'&';
                   4015:         }
                   4016:     }
                   4017:     $items=~s/\&$//;
1.627     albertel 4018:     if ($critical) {
                   4019: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4020:     } else {
                   4021: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4022:     }
1.449     matthew  4023: }
                   4024: 
1.12      www      4025: # --------------------------------------------------------------- put interface
                   4026: 
                   4027: sub put {
1.134     albertel 4028:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4029:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4030:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4031:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4032:    my $items='';
1.800     albertel 4033:    foreach my $item (keys(%$storehash)) {
                   4034:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4035:    }
1.12      www      4036:    $items=~s/\&$//;
1.134     albertel 4037:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4038: }
                   4039: 
1.631     albertel 4040: # ------------------------------------------------------------ newput interface
                   4041: 
                   4042: sub newput {
                   4043:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4044:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4045:    if (!$uname) { $uname=$env{'user.name'}; }
                   4046:    my $uhome=&homeserver($uname,$udomain);
                   4047:    my $items='';
                   4048:    foreach my $key (keys(%$storehash)) {
                   4049:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4050:    }
                   4051:    $items=~s/\&$//;
                   4052:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4053: }
                   4054: 
                   4055: # ---------------------------------------------------------  putstore interface
                   4056: 
1.524     raeburn  4057: sub putstore {
1.715     albertel 4058:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4059:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4060:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4061:    my $uhome=&homeserver($uname,$udomain);
                   4062:    my $items='';
1.715     albertel 4063:    foreach my $key (keys(%$storehash)) {
                   4064:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4065:    }
1.715     albertel 4066:    $items=~s/\&$//;
1.716     albertel 4067:    my $esc_symb=&escape($symb);
                   4068:    my $esc_v=&escape($version);
1.715     albertel 4069:    my $reply =
1.716     albertel 4070:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4071: 	      $uhome);
                   4072:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4073:        # gfall back to way things use to be done
1.715     albertel 4074:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4075: 			    $uname);
1.524     raeburn  4076:    }
1.715     albertel 4077:    return $reply;
                   4078: }
                   4079: 
                   4080: sub old_putstore {
1.716     albertel 4081:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4082:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4083:     if (!$uname) { $uname=$env{'user.name'}; }
                   4084:     my $uhome=&homeserver($uname,$udomain);
                   4085:     my %newstorehash;
1.800     albertel 4086:     foreach my $item (keys(%$storehash)) {
                   4087: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4088: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4089:     }
                   4090:     my $items='';
                   4091:     my %allitems = ();
1.800     albertel 4092:     foreach my $item (keys(%newstorehash)) {
                   4093: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4094: 	    my $key = $1.':keys:'.$2;
                   4095: 	    $allitems{$key} .= $3.':';
                   4096: 	}
1.800     albertel 4097: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4098:     }
1.800     albertel 4099:     foreach my $item (keys(%allitems)) {
                   4100: 	$allitems{$item} =~ s/\:$//;
                   4101: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4102:     }
                   4103:     $items=~s/\&$//;
                   4104:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4105: }
                   4106: 
1.47      www      4107: # ------------------------------------------------------ critical put interface
                   4108: 
                   4109: sub cput {
1.134     albertel 4110:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4111:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4112:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4113:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4114:    my $items='';
1.800     albertel 4115:    foreach my $item (keys(%$storehash)) {
                   4116:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4117:    }
1.47      www      4118:    $items=~s/\&$//;
1.134     albertel 4119:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4120: }
                   4121: 
                   4122: # -------------------------------------------------------------- eget interface
                   4123: 
                   4124: sub eget {
1.133     albertel 4125:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4126:    my $items='';
1.800     albertel 4127:    foreach my $item (@$storearr) {
                   4128:        $items.=&escape($item).'&';
1.191     harris41 4129:    }
1.12      www      4130:    $items=~s/\&$//;
1.620     albertel 4131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4132:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4133:    my $uhome=&homeserver($uname,$udomain);
                   4134:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4135:    my @pairs=split(/\&/,$rep);
                   4136:    my %returnhash=();
1.42      www      4137:    my $i=0;
1.800     albertel 4138:    foreach my $item (@$storearr) {
                   4139:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4140:       $i++;
1.191     harris41 4141:    }
1.12      www      4142:    return %returnhash;
                   4143: }
                   4144: 
1.667     albertel 4145: # ------------------------------------------------------------ tmpput interface
                   4146: sub tmpput {
1.802     raeburn  4147:     my ($storehash,$server,$context)=@_;
1.667     albertel 4148:     my $items='';
1.800     albertel 4149:     foreach my $item (keys(%$storehash)) {
                   4150: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4151:     }
                   4152:     $items=~s/\&$//;
1.802     raeburn  4153:     if (defined($context)) {
                   4154:         $items .= ':'.&escape($context);
                   4155:     }
1.667     albertel 4156:     return &reply("tmpput:$items",$server);
                   4157: }
                   4158: 
                   4159: # ------------------------------------------------------------ tmpget interface
                   4160: sub tmpget {
1.688     albertel 4161:     my ($token,$server)=@_;
                   4162:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4163:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4164:     my %returnhash;
                   4165:     foreach my $item (split(/\&/,$rep)) {
                   4166: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4167:         next if ($key =~ /^error: 2 /);
1.667     albertel 4168: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4169:     }
                   4170:     return %returnhash;
                   4171: }
                   4172: 
1.688     albertel 4173: # ------------------------------------------------------------ tmpget interface
                   4174: sub tmpdel {
                   4175:     my ($token,$server)=@_;
                   4176:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4177:     return &reply("tmpdel:$token",$server);
                   4178: }
                   4179: 
1.765     albertel 4180: # -------------------------------------------------- portfolio access checking
                   4181: 
                   4182: sub portfolio_access {
1.766     albertel 4183:     my ($requrl) = @_;
1.765     albertel 4184:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4185:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4186:     if ($result) {
                   4187:         my %setters;
                   4188:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4189:             my ($startblock,$endblock) =
                   4190:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4191:             if ($startblock && $endblock) {
                   4192:                 return 'B';
                   4193:             }
                   4194:         } else {
                   4195:             my ($startblock,$endblock) =
                   4196:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4197:             if ($startblock && $endblock) {
                   4198:                 return 'B';
                   4199:             }
                   4200:         }
                   4201:     }
1.765     albertel 4202:     if ($result eq 'ok') {
1.766     albertel 4203:        return 'F';
1.765     albertel 4204:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4205:        return 'A';
1.765     albertel 4206:     }
1.766     albertel 4207:     return '';
1.765     albertel 4208: }
                   4209: 
                   4210: sub get_portfolio_access {
1.767     albertel 4211:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4212: 
                   4213:     if (!ref($access_hash)) {
                   4214: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4215: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4216: 						   $file_name);
                   4217: 	$access_hash = $access_controls{$file_name};
                   4218:     }
                   4219: 
1.765     albertel 4220:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4221:     my $now = time;
                   4222:     if (ref($access_hash) eq 'HASH') {
                   4223:         foreach my $key (keys(%{$access_hash})) {
                   4224:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4225:             if ($start > $now) {
                   4226:                 next;
                   4227:             }
                   4228:             if ($end && $end<$now) {
                   4229:                 next;
                   4230:             }
                   4231:             if ($scope eq 'public') {
                   4232:                 $public = $key;
                   4233:                 last;
                   4234:             } elsif ($scope eq 'guest') {
                   4235:                 $guest = $key;
                   4236:             } elsif ($scope eq 'domains') {
                   4237:                 push(@domains,$key);
                   4238:             } elsif ($scope eq 'users') {
                   4239:                 push(@users,$key);
                   4240:             } elsif ($scope eq 'course') {
                   4241:                 push(@courses,$key);
                   4242:             } elsif ($scope eq 'group') {
                   4243:                 push(@groups,$key);
                   4244:             }
                   4245:         }
                   4246:         if ($public) {
                   4247:             return 'ok';
                   4248:         }
                   4249:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4250:             if ($guest) {
                   4251:                 return $guest;
                   4252:             }
                   4253:         } else {
                   4254:             if (@domains > 0) {
                   4255:                 foreach my $domkey (@domains) {
                   4256:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4257:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4258:                             return 'ok';
                   4259:                         }
                   4260:                     }
                   4261:                 }
                   4262:             }
                   4263:             if (@users > 0) {
                   4264:                 foreach my $userkey (@users) {
1.865     raeburn  4265:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4266:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4267:                             if (ref($item) eq 'HASH') {
                   4268:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4269:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4270:                                     return 'ok';
                   4271:                                 }
                   4272:                             }
                   4273:                         }
                   4274:                     } 
1.765     albertel 4275:                 }
                   4276:             }
                   4277:             my %roleshash;
                   4278:             my @courses_and_groups = @courses;
                   4279:             push(@courses_and_groups,@groups); 
                   4280:             if (@courses_and_groups > 0) {
                   4281:                 my (%allgroups,%allroles); 
                   4282:                 my ($start,$end,$role,$sec,$group);
                   4283:                 foreach my $envkey (%env) {
1.811     albertel 4284:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4285:                         my $cid = $2.'_'.$3; 
                   4286:                         if ($1 eq 'gr') {
                   4287:                             $group = $4;
                   4288:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4289:                         } else {
                   4290:                             if ($4 eq '') {
                   4291:                                 $sec = 'none';
                   4292:                             } else {
                   4293:                                 $sec = $4;
                   4294:                             }
                   4295:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4296:                         }
1.811     albertel 4297:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4298:                         my $cid = $2.'_'.$3;
                   4299:                         if ($4 eq '') {
                   4300:                             $sec = 'none';
                   4301:                         } else {
                   4302:                             $sec = $4;
                   4303:                         }
                   4304:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4305:                     }
                   4306:                 }
                   4307:                 if (keys(%allroles) == 0) {
                   4308:                     return;
                   4309:                 }
                   4310:                 foreach my $key (@courses_and_groups) {
                   4311:                     my %content = %{$$access_hash{$key}};
                   4312:                     my $cnum = $content{'number'};
                   4313:                     my $cdom = $content{'domain'};
                   4314:                     my $cid = $cdom.'_'.$cnum;
                   4315:                     if (!exists($allroles{$cid})) {
                   4316:                         next;
                   4317:                     }    
                   4318:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4319:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4320:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4321:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4322:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4323:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4324:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4325:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4326:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4327:                                         if (grep/^all$/,@sections) {
                   4328:                                             return 'ok';
                   4329:                                         } else {
                   4330:                                             if (grep/^$sec$/,@sections) {
                   4331:                                                 return 'ok';
                   4332:                                             }
                   4333:                                         }
                   4334:                                     }
                   4335:                                 }
                   4336:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4337:                                     if (grep/^none$/,@groups) {
                   4338:                                         return 'ok';
                   4339:                                     }
                   4340:                                 } else {
                   4341:                                     if (grep/^all$/,@groups) {
                   4342:                                         return 'ok';
                   4343:                                     } 
                   4344:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4345:                                         if (grep/^$group$/,@groups) {
                   4346:                                             return 'ok';
                   4347:                                         }
                   4348:                                     }
                   4349:                                 } 
                   4350:                             }
                   4351:                         }
                   4352:                     }
                   4353:                 }
                   4354:             }
                   4355:             if ($guest) {
                   4356:                 return $guest;
                   4357:             }
                   4358:         }
                   4359:     }
                   4360:     return;
                   4361: }
                   4362: 
                   4363: sub course_group_datechecker {
                   4364:     my ($dates,$now,$status) = @_;
                   4365:     my ($start,$end) = split(/\./,$dates);
                   4366:     if (!$start && !$end) {
                   4367:         return 'ok';
                   4368:     }
                   4369:     if (grep/^active$/,@{$status}) {
                   4370:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4371:             return 'ok';
                   4372:         }
                   4373:     }
                   4374:     if (grep/^previous$/,@{$status}) {
                   4375:         if ($end > $now ) {
                   4376:             return 'ok';
                   4377:         }
                   4378:     }
                   4379:     if (grep/^future$/,@{$status}) {
                   4380:         if ($start > $now) {
                   4381:             return 'ok';
                   4382:         }
                   4383:     }
                   4384:     return; 
                   4385: }
                   4386: 
                   4387: sub parse_portfolio_url {
                   4388:     my ($url) = @_;
                   4389: 
                   4390:     my ($type,$udom,$unum,$group,$file_name);
                   4391:     
1.823     albertel 4392:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4393: 	$type = 1;
                   4394:         $udom = $1;
                   4395:         $unum = $2;
                   4396:         $file_name = $3;
1.823     albertel 4397:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4398: 	$type = 2;
                   4399:         $udom = $1;
                   4400:         $unum = $2;
                   4401:         $group = $3;
                   4402:         $file_name = $3.'/'.$4;
                   4403:     }
                   4404:     if (wantarray) {
                   4405: 	return ($type,$udom,$unum,$file_name,$group);
                   4406:     }
                   4407:     return $type;
                   4408: }
                   4409: 
                   4410: sub is_portfolio_url {
                   4411:     my ($url) = @_;
                   4412:     return scalar(&parse_portfolio_url($url));
                   4413: }
                   4414: 
1.798     raeburn  4415: sub is_portfolio_file {
                   4416:     my ($file) = @_;
1.820     raeburn  4417:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4418:         return 1;
                   4419:     }
                   4420:     return;
                   4421: }
                   4422: 
1.976     raeburn  4423: sub usertools_access {
1.978     raeburn  4424:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4425:     my $access;
                   4426:     my %tools = (
                   4427:                   aboutme   => 1,
                   4428:                   blog      => 1,
                   4429:                   portfolio => 1,
                   4430:                 );
                   4431:     return if (!defined($tools{$tool}));
                   4432: 
                   4433:     if ((!defined($udom)) || (!defined($uname))) {
                   4434:         $udom = $env{'user.domain'};
                   4435:         $uname = $env{'user.name'};
                   4436:     }
                   4437: 
1.978     raeburn  4438:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4439:         if ($action ne 'reload') {
                   4440:             return $env{'environment.availabletools.'.$tool};
                   4441:         } 
1.976     raeburn  4442:     }
                   4443: 
                   4444:     my ($toolstatus,$inststatus);
                   4445: 
                   4446:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4447:         $toolstatus = $env{'environment.tools.'.$tool};
                   4448:         $inststatus = $env{'environment.inststatus'};
                   4449:     } else {
                   4450:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4451:         $toolstatus = $userenv{'tools.'.$tool};
                   4452:         $inststatus = $userenv{'inststatus'};
                   4453:     }
                   4454: 
                   4455:     if ($toolstatus ne '') {
                   4456:         if ($toolstatus) {
                   4457:             $access = 1;
                   4458:         } else {
                   4459:             $access = 0;
                   4460:         }
                   4461:         return $access;
                   4462:     }
                   4463: 
                   4464:     my $is_adv = &is_advanced_user($udom,$uname);
                   4465:     my %domdef = &get_domain_defaults($udom);
                   4466:     if (ref($domdef{$tool}) eq 'HASH') {
                   4467:         if ($is_adv) {
                   4468:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4469:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4470:                     $access = 1;
                   4471:                 } else {
                   4472:                     $access = 0;
                   4473:                 }
                   4474:                 return $access;
                   4475:             }
                   4476:         }
                   4477:         if ($inststatus ne '') {
                   4478:             my ($hasaccess,$hasnoaccess);
                   4479:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4480:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4481:                     if ($domdef{$tool}{$affiliation}) {
                   4482:                         $hasaccess = 1;
                   4483:                     } else {
                   4484:                         $hasnoaccess = 1;
                   4485:                     }
                   4486:                 }
                   4487:             }
                   4488:             if ($hasaccess || $hasnoaccess) {
                   4489:                 if ($hasaccess) {
                   4490:                     $access = 1;
                   4491:                 } elsif ($hasnoaccess) {
                   4492:                     $access = 0; 
                   4493:                 }
                   4494:                 return $access;
                   4495:             }
                   4496:         } else {
                   4497:             if ($domdef{$tool}{'default'} ne '') {
                   4498:                 if ($domdef{$tool}{'default'}) {
                   4499:                     $access = 1;
                   4500:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4501:                     $access = 0;
                   4502:                 }
                   4503:                 return $access;
                   4504:             }
                   4505:         }
                   4506:     } else {
                   4507:         $access = 1;
                   4508:         return $access;
                   4509:     }
                   4510: }
                   4511: 
                   4512: sub is_advanced_user {
                   4513:     my ($udom,$uname) = @_;
                   4514:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4515:     my %allroles;
                   4516:     my $is_adv;
                   4517:     foreach my $role (keys(%roleshash)) {
                   4518:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4519:         my $area = '/'.$tdomain.'/'.$trest;
                   4520:         if ($sec ne '') {
                   4521:             $area .= '/'.$sec;
                   4522:         }
                   4523:         if (($area ne '') && ($trole ne '')) {
                   4524:             my $spec=$trole.'.'.$area;
                   4525:             if ($trole =~ /^cr\//) {
                   4526:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4527:             } elsif ($trole ne 'gr') {
                   4528:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4529:             }
                   4530:         }
                   4531:     }
                   4532:     foreach my $role (keys(%allroles)) {
                   4533:         last if ($is_adv);
                   4534:         foreach my $item (split(/:/,$allroles{$role})) {
                   4535:             if ($item ne '') {
                   4536:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4537:                 if ($privilege eq 'adv') {
                   4538:                     $is_adv = 1;
                   4539:                     last;
                   4540:                 }
                   4541:             }
                   4542:         }
                   4543:     }
                   4544:     return $is_adv;
                   4545: }
1.798     raeburn  4546: 
1.341     www      4547: # ---------------------------------------------- Custom access rule evaluation
                   4548: 
                   4549: sub customaccess {
                   4550:     my ($priv,$uri)=@_;
1.807     albertel 4551:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4552:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4553:     $udom = &LONCAPA::clean_domain($udom);
                   4554:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4555:     my $access=0;
1.800     albertel 4556:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4557: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4558: 	if ($type eq 'user') {
                   4559: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4560: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4561: 		if ($tdom) {
                   4562: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4563: 		}
1.896     albertel 4564: 		if ($tuname) {
                   4565: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4566: 		}
                   4567: 		$access=($effect eq 'allow');
                   4568: 		last;
                   4569: 	    }
                   4570: 	} else {
                   4571: 	    if ($role) {
                   4572: 		if ($role ne $urole) { next; }
                   4573: 	    }
                   4574: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4575: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4576: 		if ($tdom) {
                   4577: 		    if ($tdom ne $udom) { next; }
                   4578: 		}
                   4579: 		if ($tcrs) {
                   4580: 		    if ($tcrs ne $ucrs) { next; }
                   4581: 		}
                   4582: 		if ($tsec) {
                   4583: 		    if ($tsec ne $usec) { next; }
                   4584: 		}
                   4585: 		$access=($effect eq 'allow');
                   4586: 		last;
                   4587: 	    }
                   4588: 	    if ($realm eq '' && $role eq '') {
                   4589: 		$access=($effect eq 'allow');
                   4590: 	    }
1.402     bowersj2 4591: 	}
1.341     www      4592:     }
                   4593:     return $access;
                   4594: }
                   4595: 
1.103     harris41 4596: # ------------------------------------------------- Check for a user privilege
1.12      www      4597: 
                   4598: sub allowed {
1.810     raeburn  4599:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4600:     my $ver_orguri=$uri;
1.439     www      4601:     $uri=&deversion($uri);
1.152     www      4602:     my $orguri=$uri;
1.52      www      4603:     $uri=&declutter($uri);
1.809     raeburn  4604: 
1.810     raeburn  4605:     if ($priv eq 'evb') {
                   4606: # Evade communication block restrictions for specified role in a course
                   4607:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4608:             return $1;
                   4609:         } else {
                   4610:             return;
                   4611:         }
                   4612:     }
                   4613: 
1.620     albertel 4614:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4615: # Free bre access to adm and meta resources
1.775     albertel 4616:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4617: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4618: 	&& ($priv eq 'bre')) {
1.14      www      4619: 	return 'F';
1.159     www      4620:     }
                   4621: 
1.545     banghart 4622: # Free bre access to user's own portfolio contents
1.714     raeburn  4623:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4624:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4625: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4626:         my %setters;
                   4627:         my ($startblock,$endblock) = 
                   4628:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4629:         if ($startblock && $endblock) {
                   4630:             return 'B';
                   4631:         } else {
                   4632:             return 'F';
                   4633:         }
1.545     banghart 4634:     }
                   4635: 
1.762     raeburn  4636: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4637:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4638:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4639:         if (exists($env{'request.course.id'})) {
                   4640:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4641:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4642:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4643:                 my $courseprivid=$env{'request.course.id'};
                   4644:                 $courseprivid=~s/\_/\//;
                   4645:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4646:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4647:                     return $1; 
1.762     raeburn  4648:                 } else {
                   4649:                     if ($env{'request.course.sec'}) {
                   4650:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4651:                     }
                   4652:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4653:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4654:                         return $2;
                   4655:                     }
1.714     raeburn  4656:                 }
                   4657:             }
                   4658:         }
                   4659:     }
                   4660: 
1.159     www      4661: # Free bre to public access
                   4662: 
                   4663:     if ($priv eq 'bre') {
1.238     www      4664:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4665: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4666:            return 'F'; 
                   4667:         }
1.238     www      4668:         if ($copyright eq 'priv') {
                   4669:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4670: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4671: 		return '';
                   4672:             }
                   4673:         }
                   4674:         if ($copyright eq 'domain') {
                   4675:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4676: 	    unless (($env{'user.domain'} eq $1) ||
                   4677:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4678: 		return '';
                   4679:             }
1.262     matthew  4680:         }
1.620     albertel 4681:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4682:             # Library role, so allow browsing of resources in this domain.
                   4683:             return 'F';
1.238     www      4684:         }
1.341     www      4685:         if ($copyright eq 'custom') {
                   4686: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4687:         }
1.14      www      4688:     }
1.264     matthew  4689:     # Domain coordinator is trying to create a course
1.620     albertel 4690:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4691:         # uri is the requested domain in this case.
                   4692:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4693:         # a role of dc for the domain in question.
1.620     albertel 4694:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4695:     }
1.29      www      4696: 
1.52      www      4697:     my $thisallowed='';
                   4698:     my $statecond=0;
                   4699:     my $courseprivid='';
                   4700: 
                   4701: # Course
                   4702: 
1.620     albertel 4703:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4704:        $thisallowed.=$1;
                   4705:     }
1.29      www      4706: 
1.52      www      4707: # Domain
                   4708: 
1.620     albertel 4709:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4710:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4711:        $thisallowed.=$1;
                   4712:     }
1.52      www      4713: 
                   4714: # Course: uri itself is a course
1.66      www      4715:     my $courseuri=$uri;
                   4716:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4717:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4718: 
1.620     albertel 4719:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4720:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4721:        $thisallowed.=$1;
                   4722:     }
1.29      www      4723: 
1.665     albertel 4724: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4725: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4726:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4727: 	$thisallowed='';
1.671     raeburn  4728:         my ($match)=&is_on_map($uri);
                   4729:         if ($match) {
                   4730:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4731:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4732:                 $thisallowed.=$1;
                   4733:             }
                   4734:         } else {
1.705     albertel 4735:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4736:             if ($refuri) {
                   4737:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4738:                     $thisallowed='F';
1.671     raeburn  4739:                 } else {
                   4740:                     $refuri=&declutter($refuri);
                   4741:                     my ($match) = &is_on_map($refuri);
                   4742:                     if ($match) {
                   4743:                         $thisallowed='F';
                   4744:                     }
1.669     raeburn  4745:                 }
1.671     raeburn  4746:             }
                   4747:         }
1.314     www      4748:     }
1.492     albertel 4749: 
1.766     albertel 4750:     if ($priv eq 'bre'
                   4751: 	&& $thisallowed ne 'F' 
                   4752: 	&& $thisallowed ne '2'
                   4753: 	&& &is_portfolio_url($uri)) {
                   4754: 	$thisallowed = &portfolio_access($uri);
                   4755:     }
                   4756:     
1.52      www      4757: # Full access at system, domain or course-wide level? Exit.
1.29      www      4758:     if ($thisallowed=~/F/) {
                   4759: 	return 'F';
                   4760:     }
                   4761: 
1.52      www      4762: # If this is generating or modifying users, exit with special codes
1.29      www      4763: 
1.643     www      4764:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4765: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4766: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4767: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4768: 	    unless ($auname) { return $thisallowed; }
                   4769: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4770: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4771: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4772: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4773: 	}
1.52      www      4774: 	return $thisallowed;
                   4775:     }
                   4776: #
1.103     harris41 4777: # Gathered so far: system, domain and course wide privileges
1.52      www      4778: #
                   4779: # Course: See if uri or referer is an individual resource that is part of 
                   4780: # the course
                   4781: 
1.620     albertel 4782:     if ($env{'request.course.id'}) {
1.232     www      4783: 
1.620     albertel 4784:        $courseprivid=$env{'request.course.id'};
                   4785:        if ($env{'request.course.sec'}) {
                   4786:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4787:        }
                   4788:        $courseprivid=~s/\_/\//;
                   4789:        my $checkreferer=1;
1.232     www      4790:        my ($match,$cond)=&is_on_map($uri);
                   4791:        if ($match) {
                   4792:            $statecond=$cond;
1.620     albertel 4793:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4794:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4795:                $thisallowed.=$1;
                   4796:                $checkreferer=0;
                   4797:            }
1.29      www      4798:        }
1.83      www      4799:        
1.148     www      4800:        if ($checkreferer) {
1.620     albertel 4801: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4802:             unless ($refuri) {
1.800     albertel 4803:                 foreach my $key (keys(%env)) {
                   4804: 		    if ($key=~/^httpref\..*\*/) {
                   4805: 			my $pattern=$key;
1.156     www      4806:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4807:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4808:                         $pattern=~s/\//\\\//g;
1.152     www      4809:                         if ($orguri=~/$pattern/) {
1.800     albertel 4810: 			    $refuri=$env{$key};
1.148     www      4811:                         }
                   4812:                     }
1.191     harris41 4813:                 }
1.148     www      4814:             }
1.232     www      4815: 
1.148     www      4816:          if ($refuri) { 
1.152     www      4817: 	  $refuri=&declutter($refuri);
1.232     www      4818:           my ($match,$cond)=&is_on_map($refuri);
                   4819:             if ($match) {
                   4820:               my $refstatecond=$cond;
1.620     albertel 4821:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4822:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4823:                   $thisallowed.=$1;
1.53      www      4824:                   $uri=$refuri;
                   4825:                   $statecond=$refstatecond;
1.52      www      4826:               }
                   4827:           }
1.148     www      4828:         }
1.29      www      4829:        }
1.52      www      4830:    }
1.29      www      4831: 
1.52      www      4832: #
1.103     harris41 4833: # Gathered now: all privileges that could apply, and condition number
1.52      www      4834: # 
                   4835: #
                   4836: # Full or no access?
                   4837: #
1.29      www      4838: 
1.52      www      4839:     if ($thisallowed=~/F/) {
                   4840: 	return 'F';
                   4841:     }
1.29      www      4842: 
1.52      www      4843:     unless ($thisallowed) {
                   4844:         return '';
                   4845:     }
1.29      www      4846: 
1.52      www      4847: # Restrictions exist, deal with them
                   4848: #
                   4849: #   C:according to course preferences
                   4850: #   R:according to resource settings
                   4851: #   L:unless locked
                   4852: #   X:according to user session state
                   4853: #
                   4854: 
                   4855: # Possibly locked functionality, check all courses
1.54      www      4856: # Locks might take effect only after 10 minutes cache expiration for other
                   4857: # courses, and 2 minutes for current course
1.52      www      4858: 
                   4859:     my $envkey;
                   4860:     if ($thisallowed=~/L/) {
1.620     albertel 4861:         foreach $envkey (keys %env) {
1.54      www      4862:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4863:                my $courseid=$2;
                   4864:                my $roleid=$1.'.'.$2;
1.92      www      4865:                $courseid=~s/^\///;
1.54      www      4866:                my $expiretime=600;
1.620     albertel 4867:                if ($env{'request.role'} eq $roleid) {
1.54      www      4868: 		  $expiretime=120;
                   4869:                }
                   4870: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4871:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4872:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4873: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4874:                }
1.620     albertel 4875:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4876:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4877: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4878:                        &log($env{'user.domain'},$env{'user.name'},
                   4879:                             $env{'user.home'},
1.57      www      4880:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4881:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4882:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4883: 		       return '';
                   4884:                    }
                   4885:                }
1.620     albertel 4886:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4887:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4888: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4889:                        &log($env{'user.domain'},$env{'user.name'},
                   4890:                             $env{'user.home'},
1.57      www      4891:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4892:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4893:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4894: 		       return '';
                   4895:                    }
                   4896:                }
                   4897: 	   }
1.29      www      4898:        }
1.52      www      4899:     }
                   4900:    
                   4901: #
                   4902: # Rest of the restrictions depend on selected course
                   4903: #
                   4904: 
1.620     albertel 4905:     unless ($env{'request.course.id'}) {
1.766     albertel 4906: 	if ($thisallowed eq 'A') {
                   4907: 	    return 'A';
1.814     raeburn  4908:         } elsif ($thisallowed eq 'B') {
                   4909:             return 'B';
1.766     albertel 4910: 	} else {
                   4911: 	    return '1';
                   4912: 	}
1.52      www      4913:     }
1.29      www      4914: 
1.52      www      4915: #
                   4916: # Now user is definitely in a course
                   4917: #
1.53      www      4918: 
                   4919: 
                   4920: # Course preferences
                   4921: 
                   4922:    if ($thisallowed=~/C/) {
1.620     albertel 4923:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4924:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4925:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4926: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4927: 	   if ($priv ne 'pch') { 
                   4928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4929: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4930: 			$env{'request.course.id'});
                   4931: 	   }
1.237     www      4932:            return '';
                   4933:        }
                   4934: 
1.620     albertel 4935:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4936: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4937: 	   if ($priv ne 'pch') { 
                   4938: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4939: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4940: 			$env{'request.course.id'});
                   4941: 	   }
1.54      www      4942:            return '';
                   4943:        }
1.53      www      4944:    }
                   4945: 
                   4946: # Resource preferences
                   4947: 
                   4948:    if ($thisallowed=~/R/) {
1.620     albertel 4949:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4950:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4951: 	   if ($priv ne 'pch') { 
                   4952: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4953: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4954: 	   }
                   4955: 	   return '';
1.54      www      4956:        }
1.53      www      4957:    }
1.30      www      4958: 
1.246     www      4959: # Restricted by state or randomout?
1.30      www      4960: 
1.52      www      4961:    if ($thisallowed=~/X/) {
1.620     albertel 4962:       if ($env{'acc.randomout'}) {
1.579     albertel 4963: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4964:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4965:             return ''; 
                   4966:          }
1.247     www      4967:       }
                   4968:       if (&condval($statecond)) {
1.52      www      4969: 	 return '2';
                   4970:       } else {
                   4971:          return '';
                   4972:       }
                   4973:    }
1.30      www      4974: 
1.766     albertel 4975:     if ($thisallowed eq 'A') {
                   4976: 	return 'A';
1.814     raeburn  4977:     } elsif ($thisallowed eq 'B') {
                   4978:         return 'B';
1.766     albertel 4979:     }
1.52      www      4980:    return 'F';
1.232     www      4981: }
                   4982: 
1.710     albertel 4983: sub split_uri_for_cond {
                   4984:     my $uri=&deversion(&declutter(shift));
                   4985:     my @uriparts=split(/\//,$uri);
                   4986:     my $filename=pop(@uriparts);
                   4987:     my $pathname=join('/',@uriparts);
                   4988:     return ($pathname,$filename);
                   4989: }
1.232     www      4990: # --------------------------------------------------- Is a resource on the map?
                   4991: 
                   4992: sub is_on_map {
1.710     albertel 4993:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4994:     #Trying to find the conditional for the file
1.620     albertel 4995:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4996: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4997:     if ($match) {
1.289     bowersj2 4998: 	return (1,$1);
                   4999:     } else {
1.434     www      5000: 	return (0,0);
1.289     bowersj2 5001:     }
1.12      www      5002: }
                   5003: 
1.427     www      5004: # --------------------------------------------------------- Get symb from alias
                   5005: 
                   5006: sub get_symb_from_alias {
                   5007:     my $symb=shift;
                   5008:     my ($map,$resid,$url)=&decode_symb($symb);
                   5009: # Already is a symb
                   5010:     if ($url) { return $symb; }
                   5011: # Must be an alias
                   5012:     my $aliassymb='';
                   5013:     my %bighash;
1.620     albertel 5014:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5015:                             &GDBM_READER(),0640)) {
                   5016:         my $rid=$bighash{'mapalias_'.$symb};
                   5017: 	if ($rid) {
                   5018: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5019: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5020: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5021: 	}
                   5022:         untie %bighash;
                   5023:     }
                   5024:     return $aliassymb;
                   5025: }
                   5026: 
1.12      www      5027: # ----------------------------------------------------------------- Define Role
                   5028: 
                   5029: sub definerole {
                   5030:   if (allowed('mcr','/')) {
                   5031:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5032:     foreach my $role (split(':',$sysrole)) {
                   5033: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5034:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5035:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5036: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5037:                return "refused:s:$crole&$cqual"; 
                   5038:             }
                   5039:         }
1.191     harris41 5040:     }
1.800     albertel 5041:     foreach my $role (split(':',$domrole)) {
                   5042: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5043:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5044:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5045: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5046:                return "refused:d:$crole&$cqual"; 
                   5047:             }
                   5048:         }
1.191     harris41 5049:     }
1.800     albertel 5050:     foreach my $role (split(':',$courole)) {
                   5051: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5052:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5053:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5054: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5055:                return "refused:c:$crole&$cqual"; 
                   5056:             }
                   5057:         }
1.191     harris41 5058:     }
1.620     albertel 5059:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5060:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5061: 	        "rolesdef_$rolename=".
                   5062:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5063:     return reply($command,$env{'user.home'});
1.12      www      5064:   } else {
                   5065:     return 'refused';
                   5066:   }
1.105     harris41 5067: }
                   5068: 
                   5069: # ---------------- Make a metadata query against the network of library servers
                   5070: 
                   5071: sub metadata_query {
1.244     matthew  5072:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5073:     my %rhash;
1.845     albertel 5074:     my %libserv = &all_library();
1.244     matthew  5075:     my @server_list = (defined($server_array) ? @$server_array
                   5076:                                               : keys(%libserv) );
                   5077:     for my $server (@server_list) {
1.118     harris41 5078: 	unless ($custom or $customshow) {
                   5079: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5080: 	    $rhash{$server}=$reply;
                   5081: 	}
                   5082: 	else {
                   5083: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5084: 			     &escape($custom).':'.&escape($customshow),
                   5085: 			     $server);
                   5086: 	    $rhash{$server}=$reply;
                   5087: 	}
1.112     harris41 5088:     }
1.118     harris41 5089:     return \%rhash;
1.240     www      5090: }
                   5091: 
                   5092: # ----------------------------------------- Send log queries and wait for reply
                   5093: 
                   5094: sub log_query {
                   5095:     my ($uname,$udom,$query,%filters)=@_;
                   5096:     my $uhome=&homeserver($uname,$udom);
                   5097:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5098:     my $uhost=&hostname($uhome);
1.800     albertel 5099:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5100:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5101:                        $uhome);
1.479     albertel 5102:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5103:     return get_query_reply($queryid);
                   5104: }
                   5105: 
1.818     raeburn  5106: # -------------------------- Update MySQL table for portfolio file
                   5107: 
                   5108: sub update_portfolio_table {
1.821     raeburn  5109:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5110:     if ($group ne '') {
                   5111:         $file_name =~s /^\Q$group\E//;
                   5112:     }
1.818     raeburn  5113:     my $homeserver = &homeserver($uname,$udom);
                   5114:     my $queryid=
1.821     raeburn  5115:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5116:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5117:     my $reply = &get_query_reply($queryid);
                   5118:     return $reply;
                   5119: }
                   5120: 
1.899     raeburn  5121: # -------------------------- Update MySQL allusers table
                   5122: 
                   5123: sub update_allusers_table {
                   5124:     my ($uname,$udom,$names) = @_;
                   5125:     my $homeserver = &homeserver($uname,$udom);
                   5126:     my $queryid=
                   5127:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5128:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5129:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5130:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5131:                'generation='.&escape($names->{'generation'}).'%%'.
                   5132:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5133:                'id='.&escape($names->{'id'}),$homeserver);
                   5134:     my $reply = &get_query_reply($queryid);
                   5135:     return $reply;
                   5136: }
                   5137: 
1.508     raeburn  5138: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5139: 
                   5140: sub fetch_enrollment_query {
1.511     raeburn  5141:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5142:     my $homeserver;
1.547     raeburn  5143:     my $maxtries = 1;
1.508     raeburn  5144:     if ($context eq 'automated') {
                   5145:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5146:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5147:     } else {
                   5148:         $homeserver = &homeserver($cnum,$dom);
                   5149:     }
1.838     albertel 5150:     my $host=&hostname($homeserver);
1.506     raeburn  5151:     my $cmd = '';
1.800     albertel 5152:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5153:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5154:     }
                   5155:     $cmd =~ s/%%$//;
                   5156:     $cmd = &escape($cmd);
                   5157:     my $query = 'fetchenrollment';
1.620     albertel 5158:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5159:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5160:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5161:         return 'error: '.$queryid;
                   5162:     }
1.506     raeburn  5163:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5164:     my $tries = 1;
                   5165:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5166:         $reply = &get_query_reply($queryid);
                   5167:         $tries ++;
                   5168:     }
1.526     raeburn  5169:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5170:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5171:     } else {
1.901     albertel 5172:         my @responses = split(/:/,$reply);
1.515     raeburn  5173:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5174:             foreach my $line (@responses) {
                   5175:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5176:                 $$replyref{$key} = $value;
                   5177:             }
                   5178:         } else {
1.506     raeburn  5179:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5180:             foreach my $line (@responses) {
                   5181:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5182:                 $$replyref{$key} = $value;
                   5183:                 if ($value > 0) {
1.800     albertel 5184:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5185:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5186:                         my $destname = $pathname.'/'.$filename;
                   5187:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5188:                         if ($xml_classlist =~ /^error/) {
                   5189:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5190:                         } else {
1.506     raeburn  5191:                             if ( open(FILE,">$destname") ) {
                   5192:                                 print FILE &unescape($xml_classlist);
                   5193:                                 close(FILE);
1.526     raeburn  5194:                             } else {
                   5195:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5196:                             }
                   5197:                         }
                   5198:                     }
                   5199:                 }
                   5200:             }
                   5201:         }
                   5202:         return 'ok';
                   5203:     }
                   5204:     return 'error';
                   5205: }
                   5206: 
1.242     www      5207: sub get_query_reply {
                   5208:     my $queryid=shift;
1.240     www      5209:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5210:     my $reply='';
                   5211:     for (1..100) {
                   5212: 	sleep 2;
                   5213:         if (-e $replyfile.'.end') {
1.448     albertel 5214: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5215: 		$reply = join('',<$fh>);
                   5216: 		close($fh);
1.240     www      5217: 	   } else { return 'error: reply_file_error'; }
1.242     www      5218:            return &unescape($reply);
                   5219: 	}
1.240     www      5220:     }
1.242     www      5221:     return 'timeout:'.$queryid;
1.240     www      5222: }
                   5223: 
                   5224: sub courselog_query {
1.241     www      5225: #
                   5226: # possible filters:
                   5227: # url: url or symb
                   5228: # username
                   5229: # domain
                   5230: # action: view, submit, grade
                   5231: # start: timestamp
                   5232: # end: timestamp
                   5233: #
1.240     www      5234:     my (%filters)=@_;
1.620     albertel 5235:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5236:     if ($filters{'url'}) {
                   5237: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5238:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5239:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5240:     }
1.620     albertel 5241:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5242:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5243:     return &log_query($cname,$cdom,'courselog',%filters);
                   5244: }
                   5245: 
                   5246: sub userlog_query {
1.858     raeburn  5247: #
                   5248: # possible filters:
                   5249: # action: log check role
                   5250: # start: timestamp
                   5251: # end: timestamp
                   5252: #
1.240     www      5253:     my ($uname,$udom,%filters)=@_;
                   5254:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5255: }
                   5256: 
1.506     raeburn  5257: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5258: 
                   5259: sub auto_run {
1.508     raeburn  5260:     my ($cnum,$cdom) = @_;
1.876     raeburn  5261:     my $response = 0;
                   5262:     my $settings;
                   5263:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5264:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5265:         $settings = $domconfig{'autoenroll'};
                   5266:         if ($settings->{'run'} eq '1') {
                   5267:             $response = 1;
                   5268:         }
                   5269:     } else {
1.934     raeburn  5270:         my $homeserver;
                   5271:         if (&is_course($cdom,$cnum)) {
                   5272:             $homeserver = &homeserver($cnum,$cdom);
                   5273:         } else {
                   5274:             $homeserver = &domain($cdom,'primary');
                   5275:         }
                   5276:         if ($homeserver ne 'no_host') {
                   5277:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5278:         }
1.876     raeburn  5279:     }
1.506     raeburn  5280:     return $response;
                   5281: }
1.776     albertel 5282: 
1.506     raeburn  5283: sub auto_get_sections {
1.508     raeburn  5284:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5285:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5286:     my @secs = ();
1.511     raeburn  5287:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5288:     unless ($response eq 'refused') {
1.901     albertel 5289:         @secs = split(/:/,$response);
1.506     raeburn  5290:     }
                   5291:     return @secs;
                   5292: }
1.776     albertel 5293: 
1.506     raeburn  5294: sub auto_new_course {
1.508     raeburn  5295:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5296:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5297:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5298:     return $response;
                   5299: }
1.776     albertel 5300: 
1.506     raeburn  5301: sub auto_validate_courseID {
1.508     raeburn  5302:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5303:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5304:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5305:     return $response;
                   5306: }
1.776     albertel 5307: 
1.506     raeburn  5308: sub auto_create_password {
1.873     raeburn  5309:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5310:     my ($homeserver,$response);
1.506     raeburn  5311:     my $create_passwd = 0;
                   5312:     my $authchk = '';
1.873     raeburn  5313:     if ($udom =~ /^$match_domain$/) {
                   5314:         $homeserver = &domain($udom,'primary');
                   5315:     }
                   5316:     if ($homeserver eq '') {
                   5317:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5318:             $homeserver = &homeserver($cnum,$cdom);
                   5319:         }
                   5320:     }
                   5321:     if ($homeserver eq '') {
                   5322:         $authchk = 'nodomain';
1.506     raeburn  5323:     } else {
1.873     raeburn  5324:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5325:         if ($response eq 'refused') {
                   5326:             $authchk = 'refused';
                   5327:         } else {
1.901     albertel 5328:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5329:         }
1.506     raeburn  5330:     }
                   5331:     return ($authparam,$create_passwd,$authchk);
                   5332: }
                   5333: 
1.706     raeburn  5334: sub auto_photo_permission {
                   5335:     my ($cnum,$cdom,$students) = @_;
                   5336:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5337:     my ($outcome,$perm_reqd,$conditions) = 
                   5338: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5339:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5340: 	return (undef,undef);
                   5341:     }
1.706     raeburn  5342:     return ($outcome,$perm_reqd,$conditions);
                   5343: }
                   5344: 
                   5345: sub auto_checkphotos {
                   5346:     my ($uname,$udom,$pid) = @_;
                   5347:     my $homeserver = &homeserver($uname,$udom);
                   5348:     my ($result,$resulttype);
                   5349:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5350: 				   &escape($uname).':'.&escape($pid),
                   5351: 				   $homeserver));
1.709     albertel 5352:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5353: 	return (undef,undef);
                   5354:     }
1.706     raeburn  5355:     if ($outcome) {
                   5356:         ($result,$resulttype) = split(/:/,$outcome);
                   5357:     } 
                   5358:     return ($result,$resulttype);
                   5359: }
                   5360: 
                   5361: sub auto_photochoice {
                   5362:     my ($cnum,$cdom) = @_;
                   5363:     my $homeserver = &homeserver($cnum,$cdom);
                   5364:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5365: 						       &escape($cdom),
                   5366: 						       $homeserver)));
1.709     albertel 5367:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5368: 	return (undef,undef);
                   5369:     }
1.706     raeburn  5370:     return ($update,$comment);
                   5371: }
                   5372: 
                   5373: sub auto_photoupdate {
                   5374:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5375:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5376:     my $host=&hostname($homeserver);
1.706     raeburn  5377:     my $cmd = '';
                   5378:     my $maxtries = 1;
1.800     albertel 5379:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5380:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5381:     }
                   5382:     $cmd =~ s/%%$//;
                   5383:     $cmd = &escape($cmd);
                   5384:     my $query = 'institutionalphotos';
                   5385:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5386:     unless ($queryid=~/^\Q$host\E\_/) {
                   5387:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5388:         return 'error: '.$queryid;
                   5389:     }
                   5390:     my $reply = &get_query_reply($queryid);
                   5391:     my $tries = 1;
                   5392:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5393:         $reply = &get_query_reply($queryid);
                   5394:         $tries ++;
                   5395:     }
                   5396:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5397:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5398:     } else {
                   5399:         my @responses = split(/:/,$reply);
                   5400:         my $outcome = shift(@responses); 
                   5401:         foreach my $item (@responses) {
                   5402:             my ($key,$value) = split(/=/,$item);
                   5403:             $$photo{$key} = $value;
                   5404:         }
                   5405:         return $outcome;
                   5406:     }
                   5407:     return 'error';
                   5408: }
                   5409: 
1.521     raeburn  5410: sub auto_instcode_format {
1.793     albertel 5411:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5412: 	$cat_order) = @_;
1.521     raeburn  5413:     my $courses = '';
1.772     raeburn  5414:     my @homeservers;
1.521     raeburn  5415:     if ($caller eq 'global') {
1.841     albertel 5416: 	my %servers = &get_servers($codedom,'library');
                   5417: 	foreach my $tryserver (keys(%servers)) {
                   5418: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5419: 		push(@homeservers,$tryserver);
                   5420: 	    }
1.584     raeburn  5421:         }
1.521     raeburn  5422:     } else {
1.772     raeburn  5423:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5424:     }
1.793     albertel 5425:     foreach my $code (keys(%{$instcodes})) {
                   5426:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5427:     }
                   5428:     chop($courses);
1.772     raeburn  5429:     my $ok_response = 0;
                   5430:     my $response;
                   5431:     while (@homeservers > 0 && $ok_response == 0) {
                   5432:         my $server = shift(@homeservers); 
                   5433:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5434:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5435:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5436: 		split(/:/,$response);
1.772     raeburn  5437:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5438:             push(@{$codetitles},&str2array($codetitles_str));
                   5439:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5440:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5441:             $ok_response = 1;
                   5442:         }
                   5443:     }
                   5444:     if ($ok_response) {
1.521     raeburn  5445:         return 'ok';
1.772     raeburn  5446:     } else {
                   5447:         return $response;
1.521     raeburn  5448:     }
                   5449: }
                   5450: 
1.792     raeburn  5451: sub auto_instcode_defaults {
                   5452:     my ($domain,$returnhash,$code_order) = @_;
                   5453:     my @homeservers;
1.841     albertel 5454: 
                   5455:     my %servers = &get_servers($domain,'library');
                   5456:     foreach my $tryserver (keys(%servers)) {
                   5457: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5458: 	    push(@homeservers,$tryserver);
                   5459: 	}
1.792     raeburn  5460:     }
1.841     albertel 5461: 
1.792     raeburn  5462:     my $response;
1.841     albertel 5463:     foreach my $server (@homeservers) {
1.792     raeburn  5464:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5465:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5466: 	
                   5467: 	foreach my $pair (split(/\&/,$response)) {
                   5468: 	    my ($name,$value)=split(/\=/,$pair);
                   5469: 	    if ($name eq 'code_order') {
                   5470: 		@{$code_order} = split(/\&/,&unescape($value));
                   5471: 	    } else {
                   5472: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5473: 	    }
                   5474: 	}
                   5475: 	return 'ok';
1.792     raeburn  5476:     }
1.841     albertel 5477: 
                   5478:     return $response;
1.792     raeburn  5479: } 
                   5480: 
1.777     albertel 5481: sub auto_validate_class_sec {
1.918     raeburn  5482:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5483:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5484:     my $ownerlist;
                   5485:     if (ref($owners) eq 'ARRAY') {
                   5486:         $ownerlist = join(',',@{$owners});
                   5487:     } else {
                   5488:         $ownerlist = $owners;
                   5489:     }
1.773     raeburn  5490:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5491:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5492:     return $response;
                   5493: }
                   5494: 
1.679     raeburn  5495: # ------------------------------------------------------- Course Group routines
                   5496: 
                   5497: sub get_coursegroups {
1.809     raeburn  5498:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5499:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5500: }
                   5501: 
1.679     raeburn  5502: sub modify_coursegroup {
                   5503:     my ($cdom,$cnum,$groupsettings) = @_;
                   5504:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5505: }
                   5506: 
1.809     raeburn  5507: sub toggle_coursegroup_status {
                   5508:     my ($cdom,$cnum,$group,$action) = @_;
                   5509:     my ($from_namespace,$to_namespace);
                   5510:     if ($action eq 'delete') {
                   5511:         $from_namespace = 'coursegroups';
                   5512:         $to_namespace = 'deleted_groups';
                   5513:     } else {
                   5514:         $from_namespace = 'deleted_groups';
                   5515:         $to_namespace = 'coursegroups';
                   5516:     }
                   5517:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5518:     if (my $tmp = &error(%curr_group)) {
                   5519:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5520:         return ('read error',$tmp);
                   5521:     } else {
                   5522:         my %savedsettings = %curr_group; 
1.809     raeburn  5523:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5524:         my $deloutcome;
                   5525:         if ($result eq 'ok') {
1.809     raeburn  5526:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5527:         } else {
                   5528:             return ('write error',$result);
                   5529:         }
                   5530:         if ($deloutcome eq 'ok') {
                   5531:             return 'ok';
                   5532:         } else {
                   5533:             return ('delete error',$deloutcome);
                   5534:         }
                   5535:     }
                   5536: }
                   5537: 
1.679     raeburn  5538: sub modify_group_roles {
1.957     raeburn  5539:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5540:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5541:     my $role = 'gr/'.&escape($userprivs);
                   5542:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5543:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5544:     if ($result eq 'ok') {
                   5545:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5546:     }
1.679     raeburn  5547:     return $result;
                   5548: }
                   5549: 
                   5550: sub modify_coursegroup_membership {
                   5551:     my ($cdom,$cnum,$membership) = @_;
                   5552:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5553:     return $result;
                   5554: }
                   5555: 
1.682     raeburn  5556: sub get_active_groups {
                   5557:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5558:     my $now = time;
                   5559:     my %groups = ();
                   5560:     foreach my $key (keys(%env)) {
1.811     albertel 5561:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5562:             my ($start,$end) = split(/\./,$env{$key});
                   5563:             if (($end!=0) && ($end<$now)) { next; }
                   5564:             if (($start!=0) && ($start>$now)) { next; }
                   5565:             if ($1 eq $cdom && $2 eq $cnum) {
                   5566:                 $groups{$3} = $env{$key} ;
                   5567:             }
                   5568:         }
                   5569:     }
                   5570:     return %groups;
                   5571: }
                   5572: 
1.683     raeburn  5573: sub get_group_membership {
                   5574:     my ($cdom,$cnum,$group) = @_;
                   5575:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5576: }
                   5577: 
                   5578: sub get_users_groups {
                   5579:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5580:     my @usersgroups;
1.683     raeburn  5581:     my $cachetime=1800;
                   5582: 
                   5583:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5584:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5585:     if (defined($cached)) {
1.734     albertel 5586:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5587:     } else {  
                   5588:         $grouplist = '';
1.816     raeburn  5589:         my $courseurl = &courseid_to_courseurl($courseid);
                   5590:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5591:         my $access_end = $env{'course.'.$courseid.
                   5592:                               '.default_enrollment_end_date'};
                   5593:         my $now = time;
                   5594:         foreach my $key (keys(%roleshash)) {
                   5595:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5596:                 my $group = $1;
                   5597:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5598:                     my $start = $2;
                   5599:                     my $end = $1;
                   5600:                     if ($start == -1) { next; } # deleted from group
                   5601:                     if (($start!=0) && ($start>$now)) { next; }
                   5602:                     if (($end!=0) && ($end<$now)) {
                   5603:                         if ($access_end && $access_end < $now) {
                   5604:                             if ($access_end - $end < 86400) {
                   5605:                                 push(@usersgroups,$group);
1.733     raeburn  5606:                             }
                   5607:                         }
1.817     raeburn  5608:                         next;
1.733     raeburn  5609:                     }
1.817     raeburn  5610:                     push(@usersgroups,$group);
1.683     raeburn  5611:                 }
                   5612:             }
                   5613:         }
1.817     raeburn  5614:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5615:         $grouplist = join(':',@usersgroups);
                   5616:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5617:     }
1.733     raeburn  5618:     return @usersgroups;
1.683     raeburn  5619: }
                   5620: 
                   5621: sub devalidate_getgroups_cache {
                   5622:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5623:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5624: 
1.683     raeburn  5625:     my $hashid="$udom:$uname:$courseid";
                   5626:     &devalidate_cache_new('getgroups',$hashid);
                   5627: }
                   5628: 
1.12      www      5629: # ------------------------------------------------------------------ Plain Text
                   5630: 
                   5631: sub plaintext {
1.742     raeburn  5632:     my ($short,$type,$cid) = @_;
1.758     albertel 5633:     if ($short =~ /^cr/) {
                   5634: 	return (split('/',$short))[-1];
                   5635:     }
1.742     raeburn  5636:     if (!defined($cid)) {
                   5637:         $cid = $env{'request.course.id'};
                   5638:     }
                   5639:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5640:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5641:                                           '.plaintext'});
                   5642:     }
                   5643:     my %rolenames = (
                   5644:                       Course => 'std',
                   5645:                       Group => 'alt1',
                   5646:                     );
                   5647:     if (defined($type) && 
                   5648:          defined($rolenames{$type}) && 
                   5649:          defined($prp{$short}{$rolenames{$type}})) {
                   5650:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5651:     } else {
                   5652:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5653:     }
1.12      www      5654: }
                   5655: 
                   5656: # ----------------------------------------------------------------- Assign Role
                   5657: 
                   5658: sub assignrole {
1.957     raeburn  5659:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5660:         $context)=@_;
1.21      www      5661:     my $mrole;
                   5662:     if ($role =~ /^cr\//) {
1.393     www      5663:         my $cwosec=$url;
1.811     albertel 5664:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5665: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5666:            &logthis('Refused custom assignrole: '.
                   5667:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5668: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5669:            return 'refused'; 
                   5670:         }
1.21      www      5671:         $mrole='cr';
1.678     raeburn  5672:     } elsif ($role =~ /^gr\//) {
                   5673:         my $cwogrp=$url;
1.811     albertel 5674:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5675:         unless (&allowed('mdg',$cwogrp)) {
                   5676:             &logthis('Refused group assignrole: '.
                   5677:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5678:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5679:             return 'refused';
                   5680:         }
                   5681:         $mrole='gr';
1.21      www      5682:     } else {
1.82      www      5683:         my $cwosec=$url;
1.811     albertel 5684:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5685:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5686:             my $refused;
                   5687:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5688:                 if (!(&allowed('c'.$role,$url))) {
                   5689:                     $refused = 1;
                   5690:                 }
                   5691:             } else {
                   5692:                 $refused = 1;
                   5693:             }
1.947     raeburn  5694:             if ($refused) {
                   5695:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5696:                     $refused = '';
                   5697:                 } else {
                   5698:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5699:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5700: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5701:                     return 'refused';
                   5702:                 }
1.932     raeburn  5703:             }
1.104     www      5704:         }
1.21      www      5705:         $mrole=$role;
                   5706:     }
1.620     albertel 5707:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5708:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5709:     if ($end) { $command.='_'.$end; }
1.21      www      5710:     if ($start) {
                   5711: 	if ($end) { 
1.81      www      5712:            $command.='_'.$start; 
1.21      www      5713:         } else {
1.81      www      5714:            $command.='_0_'.$start;
1.21      www      5715:         }
                   5716:     }
1.739     raeburn  5717:     my $origstart = $start;
                   5718:     my $origend = $end;
1.957     raeburn  5719:     my $delflag;
1.357     www      5720: # actually delete
                   5721:     if ($deleteflag) {
1.373     www      5722: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5723: # modify command to delete the role
1.620     albertel 5724:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5725:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5726: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5727: # set start and finish to negative values for userrolelog
                   5728:            $start=-1;
                   5729:            $end=-1;
1.957     raeburn  5730:            $delflag = 1;
1.357     www      5731:         }
                   5732:     }
                   5733: # send command
1.349     www      5734:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5735: # log new user role if status is ok
1.349     www      5736:     if ($answer eq 'ok') {
1.663     raeburn  5737: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5738: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5739:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5740:         unless ($role =~ /^gr/) {
                   5741:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5742:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5743:         }
1.349     www      5744:     }
                   5745:     return $answer;
1.169     harris41 5746: }
                   5747: 
                   5748: # -------------------------------------------------- Modify user authentication
1.197     www      5749: # Overrides without validation
                   5750: 
1.169     harris41 5751: sub modifyuserauth {
                   5752:     my ($udom,$uname,$umode,$upass)=@_;
                   5753:     my $uhome=&homeserver($uname,$udom);
1.197     www      5754:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5755:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5756:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5757:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5758:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5759: 		     &escape($upass),$uhome);
1.620     albertel 5760:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5761:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5762:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5763:     &log($udom,,$uname,$uhome,
1.620     albertel 5764:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5765:                                      $env{'user.name'}.', '.$umode.
1.197     www      5766:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5767:     unless ($reply eq 'ok') {
1.197     www      5768:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5769: 	return 'error: '.$reply;
                   5770:     }   
1.170     harris41 5771:     return 'ok';
1.80      www      5772: }
                   5773: 
1.81      www      5774: # --------------------------------------------------------------- Modify a user
1.80      www      5775: 
1.81      www      5776: sub modifyuser {
1.206     matthew  5777:     my ($udom,    $uname, $uid,
                   5778:         $umode,   $upass, $first,
                   5779:         $middle,  $last,  $gene,
1.963     raeburn  5780:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5781:     $udom= &LONCAPA::clean_domain($udom);
                   5782:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5783:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5784:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5785: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5786:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5787:                                      ' desiredhome not specified'). 
1.620     albertel 5788:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5789:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5790:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5791: # ----------------------------------------------------------------- Create User
1.406     albertel 5792:     if (($uhome eq 'no_host') && 
                   5793: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5794:         my $unhome='';
1.844     albertel 5795:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5796:             $unhome = $desiredhome;
1.620     albertel 5797: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5798: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5799:         } else { # load balancing routine for determining $unhome
1.81      www      5800:             my $loadm=10000000;
1.841     albertel 5801: 	    my %servers = &get_servers($udom,'library');
                   5802: 	    foreach my $tryserver (keys(%servers)) {
                   5803: 		my $answer=reply('load',$tryserver);
                   5804: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5805: 		    $loadm=$answer;
                   5806: 		    $unhome=$tryserver;
                   5807: 		}
1.80      www      5808: 	    }
                   5809:         }
                   5810:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5811: 	    return 'error: unable to find a home server for '.$uname.
                   5812:                    ' in domain '.$udom;
1.80      www      5813:         }
                   5814:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5815:                          &escape($upass),$unhome);
                   5816: 	unless ($reply eq 'ok') {
                   5817:             return 'error: '.$reply;
                   5818:         }   
1.230     stredwic 5819:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5820:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5821: 	    return 'error: unable verify users home machine.';
1.80      www      5822:         }
1.209     matthew  5823:     }   # End of creation of new user
1.80      www      5824: # ---------------------------------------------------------------------- Add ID
                   5825:     if ($uid) {
                   5826:        $uid=~tr/A-Z/a-z/;
                   5827:        my %uidhash=&idrget($udom,$uname);
1.196     www      5828:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5829:          && (!$forceid)) {
1.80      www      5830: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5831: 	      return 'error: user id "'.$uid.'" does not match '.
                   5832:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5833:           }
                   5834:        } else {
                   5835: 	  &idput($udom,($uname => $uid));
                   5836:        }
                   5837:     }
                   5838: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5839:     my @tmp=&get('environment',
1.899     raeburn  5840: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5841:                     'permanentemail','inststatus'],
1.134     albertel 5842: 		   $udom,$uname);
1.313     matthew  5843:     my %names;
                   5844:     if ($tmp[0] =~ m/^error:.*/) { 
                   5845:         %names=(); 
                   5846:     } else {
                   5847:         %names = @tmp;
                   5848:     }
1.388     www      5849: #
                   5850: # Make sure to not trash student environment if instructor does not bother
                   5851: # to supply name and email information
                   5852: #
                   5853:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5854:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5855:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5856:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5857:     if ($email) {
                   5858:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5859:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5860:     }
1.899     raeburn  5861:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5862:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5863:     my $reply = &put('environment', \%names, $udom,$uname);
                   5864:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5865:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5866:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5867:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5868:                  $umode.', '.$first.', '.$middle.', '.
                   5869: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5870:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5871:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5872:     } else {
                   5873:         $logmsg .= ' during self creation';
                   5874:     }
                   5875:     &logthis($logmsg);
1.134     albertel 5876:     return 'ok';
1.80      www      5877: }
                   5878: 
1.81      www      5879: # -------------------------------------------------------------- Modify student
1.80      www      5880: 
1.81      www      5881: sub modifystudent {
                   5882:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5883:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5884:         $selfenroll,$context)=@_;
1.455     albertel 5885:     if (!$cid) {
1.620     albertel 5886: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5887: 	    return 'not_in_class';
                   5888: 	}
1.80      www      5889:     }
                   5890: # --------------------------------------------------------------- Make the user
1.81      www      5891:     my $reply=&modifyuser
1.209     matthew  5892: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5893:          $desiredhome,$email);
1.80      www      5894:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5895:     # This will cause &modify_student_enrollment to get the uid from the
                   5896:     # students environment
                   5897:     $uid = undef if (!$forceid);
1.455     albertel 5898:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5899: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5900:     return $reply;
                   5901: }
                   5902: 
                   5903: sub modify_student_enrollment {
1.957     raeburn  5904:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5905:     my ($cdom,$cnum,$chome);
                   5906:     if (!$cid) {
1.620     albertel 5907: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5908: 	    return 'not_in_class';
                   5909: 	}
1.620     albertel 5910: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5911: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5912:     } else {
                   5913: 	($cdom,$cnum)=split(/_/,$cid);
                   5914:     }
1.620     albertel 5915:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5916:     if (!$chome) {
1.457     raeburn  5917: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5918:     }
1.455     albertel 5919:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5920:     # Make sure the user exists
1.81      www      5921:     my $uhome=&homeserver($uname,$udom);
                   5922:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5923: 	return 'error: no such user';
                   5924:     }
1.297     matthew  5925:     # Get student data if we were not given enough information
                   5926:     if (!defined($first)  || $first  eq '' || 
                   5927:         !defined($last)   || $last   eq '' || 
                   5928:         !defined($uid)    || $uid    eq '' || 
                   5929:         !defined($middle) || $middle eq '' || 
                   5930:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5931:         # They did not supply us with enough data to enroll the student, so
                   5932:         # we need to pick up more information.
1.297     matthew  5933:         my %tmp = &get('environment',
1.294     matthew  5934:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5935:                        ,$udom,$uname);
                   5936: 
1.800     albertel 5937:         #foreach my $key (keys(%tmp)) {
                   5938:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5939:         #}
1.294     matthew  5940:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5941:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5942:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5943:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5944:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5945:     }
1.556     albertel 5946:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5947:     my $reply=cput('classlist',
                   5948: 		   {"$uname:$udom" => 
1.515     raeburn  5949: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5950: 		   $cdom,$cnum);
1.81      www      5951:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5952: 	return 'error: '.$reply;
1.652     albertel 5953:     } else {
                   5954: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5955:     }
1.297     matthew  5956:     # Add student role to user
1.83      www      5957:     my $uurl='/'.$cid;
1.81      www      5958:     $uurl=~s/\_/\//g;
                   5959:     if ($usec) {
                   5960: 	$uurl.='/'.$usec;
                   5961:     }
1.957     raeburn  5962:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5963: }
                   5964: 
1.556     albertel 5965: sub format_name {
                   5966:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5967:     my $name;
                   5968:     if ($first ne 'lastname') {
                   5969: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5970:     } else {
                   5971: 	if ($lastname=~/\S/) {
                   5972: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5973: 	    $name=~s/\s+,/,/;
                   5974: 	} else {
                   5975: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5976: 	}
                   5977:     }
                   5978:     $name=~s/^\s+//;
                   5979:     $name=~s/\s+$//;
                   5980:     $name=~s/\s+/ /g;
                   5981:     return $name;
                   5982: }
                   5983: 
1.84      www      5984: # ------------------------------------------------- Write to course preferences
                   5985: 
                   5986: sub writecoursepref {
                   5987:     my ($courseid,%prefs)=@_;
                   5988:     $courseid=~s/^\///;
                   5989:     $courseid=~s/\_/\//g;
                   5990:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5991:     my $chome=homeserver($cnum,$cdomain);
                   5992:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5993: 	return 'error: no such course';
                   5994:     }
                   5995:     my $cstring='';
1.800     albertel 5996:     foreach my $pref (keys(%prefs)) {
                   5997: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5998:     }
1.84      www      5999:     $cstring=~s/\&$//;
                   6000:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6001: }
                   6002: 
                   6003: # ---------------------------------------------------------- Make/modify course
                   6004: 
                   6005: sub createcourse {
1.741     raeburn  6006:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6007:         $course_owner,$crstype)=@_;
1.84      www      6008:     $url=&declutter($url);
                   6009:     my $cid='';
1.264     matthew  6010:     unless (&allowed('ccc',$udom)) {
1.84      www      6011:         return 'refused';
                   6012:     }
                   6013: # ------------------------------------------------------------------- Create ID
1.674     www      6014:    my $uname=int(1+rand(9)).
                   6015:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6016:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6017:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6018: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6019:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6020:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6021:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6022:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6023:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6024:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6025:            return 'error: unable to generate unique course-ID';
                   6026:        } 
                   6027:    }
1.264     matthew  6028: # ------------------------------------------------ Check supplied server name
1.620     albertel 6029:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6030:     if (! &is_library($course_server)) {
1.264     matthew  6031:         return 'error:bad server name '.$course_server;
                   6032:     }
1.84      www      6033: # ------------------------------------------------------------- Make the course
                   6034:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6035:                       $course_server);
1.84      www      6036:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6037:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6038:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6039: 	return 'error: no such course';
                   6040:     }
1.271     www      6041: # ----------------------------------------------------------------- Course made
1.516     raeburn  6042: # log existence
1.918     raeburn  6043:     my $newcourse = {
                   6044:                     $udom.'_'.$uname => {
1.921     raeburn  6045:                                      description => $description,
                   6046:                                      inst_code   => $inst_code,
                   6047:                                      owner       => $course_owner,
                   6048:                                      type        => $crstype,
1.918     raeburn  6049:                                                 },
                   6050:                     };
1.921     raeburn  6051:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6052: # set toplevel url
1.271     www      6053:     my $topurl=$url;
                   6054:     unless ($nonstandard) {
                   6055: # ------------------------------------------ For standard courses, make top url
                   6056:         my $mapurl=&clutter($url);
1.278     www      6057:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6058:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6059: <map>
                   6060: <resource id="1" type="start"></resource>
                   6061: <resource id="2" src="$mapurl"></resource>
                   6062: <resource id="3" type="finish"></resource>
                   6063: <link index="1" from="1" to="2"></link>
                   6064: <link index="2" from="2" to="3"></link>
                   6065: </map>
                   6066: ENDINITMAP
                   6067:         $topurl=&declutter(
1.638     albertel 6068:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6069:                           );
                   6070:     }
                   6071: # ----------------------------------------------------------- Write preferences
1.84      www      6072:     &writecoursepref($udom.'_'.$uname,
                   6073:                      ('description' => $description,
1.271     www      6074:                       'url'         => $topurl));
1.84      www      6075:     return '/'.$udom.'/'.$uname;
                   6076: }
                   6077: 
1.813     albertel 6078: sub is_course {
                   6079:     my ($cdom,$cnum) = @_;
                   6080:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6081: 				undef,'.');
1.813     albertel 6082:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6083:         return 1;
                   6084:     }
                   6085:     return 0;
                   6086: }
                   6087: 
1.21      www      6088: # ---------------------------------------------------------- Assign Custom Role
                   6089: 
                   6090: sub assigncustomrole {
1.957     raeburn  6091:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6092:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6093:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6094: }
                   6095: 
                   6096: # ----------------------------------------------------------------- Revoke Role
                   6097: 
                   6098: sub revokerole {
1.957     raeburn  6099:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6100:     my $now=time;
1.965     raeburn  6101:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6102: }
                   6103: 
                   6104: # ---------------------------------------------------------- Revoke Custom Role
                   6105: 
                   6106: sub revokecustomrole {
1.957     raeburn  6107:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6108:     my $now=time;
1.357     www      6109:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6110:            $deleteflag,$selfenroll,$context);
1.17      www      6111: }
                   6112: 
1.533     banghart 6113: # ------------------------------------------------------------ Disk usage
1.535     albertel 6114: sub diskusage {
1.955     raeburn  6115:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6116:     $directorypath =~ s/\/$//;
                   6117:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6118:                        .&escape($getpropath).':'.&escape($uname).':'
                   6119:                        .&escape($udom),homeserver($uname,$udom));
                   6120:     if ($listing eq 'unknown_cmd') {
                   6121:         if ($getpropath) {
                   6122:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6123:         }
                   6124:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6125:     }
1.514     albertel 6126:     return $listing;
1.512     banghart 6127: }
                   6128: 
1.566     banghart 6129: sub is_locked {
                   6130:     my ($file_name, $domain, $user) = @_;
                   6131:     my @check;
                   6132:     my $is_locked;
                   6133:     push @check, $file_name;
1.613     albertel 6134:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6135: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6136:     my ($tmp)=keys(%locked);
                   6137:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6138:     
1.566     banghart 6139:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6140:         $is_locked = 'false';
                   6141:         foreach my $entry (@{$locked{$file_name}}) {
                   6142:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6143:                $is_locked = 'true';
                   6144:                last;
1.745     raeburn  6145:            }
                   6146:        }
1.566     banghart 6147:     } else {
                   6148:         $is_locked = 'false';
                   6149:     }
                   6150: }
                   6151: 
1.759     albertel 6152: sub declutter_portfile {
                   6153:     my ($file) = @_;
1.833     albertel 6154:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6155:     return $file;
                   6156: }
                   6157: 
1.559     banghart 6158: # ------------------------------------------------------------- Mark as Read Only
                   6159: 
                   6160: sub mark_as_readonly {
                   6161:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6162:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6163:     my ($tmp)=keys(%current_permissions);
                   6164:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6165:     foreach my $file (@{$files}) {
1.759     albertel 6166: 	$file = &declutter_portfile($file);
1.561     banghart 6167:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6168:     }
1.613     albertel 6169:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6170:     return;
                   6171: }
                   6172: 
1.572     banghart 6173: # ------------------------------------------------------------Save Selected Files
                   6174: 
                   6175: sub save_selected_files {
                   6176:     my ($user, $path, @files) = @_;
                   6177:     my $filename = $user."savedfiles";
1.573     banghart 6178:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6179:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6180:     foreach my $file (@files) {
1.620     albertel 6181:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6182:     }
                   6183:     foreach my $file (@other_files) {
1.574     banghart 6184:         print (OUT $file."\n");
1.572     banghart 6185:     }
1.574     banghart 6186:     close (OUT);
1.572     banghart 6187:     return 'ok';
                   6188: }
                   6189: 
1.574     banghart 6190: sub clear_selected_files {
                   6191:     my ($user) = @_;
                   6192:     my $filename = $user."savedfiles";
                   6193:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6194:     print (OUT undef);
                   6195:     close (OUT);
                   6196:     return ("ok");    
                   6197: }
                   6198: 
1.572     banghart 6199: sub files_in_path {
                   6200:     my ($user, $path) = @_;
                   6201:     my $filename = $user."savedfiles";
                   6202:     my %return_files;
1.574     banghart 6203:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6204:     while (my $line_in = <IN>) {
1.574     banghart 6205:         chomp ($line_in);
                   6206:         my @paths_and_file = split (m!/!, $line_in);
                   6207:         my $file_part = pop (@paths_and_file);
                   6208:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6209:         $path_part.='/';
                   6210:         my $path_and_file = $path_part.$file_part;
                   6211:         if ($path_part eq $path) {
                   6212:             $return_files{$file_part}= 'selected';
                   6213:         }
                   6214:     }
1.574     banghart 6215:     close (IN);
                   6216:     return (\%return_files);
1.572     banghart 6217: }
                   6218: 
                   6219: # called in portfolio select mode, to show files selected NOT in current directory
                   6220: sub files_not_in_path {
                   6221:     my ($user, $path) = @_;
                   6222:     my $filename = $user."savedfiles";
                   6223:     my @return_files;
                   6224:     my $path_part;
1.800     albertel 6225:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6226:     while (my $line = <IN>) {
1.572     banghart 6227:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6228:         my @paths_and_file = split(m|/|, $line);
                   6229:         my $file_part = pop(@paths_and_file);
                   6230:         chomp($file_part);
                   6231:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6232:         $path_part .= '/';
                   6233:         my $path_and_file = $path_part.$file_part;
                   6234:         if ($path_part ne $path) {
1.800     albertel 6235:             push(@return_files, ($path_and_file));
1.572     banghart 6236:         }
                   6237:     }
1.800     albertel 6238:     close(OUT);
1.574     banghart 6239:     return (@return_files);
1.572     banghart 6240: }
                   6241: 
1.745     raeburn  6242: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6243: 
1.745     raeburn  6244: sub get_portfile_permissions {
                   6245:     my ($domain,$user) = @_;
1.613     albertel 6246:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6247:     my ($tmp)=keys(%current_permissions);
                   6248:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6249:     return \%current_permissions;
                   6250: }
                   6251: 
                   6252: #---------------------------------------------Get portfolio file access controls
                   6253: 
1.749     raeburn  6254: sub get_access_controls {
1.745     raeburn  6255:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6256:     my %access;
                   6257:     my $real_file = $file;
                   6258:     $file =~ s/\.meta$//;
1.745     raeburn  6259:     if (defined($file)) {
1.749     raeburn  6260:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6261:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6262:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6263:             }
                   6264:         }
1.745     raeburn  6265:     } else {
1.749     raeburn  6266:         foreach my $key (keys(%{$current_permissions})) {
                   6267:             if ($key =~ /\0accesscontrol$/) {
                   6268:                 if (defined($group)) {
                   6269:                     if ($key !~ m-^\Q$group\E/-) {
                   6270:                         next;
                   6271:                     }
                   6272:                 }
                   6273:                 my ($fullpath) = split(/\0/,$key);
                   6274:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6275:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6276:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6277:                     }
                   6278:                 }
                   6279:             }
                   6280:         }
                   6281:     }
                   6282:     return %access;
                   6283: }
                   6284: 
                   6285: sub modify_access_controls {
                   6286:     my ($file_name,$changes,$domain,$user)=@_;
                   6287:     my ($outcome,$deloutcome);
                   6288:     my %store_permissions;
                   6289:     my %new_values;
                   6290:     my %new_control;
                   6291:     my %translation;
                   6292:     my @deletions = ();
                   6293:     my $now = time;
                   6294:     if (exists($$changes{'activate'})) {
                   6295:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6296:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6297:             my $numnew = scalar(@newitems);
                   6298:             for (my $i=0; $i<$numnew; $i++) {
                   6299:                 my $newkey = $newitems[$i];
                   6300:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6301:                 if ($newkey =~ /^\d+:/) { 
                   6302:                     $newkey =~ s/^(\d+)/$newid/;
                   6303:                     $translation{$1} = $newid;
                   6304:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6305:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6306:                     $translation{$1} = $newid;
                   6307:                 }
1.749     raeburn  6308:                 $new_values{$file_name."\0".$newkey} = 
                   6309:                                           $$changes{'activate'}{$newitems[$i]};
                   6310:                 $new_control{$newkey} = $now;
                   6311:             }
                   6312:         }
                   6313:     }
                   6314:     my %todelete;
                   6315:     my %changed_items;
                   6316:     foreach my $action ('delete','update') {
                   6317:         if (exists($$changes{$action})) {
                   6318:             if (ref($$changes{$action}) eq 'HASH') {
                   6319:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6320:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6321:                     if ($action eq 'delete') { 
                   6322:                         $todelete{$itemnum} = 1;
                   6323:                     } else {
                   6324:                         $changed_items{$itemnum} = $key;
                   6325:                     }
                   6326:                 }
1.745     raeburn  6327:             }
                   6328:         }
1.749     raeburn  6329:     }
                   6330:     # get lock on access controls for file.
                   6331:     my $lockhash = {
                   6332:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6333:                                                        ':'.$env{'user.domain'},
                   6334:                    }; 
                   6335:     my $tries = 0;
                   6336:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6337:    
                   6338:     while (($gotlock ne 'ok') && $tries <3) {
                   6339:         $tries ++;
                   6340:         sleep 1;
                   6341:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6342:     }
                   6343:     if ($gotlock eq 'ok') {
                   6344:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6345:         my ($tmp)=keys(%curr_permissions);
                   6346:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6347:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6348:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6349:             if (ref($curr_controls) eq 'HASH') {
                   6350:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6351:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6352:                     if (defined($todelete{$itemnum})) {
                   6353:                         push(@deletions,$file_name."\0".$control_item);
                   6354:                     } else {
                   6355:                         if (defined($changed_items{$itemnum})) {
                   6356:                             $new_control{$changed_items{$itemnum}} = $now;
                   6357:                             push(@deletions,$file_name."\0".$control_item);
                   6358:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6359:                         } else {
                   6360:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6361:                         }
                   6362:                     }
1.745     raeburn  6363:                 }
                   6364:             }
                   6365:         }
1.970     raeburn  6366:         my ($group);
                   6367:         if (&is_course($domain,$user)) {
                   6368:             ($group,my $file) = split(/\//,$file_name,2);
                   6369:         }
1.749     raeburn  6370:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6371:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6372:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6373:         #  remove lock
                   6374:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6375:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6376:         my $sqlresult =
1.970     raeburn  6377:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6378:                                     $group);
1.749     raeburn  6379:     } else {
                   6380:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6381:     }
1.749     raeburn  6382:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6383: }
                   6384: 
1.827     raeburn  6385: sub make_public_indefinitely {
                   6386:     my ($requrl) = @_;
                   6387:     my $now = time;
                   6388:     my $action = 'activate';
                   6389:     my $aclnum = 0;
                   6390:     if (&is_portfolio_url($requrl)) {
                   6391:         my (undef,$udom,$unum,$file_name,$group) =
                   6392:             &parse_portfolio_url($requrl);
                   6393:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6394:         my %access_controls = &get_access_controls($current_perms,
                   6395:                                                    $group,$file_name);
                   6396:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6397:             my ($num,$scope,$end,$start) = 
                   6398:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6399:             if ($scope eq 'public') {
                   6400:                 if ($start <= $now && $end == 0) {
                   6401:                     $action = 'none';
                   6402:                 } else {
                   6403:                     $action = 'update';
                   6404:                     $aclnum = $num;
                   6405:                 }
                   6406:                 last;
                   6407:             }
                   6408:         }
                   6409:         if ($action eq 'none') {
                   6410:              return 'ok';
                   6411:         } else {
                   6412:             my %changes;
                   6413:             my $newend = 0;
                   6414:             my $newstart = $now;
                   6415:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6416:             $changes{$action}{$newkey} = {
                   6417:                 type => 'public',
                   6418:                 time => {
                   6419:                     start => $newstart,
                   6420:                     end   => $newend,
                   6421:                 },
                   6422:             };
                   6423:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6424:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6425:             return $outcome;
                   6426:         }
                   6427:     } else {
                   6428:         return 'invalid';
                   6429:     }
                   6430: }
                   6431: 
1.745     raeburn  6432: #------------------------------------------------------Get Marked as Read Only
                   6433: 
                   6434: sub get_marked_as_readonly {
                   6435:     my ($domain,$user,$what,$group) = @_;
                   6436:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6437:     my @readonly_files;
1.629     banghart 6438:     my $cmp1=$what;
                   6439:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6440:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6441:         if (defined($group)) {
                   6442:             if ($file_name !~ m-^\Q$group\E/-) {
                   6443:                 next;
                   6444:             }
                   6445:         }
1.561     banghart 6446:         if (ref($value) eq "ARRAY"){
                   6447:             foreach my $stored_what (@{$value}) {
1.629     banghart 6448:                 my $cmp2=$stored_what;
1.759     albertel 6449:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6450:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6451:                 }
1.629     banghart 6452:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6453:                     push(@readonly_files, $file_name);
1.745     raeburn  6454:                     last;
1.563     banghart 6455:                 } elsif (!defined($what)) {
                   6456:                     push(@readonly_files, $file_name);
1.745     raeburn  6457:                     last;
1.561     banghart 6458:                 }
                   6459:             }
1.745     raeburn  6460:         }
1.561     banghart 6461:     }
                   6462:     return @readonly_files;
                   6463: }
1.577     banghart 6464: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6465: 
1.577     banghart 6466: sub get_marked_as_readonly_hash {
1.745     raeburn  6467:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6468:     my %readonly_files;
1.745     raeburn  6469:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6470:         if (defined($group)) {
                   6471:             if ($file_name !~ m-^\Q$group\E/-) {
                   6472:                 next;
                   6473:             }
                   6474:         }
1.577     banghart 6475:         if (ref($value) eq "ARRAY"){
                   6476:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6477:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6478:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6479:                         if ($lock_descriptor eq 'graded') {
                   6480:                             $readonly_files{$file_name} = 'graded';
                   6481:                         } elsif ($lock_descriptor eq 'handback') {
                   6482:                             $readonly_files{$file_name} = 'handback';
                   6483:                         } else {
                   6484:                             if (!exists($readonly_files{$file_name})) {
                   6485:                                 $readonly_files{$file_name} = 'locked';
                   6486:                             }
                   6487:                         }
1.745     raeburn  6488:                     }
1.750     banghart 6489:                 } 
1.577     banghart 6490:             }
                   6491:         } 
                   6492:     }
                   6493:     return %readonly_files;
                   6494: }
1.559     banghart 6495: # ------------------------------------------------------------ Unmark as Read Only
                   6496: 
                   6497: sub unmark_as_readonly {
1.629     banghart 6498:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6499:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6500:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6501:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6502:     my $symb_crs = $what;
                   6503:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6504:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6505:     my ($tmp)=keys(%current_permissions);
                   6506:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6507:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6508:     foreach my $file (@readonly_files) {
1.759     albertel 6509: 	my $clean_file = &declutter_portfile($file);
                   6510: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6511: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6512:         my @new_locks;
                   6513:         my @del_keys;
                   6514:         if (ref($current_locks) eq "ARRAY"){
                   6515:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6516:                 my $compare=$locker;
1.749     raeburn  6517:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6518:                     $compare=join('',@{$locker});
1.746     raeburn  6519:                     if ($compare ne $symb_crs) {
                   6520:                         push(@new_locks, $locker);
                   6521:                     }
1.563     banghart 6522:                 }
                   6523:             }
1.650     albertel 6524:             if (scalar(@new_locks) > 0) {
1.563     banghart 6525:                 $current_permissions{$file} = \@new_locks;
                   6526:             } else {
                   6527:                 push(@del_keys, $file);
1.613     albertel 6528:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6529:                 delete($current_permissions{$file});
1.563     banghart 6530:             }
                   6531:         }
1.561     banghart 6532:     }
1.613     albertel 6533:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6534:     return;
                   6535: }
1.512     banghart 6536: 
1.17      www      6537: # ------------------------------------------------------------ Directory lister
                   6538: 
                   6539: sub dirlist {
1.955     raeburn  6540:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6541:     $uri=~s/^\///;
                   6542:     $uri=~s/\/$//;
1.253     stredwic 6543:     my ($udom, $uname);
1.955     raeburn  6544:     if ($getuserdir) {
1.253     stredwic 6545:         $udom = $userdomain;
                   6546:         $uname = $username;
1.955     raeburn  6547:     } else {
                   6548:         (undef,$udom,$uname)=split(/\//,$uri);
                   6549:         if(defined($userdomain)) {
                   6550:             $udom = $userdomain;
                   6551:         }
                   6552:         if(defined($username)) {
                   6553:             $uname = $username;
                   6554:         }
1.253     stredwic 6555:     }
1.955     raeburn  6556:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6557: 
1.955     raeburn  6558:     $dirRoot = $perlvar{'lonDocRoot'};
                   6559:     if (defined($getpropath)) {
                   6560:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6561:         $dirRoot =~ s/\/$//;
1.955     raeburn  6562:     } elsif (defined($getuserdir)) {
                   6563:         my $subdir=$uname.'__';
                   6564:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6565:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6566:                    ."/$udom/$subdir/$uname";
                   6567:     } elsif (defined($alternateRoot)) {
                   6568:         $dirRoot = $alternateRoot;
1.751     banghart 6569:     }
1.253     stredwic 6570: 
                   6571:     if($udom) {
                   6572:         if($uname) {
1.955     raeburn  6573:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6574:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6575:                               .':'.&escape($uname).':'.&escape($udom),
                   6576:                               &homeserver($uname,$udom));
                   6577:             if ($listing eq 'unknown_cmd') {
                   6578:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6579:                                   &homeserver($uname,$udom));
                   6580:             } else {
                   6581:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6582:             }
1.605     matthew  6583:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6584:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6585: 				  &homeserver($uname,$udom));
1.605     matthew  6586:                 @listing_results = split(/:/,$listing);
                   6587:             } else {
                   6588:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6589:             }
                   6590:             return @listing_results;
1.955     raeburn  6591:         } elsif(!$alternateRoot) {
1.800     albertel 6592:             my %allusers;
1.841     albertel 6593: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6594:  	    foreach my $tryserver (keys(%servers)) {
                   6595:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6596:                                   &escape($udom),$tryserver);
                   6597:                 if ($listing eq 'unknown_cmd') {
                   6598: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6599: 				      $udom, $tryserver);
                   6600:                 } else {
                   6601:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6602:                 }
1.841     albertel 6603: 		if ($listing eq 'unknown_cmd') {
                   6604: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6605: 				      $udom, $tryserver);
                   6606: 		    @listing_results = split(/:/,$listing);
                   6607: 		} else {
                   6608: 		    @listing_results =
                   6609: 			map { &unescape($_); } split(/:/,$listing);
                   6610: 		}
                   6611: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6612: 		    $listing_results[0] ne 'empty'       &&
                   6613: 		    $listing_results[0] ne 'con_lost') {
                   6614: 		    foreach my $line (@listing_results) {
                   6615: 			my ($entry) = split(/&/,$line,2);
                   6616: 			$allusers{$entry} = 1;
                   6617: 		    }
                   6618: 		}
1.253     stredwic 6619:             }
                   6620:             my $alluserstr='';
1.800     albertel 6621:             foreach my $user (sort(keys(%allusers))) {
                   6622:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6623:             }
                   6624:             $alluserstr=~s/:$//;
                   6625:             return split(/:/,$alluserstr);
                   6626:         } else {
1.800     albertel 6627:             return ('missing user name');
1.253     stredwic 6628:         }
1.955     raeburn  6629:     } elsif(!defined($getpropath)) {
1.841     albertel 6630:         my @all_domains = sort(&all_domains());
1.955     raeburn  6631:         foreach my $domain (@all_domains) {
                   6632:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6633:         }
                   6634:         return @all_domains;
                   6635:     } else {
1.800     albertel 6636:         return ('missing domain');
1.275     stredwic 6637:     }
                   6638: }
                   6639: 
                   6640: # --------------------------------------------- GetFileTimestamp
                   6641: # This function utilizes dirlist and returns the date stamp for
                   6642: # when it was last modified.  It will also return an error of -1
                   6643: # if an error occurs
                   6644: 
                   6645: sub GetFileTimestamp {
1.955     raeburn  6646:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6647:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6648:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6649:     my ($fileStat) = 
                   6650:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6651:                                  undef,$getuserdir);
1.275     stredwic 6652:     my @stats = split('&', $fileStat);
                   6653:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6654:         # @stats contains first the filename, then the stat output
                   6655:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6656:     } else {
                   6657:         return -1;
1.253     stredwic 6658:     }
1.26      www      6659: }
                   6660: 
1.712     albertel 6661: sub stat_file {
                   6662:     my ($uri) = @_;
1.787     albertel 6663:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6664: 
1.955     raeburn  6665:     my ($udom,$uname,$file);
1.712     albertel 6666:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6667: 	($udom,$uname,$file) =
1.811     albertel 6668: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6669: 	$file = 'userfiles/'.$file;
                   6670:     }
                   6671:     if ($uri =~ m-^/res/-) {
                   6672: 	($udom,$uname) = 
1.807     albertel 6673: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6674: 	$file = $uri;
                   6675:     }
                   6676: 
                   6677:     if (!$udom || !$uname || !$file) {
                   6678: 	# unable to handle the uri
                   6679: 	return ();
                   6680:     }
1.956     raeburn  6681:     my $getpropath;
                   6682:     if ($file =~ /^userfiles\//) {
                   6683:         $getpropath = 1;
                   6684:     }
1.955     raeburn  6685:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6686:     my @stats = split('&', $result);
1.721     banghart 6687:     
1.712     albertel 6688:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6689: 	shift(@stats); #filename is first
                   6690: 	return @stats;
                   6691:     }
                   6692:     return ();
                   6693: }
                   6694: 
1.26      www      6695: # -------------------------------------------------------- Value of a Condition
                   6696: 
1.713     albertel 6697: # gets the value of a specific preevaluated condition
                   6698: #    stored in the string  $env{user.state.<cid>}
                   6699: # or looks up a condition reference in the bighash and if if hasn't
                   6700: # already been evaluated recurses into docondval to get the value of
                   6701: # the condition, then memoizing it to 
                   6702: #   $env{user.state.<cid>.<condition>}
1.40      www      6703: sub directcondval {
                   6704:     my $number=shift;
1.620     albertel 6705:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6706: 	&Apache::lonuserstate::evalstate();
                   6707:     }
1.713     albertel 6708:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6709: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6710:     } elsif ($number =~ /^_/) {
                   6711: 	my $sub_condition;
                   6712: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6713: 		&GDBM_READER(),0640)) {
                   6714: 	    $sub_condition=$bighash{'conditions'.$number};
                   6715: 	    untie(%bighash);
                   6716: 	}
                   6717: 	my $value = &docondval($sub_condition);
1.949     raeburn  6718: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6719: 	return $value;
                   6720:     }
1.620     albertel 6721:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6722:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6723:     } else {
                   6724:        return 2;
                   6725:     }
                   6726: }
                   6727: 
1.713     albertel 6728: # get the collection of conditions for this resource
1.26      www      6729: sub condval {
                   6730:     my $condidx=shift;
1.54      www      6731:     my $allpathcond='';
1.713     albertel 6732:     foreach my $cond (split(/\|/,$condidx)) {
                   6733: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6734: 	    $allpathcond.=
                   6735: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6736: 	}
1.191     harris41 6737:     }
1.54      www      6738:     $allpathcond=~s/\|$//;
1.713     albertel 6739:     return &docondval($allpathcond);
                   6740: }
                   6741: 
                   6742: #evaluates an expression of conditions
                   6743: sub docondval {
                   6744:     my ($allpathcond) = @_;
                   6745:     my $result=0;
                   6746:     if ($env{'request.course.id'}
                   6747: 	&& defined($allpathcond)) {
                   6748: 	my $operand='|';
                   6749: 	my @stack;
                   6750: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6751: 	    if ($chunk eq '(') {
                   6752: 		push @stack,($operand,$result);
                   6753: 	    } elsif ($chunk eq ')') {
                   6754: 		my $before=pop @stack;
                   6755: 		if (pop @stack eq '&') {
                   6756: 		    $result=$result>$before?$before:$result;
                   6757: 		} else {
                   6758: 		    $result=$result>$before?$result:$before;
                   6759: 		}
                   6760: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6761: 		$operand=$chunk;
                   6762: 	    } else {
                   6763: 		my $new=directcondval($chunk);
                   6764: 		if ($operand eq '&') {
                   6765: 		    $result=$result>$new?$new:$result;
                   6766: 		} else {
                   6767: 		    $result=$result>$new?$result:$new;
                   6768: 		}
                   6769: 	    }
                   6770: 	}
1.26      www      6771:     }
                   6772:     return $result;
1.421     albertel 6773: }
                   6774: 
                   6775: # ---------------------------------------------------- Devalidate courseresdata
                   6776: 
                   6777: sub devalidatecourseresdata {
                   6778:     my ($coursenum,$coursedomain)=@_;
                   6779:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6780:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6781: }
                   6782: 
1.763     www      6783: 
1.200     www      6784: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6785: #
                   6786: #  Parameters:
                   6787: #      $coursenum    - Number of the course.
                   6788: #      $coursedomain - Domain at which the course was created.
                   6789: #  Returns:
                   6790: #     A hash of the course parameters along (I think) with timestamps
                   6791: #     and version info.
1.877     foxr     6792: 
1.624     albertel 6793: sub get_courseresdata {
                   6794:     my ($coursenum,$coursedomain)=@_;
1.200     www      6795:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6796:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6797:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6798:     my %dumpreply;
1.417     albertel 6799:     unless (defined($cached)) {
1.624     albertel 6800: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6801: 	$result=\%dumpreply;
1.251     albertel 6802: 	my ($tmp) = keys(%dumpreply);
                   6803: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6804: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6805: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6806: 	    return $tmp;
1.416     albertel 6807: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6808: 	    $result=undef;
1.599     albertel 6809: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6810: 	}
                   6811:     }
1.624     albertel 6812:     return $result;
                   6813: }
                   6814: 
1.633     albertel 6815: sub devalidateuserresdata {
                   6816:     my ($uname,$udom)=@_;
                   6817:     my $hashid="$udom:$uname";
                   6818:     &devalidate_cache_new('userres',$hashid);
                   6819: }
                   6820: 
1.624     albertel 6821: sub get_userresdata {
                   6822:     my ($uname,$udom)=@_;
                   6823:     #most student don\'t have any data set, check if there is some data
                   6824:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6825: 
                   6826:     my $hashid="$udom:$uname";
                   6827:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6828:     if (!defined($cached)) {
                   6829: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6830: 	$result=\%resourcedata;
                   6831: 	&do_cache_new('userres',$hashid,$result,600);
                   6832:     }
                   6833:     my ($tmp)=keys(%$result);
                   6834:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6835: 	return $result;
                   6836:     }
                   6837:     #error 2 occurs when the .db doesn't exist
                   6838:     if ($tmp!~/error: 2 /) {
1.672     albertel 6839: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6840: 		 " Trying to get resource data for ".
                   6841: 		 $uname." at ".$udom.": ".
                   6842: 		 $tmp."</font>");
                   6843:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6844: 	#&EXT_cache_set($udom,$uname);
                   6845: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6846: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6847:     }
                   6848:     return $tmp;
                   6849: }
1.879     foxr     6850: #----------------------------------------------- resdata - return resource data
                   6851: #  Purpose:
                   6852: #    Return resource data for either users or for a course.
                   6853: #  Parameters:
                   6854: #     $name      - Course/user name.
                   6855: #     $domain    - Name of the domain the user/course is registered on.
                   6856: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6857: #     @which     - Array of names of resources desired.
                   6858: #  Returns:
                   6859: #     The value of the first reasource in @which that is found in the
                   6860: #     resource hash.
                   6861: #  Exceptional Conditions:
                   6862: #     If the $type passed in is not valid (not the string 'course' or 
                   6863: #     'user', an undefined  reference is returned.
                   6864: #     If none of the resources are found, an undef is returned
1.624     albertel 6865: sub resdata {
                   6866:     my ($name,$domain,$type,@which)=@_;
                   6867:     my $result;
                   6868:     if ($type eq 'course') {
                   6869: 	$result=&get_courseresdata($name,$domain);
                   6870:     } elsif ($type eq 'user') {
                   6871: 	$result=&get_userresdata($name,$domain);
                   6872:     }
                   6873:     if (!ref($result)) { return $result; }    
1.251     albertel 6874:     foreach my $item (@which) {
1.927     albertel 6875: 	if (defined($result->{$item->[0]})) {
                   6876: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6877: 	}
1.250     albertel 6878:     }
1.291     albertel 6879:     return undef;
1.200     www      6880: }
                   6881: 
1.379     matthew  6882: #
                   6883: # EXT resource caching routines
                   6884: #
                   6885: 
                   6886: sub clear_EXT_cache_status {
1.383     albertel 6887:     &delenv('cache.EXT.');
1.379     matthew  6888: }
                   6889: 
                   6890: sub EXT_cache_status {
                   6891:     my ($target_domain,$target_user) = @_;
1.383     albertel 6892:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6893:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6894:         # We know already the user has no data
                   6895:         return 1;
                   6896:     } else {
                   6897:         return 0;
                   6898:     }
                   6899: }
                   6900: 
                   6901: sub EXT_cache_set {
                   6902:     my ($target_domain,$target_user) = @_;
1.383     albertel 6903:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6904:     #&appenv({$cachename => time});
1.379     matthew  6905: }
                   6906: 
1.28      www      6907: # --------------------------------------------------------- Value of a Variable
1.58      www      6908: sub EXT {
1.715     albertel 6909: 
1.395     albertel 6910:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6911:     unless ($varname) { return ''; }
1.218     albertel 6912:     #get real user name/domain, courseid and symb
                   6913:     my $courseid;
1.359     albertel 6914:     my $publicuser;
1.427     www      6915:     if ($symbparm) {
                   6916: 	$symbparm=&get_symb_from_alias($symbparm);
                   6917:     }
1.218     albertel 6918:     if (!($uname && $udom)) {
1.790     albertel 6919:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6920:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6921:     } else {
1.620     albertel 6922: 	$courseid=$env{'request.course.id'};
1.218     albertel 6923:     }
1.48      www      6924:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6925:     my $rest;
1.320     albertel 6926:     if (defined($therest[0])) {
1.48      www      6927:        $rest=join('.',@therest);
                   6928:     } else {
                   6929:        $rest='';
                   6930:     }
1.320     albertel 6931: 
1.57      www      6932:     my $qualifierrest=$qualifier;
                   6933:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6934:     my $spacequalifierrest=$space;
                   6935:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6936:     if ($realm eq 'user') {
1.48      www      6937: # --------------------------------------------------------------- user.resource
                   6938: 	if ($space eq 'resource') {
1.651     albertel 6939: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6940: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6941: 		 &&
1.744     albertel 6942: 		 ($symbparm eq &symbread()) ) {	
                   6943: 		# if we are in the middle of processing the resource the
                   6944: 		# get the value we are planning on committing
                   6945:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6946:                     return $Apache::lonhomework::results{$qualifierrest};
                   6947:                 } else {
                   6948:                     return $Apache::lonhomework::history{$qualifierrest};
                   6949:                 }
1.335     albertel 6950: 	    } else {
1.359     albertel 6951: 		my %restored;
1.620     albertel 6952: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6953: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6954: 		} else {
                   6955: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6956: 		}
1.335     albertel 6957: 		return $restored{$qualifierrest};
                   6958: 	    }
1.48      www      6959: # ----------------------------------------------------------------- user.access
                   6960:         } elsif ($space eq 'access') {
1.218     albertel 6961: 	    # FIXME - not supporting calls for a specific user
1.48      www      6962:             return &allowed($qualifier,$rest);
                   6963: # ------------------------------------------ user.preferences, user.environment
                   6964:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6965: 	    if (($uname eq $env{'user.name'}) &&
                   6966: 		($udom eq $env{'user.domain'})) {
                   6967: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6968: 	    } else {
1.359     albertel 6969: 		my %returnhash;
                   6970: 		if (!$publicuser) {
                   6971: 		    %returnhash=&userenvironment($udom,$uname,
                   6972: 						 $qualifierrest);
                   6973: 		}
1.218     albertel 6974: 		return $returnhash{$qualifierrest};
                   6975: 	    }
1.48      www      6976: # ----------------------------------------------------------------- user.course
                   6977:         } elsif ($space eq 'course') {
1.218     albertel 6978: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6979:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6980: # ------------------------------------------------------------------- user.role
                   6981:         } elsif ($space eq 'role') {
1.218     albertel 6982: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6983:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6984:             if ($qualifier eq 'value') {
                   6985: 		return $role;
                   6986:             } elsif ($qualifier eq 'extent') {
                   6987:                 return $where;
                   6988:             }
                   6989: # ----------------------------------------------------------------- user.domain
                   6990:         } elsif ($space eq 'domain') {
1.218     albertel 6991:             return $udom;
1.48      www      6992: # ------------------------------------------------------------------- user.name
                   6993:         } elsif ($space eq 'name') {
1.218     albertel 6994:             return $uname;
1.48      www      6995: # ---------------------------------------------------- Any other user namespace
1.29      www      6996:         } else {
1.359     albertel 6997: 	    my %reply;
                   6998: 	    if (!$publicuser) {
                   6999: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7000: 	    }
                   7001: 	    return $reply{$qualifierrest};
1.48      www      7002:         }
1.236     www      7003:     } elsif ($realm eq 'query') {
                   7004: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7005:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7006: 						[$spacequalifierrest]);
1.620     albertel 7007: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7008:    } elsif ($realm eq 'request') {
1.48      www      7009: # ------------------------------------------------------------- request.browser
                   7010:         if ($space eq 'browser') {
1.430     www      7011: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7012: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7013: 		    return 1;
                   7014: 		} else {
                   7015: 		    return 0;
                   7016: 		}
                   7017: 	    } else {
1.620     albertel 7018: 		return $env{'browser.'.$qualifier};
1.430     www      7019: 	    }
1.57      www      7020: # ------------------------------------------------------------ request.filename
                   7021:         } else {
1.620     albertel 7022:             return $env{'request.'.$spacequalifierrest};
1.29      www      7023:         }
1.28      www      7024:     } elsif ($realm eq 'course') {
1.48      www      7025: # ---------------------------------------------------------- course.description
1.620     albertel 7026:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7027:     } elsif ($realm eq 'resource') {
1.165     www      7028: 
1.620     albertel 7029: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7030: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7031: 	}
1.693     albertel 7032: 
                   7033: 	if ($space eq 'title') {
                   7034: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7035: 	    return &gettitle($symbparm);
                   7036: 	}
                   7037: 	
                   7038: 	if ($space eq 'map') {
                   7039: 	    my ($map) = &decode_symb($symbparm);
                   7040: 	    return &symbread($map);
                   7041: 	}
1.905     albertel 7042: 	if ($space eq 'filename') {
                   7043: 	    if ($symbparm) {
                   7044: 		return &clutter((&decode_symb($symbparm))[2]);
                   7045: 	    }
                   7046: 	    return &hreflocation('',$env{'request.filename'});
                   7047: 	}
1.693     albertel 7048: 
                   7049: 	my ($section, $group, @groups);
1.593     albertel 7050: 	my ($courselevelm,$courselevel);
1.539     albertel 7051: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7052: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7053: 
1.218     albertel 7054: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7055: 
1.60      www      7056: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7057: 	    my $symbp=$symbparm;
1.735     albertel 7058: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7059: 
                   7060: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7061: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7062: 
1.620     albertel 7063: 	    if (($env{'user.name'} eq $uname) &&
                   7064: 		($env{'user.domain'} eq $udom)) {
                   7065: 		$section=$env{'request.course.sec'};
1.733     raeburn  7066:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7067:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7068: 	    } else {
1.539     albertel 7069: 		if (! defined($usection)) {
1.551     albertel 7070: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7071: 		} else {
                   7072: 		    $section = $usection;
                   7073: 		}
1.733     raeburn  7074:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7075: 	    }
                   7076: 
                   7077: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7078: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7079: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7080: 
1.593     albertel 7081: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7082: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7083: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7084: 
1.60      www      7085: # ----------------------------------------------------------- first, check user
1.624     albertel 7086: 
                   7087: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7088: 				       ([$courselevelr,'resource'],
                   7089: 					[$courselevelm,'map'     ],
                   7090: 					[$courselevel, 'course'  ]));
1.931     albertel 7091: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7092: 
1.594     albertel 7093: # ------------------------------------------------ second, check some of course
1.684     raeburn  7094:             my $coursereply;
1.691     raeburn  7095:             if (@groups > 0) {
                   7096:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7097:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7098:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7099:             }
1.96      www      7100: 
1.684     raeburn  7101: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7102: 				  $env{'course.'.$courseid.'.domain'},
                   7103: 				  'course',
                   7104: 				  ([$seclevelr,   'resource'],
                   7105: 				   [$seclevelm,   'map'     ],
                   7106: 				   [$seclevel,    'course'  ],
                   7107: 				   [$courselevelr,'resource']));
                   7108: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7109: 
1.60      www      7110: # ------------------------------------------------------ third, check map parms
1.218     albertel 7111: 	    my %parmhash=();
                   7112: 	    my $thisparm='';
                   7113: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7114: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7115: 		    &GDBM_READER(),0640)) {
1.218     albertel 7116: 		$thisparm=$parmhash{$symbparm};
                   7117: 		untie(%parmhash);
                   7118: 	    }
1.927     albertel 7119: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7120: 	}
1.594     albertel 7121: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7122: 
1.218     albertel 7123: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7124: 	my $filename;
                   7125: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7126: 	if ($symbparm) {
1.409     www      7127: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7128: 	} else {
1.620     albertel 7129: 	    $filename=$env{'request.filename'};
1.282     albertel 7130: 	}
                   7131: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7132: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7133: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7134: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7135: 
1.927     albertel 7136: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7137: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7138: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7139: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7140: 				     $env{'course.'.$courseid.'.domain'},
                   7141: 				     'course',
1.927     albertel 7142: 				     ([$courselevelm,'map'   ],
                   7143: 				      [$courselevel, 'course']));
                   7144: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7145: 	}
1.145     www      7146: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7147: 	unless ($space eq '0') {
1.336     albertel 7148: 	    my @parts=split(/_/,$space);
                   7149: 	    my $id=pop(@parts);
                   7150: 	    my $part=join('_',@parts);
                   7151: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7152: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7153: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7154: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7155: 	}
1.395     albertel 7156: 	if ($recurse) { return undef; }
                   7157: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7158: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7159: # ---------------------------------------------------- Any other user namespace
                   7160:     } elsif ($realm eq 'environment') {
                   7161: # ----------------------------------------------------------------- environment
1.620     albertel 7162: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7163: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7164: 	} else {
1.770     albertel 7165: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7166: 		return '';
                   7167: 	    }
1.219     albertel 7168: 	    my %returnhash=&userenvironment($udom,$uname,
                   7169: 					    $spacequalifierrest);
                   7170: 	    return $returnhash{$spacequalifierrest};
                   7171: 	}
1.28      www      7172:     } elsif ($realm eq 'system') {
1.48      www      7173: # ----------------------------------------------------------------- system.time
                   7174: 	if ($space eq 'time') {
                   7175: 	    return time;
                   7176:         }
1.696     albertel 7177:     } elsif ($realm eq 'server') {
                   7178: # ----------------------------------------------------------------- system.time
                   7179: 	if ($space eq 'name') {
                   7180: 	    return $ENV{'SERVER_NAME'};
                   7181:         }
1.28      www      7182:     }
1.48      www      7183:     return '';
1.61      www      7184: }
                   7185: 
1.927     albertel 7186: sub get_reply {
                   7187:     my ($reply_value) = @_;
1.940     raeburn  7188:     if (ref($reply_value) eq 'ARRAY') {
                   7189:         if (wantarray) {
                   7190: 	    return @$reply_value;
                   7191:         }
                   7192:         return $reply_value->[0];
                   7193:     } else {
                   7194:         return $reply_value;
1.927     albertel 7195:     }
                   7196: }
                   7197: 
1.691     raeburn  7198: sub check_group_parms {
                   7199:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7200:     my @groupitems = ();
                   7201:     my $resultitem;
1.927     albertel 7202:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7203:     foreach my $group (@{$groups}) {
                   7204:         foreach my $level (@levels) {
1.927     albertel 7205:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7206:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7207:         }
                   7208:     }
                   7209:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7210:                             $env{'course.'.$courseid.'.domain'},
                   7211:                                      'course',@groupitems);
                   7212:     return $coursereply;
                   7213: }
                   7214: 
                   7215: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7216:     my ($courseid,@groups) = @_;
                   7217:     @groups = sort(@groups);
1.691     raeburn  7218:     return @groups;
                   7219: }
                   7220: 
1.395     albertel 7221: sub packages_tab_default {
                   7222:     my ($uri,$varname)=@_;
                   7223:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7224: 
                   7225:     my (@extension,@specifics,$do_default);
                   7226:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7227: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7228: 	if ($pack_type eq 'default') {
                   7229: 	    $do_default=1;
                   7230: 	} elsif ($pack_type eq 'extension') {
                   7231: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7232: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7233: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7234: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7235: 	}
                   7236:     }
                   7237:     # first look for a package that matches the requested part id
                   7238:     foreach my $package (@specifics) {
                   7239: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7240: 	next if ($pack_part ne $part);
                   7241: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7242: 	    return $packagetab{"$pack_type&$name&default"};
                   7243: 	}
                   7244:     }
                   7245:     # look for any possible matching non extension_ package
                   7246:     foreach my $package (@specifics) {
                   7247: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7248: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7249: 	    return $packagetab{"$pack_type&$name&default"};
                   7250: 	}
1.585     albertel 7251: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7252: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7253: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7254: 	}
                   7255:     }
1.738     albertel 7256:     # look for any posible extension_ match
                   7257:     foreach my $package (@extension) {
                   7258: 	my ($package,$pack_type)=@{$package};
                   7259: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7260: 	    return $packagetab{"$pack_type&$name&default"};
                   7261: 	}
                   7262: 	if (defined($packagetab{$package."&$name&default"})) {
                   7263: 	    return $packagetab{$package."&$name&default"};
                   7264: 	}
                   7265:     }
                   7266:     # look for a global default setting
                   7267:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7268: 	return $packagetab{"default&$name&default"};
                   7269:     }
1.395     albertel 7270:     return undef;
                   7271: }
                   7272: 
1.334     albertel 7273: sub add_prefix_and_part {
                   7274:     my ($prefix,$part)=@_;
                   7275:     my $keyroot;
                   7276:     if (defined($prefix) && $prefix !~ /^__/) {
                   7277: 	# prefix that has a part already
                   7278: 	$keyroot=$prefix;
                   7279:     } elsif (defined($prefix)) {
                   7280: 	# prefix that is missing a part
                   7281: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7282:     } else {
                   7283: 	# no prefix at all
                   7284: 	if (defined($part)) { $keyroot='_'.$part; }
                   7285:     }
                   7286:     return $keyroot;
                   7287: }
                   7288: 
1.71      www      7289: # ---------------------------------------------------------------- Get metadata
                   7290: 
1.599     albertel 7291: my %metaentry;
1.71      www      7292: sub metadata {
1.176     www      7293:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7294:     $uri=&declutter($uri);
1.288     albertel 7295:     # if it is a non metadata possible uri return quickly
1.529     albertel 7296:     if (($uri eq '') || 
                   7297: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7298: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7299:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7300: 	return undef;
                   7301:     }
                   7302:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7303: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7304: 	return undef;
1.288     albertel 7305:     }
1.73      www      7306:     my $filename=$uri;
                   7307:     $uri=~s/\.meta$//;
1.172     www      7308: #
                   7309: # Is the metadata already cached?
1.177     www      7310: # Look at timestamp of caching
1.172     www      7311: # Everything is cached by the main uri, libraries are never directly cached
                   7312: #
1.428     albertel 7313:     if (!defined($liburi)) {
1.599     albertel 7314: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7315: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7316:     }
                   7317:     {
1.172     www      7318: #
                   7319: # Is this a recursive call for a library?
                   7320: #
1.599     albertel 7321: #	if (! exists($metacache{$uri})) {
                   7322: #	    $metacache{$uri}={};
                   7323: #	}
1.924     albertel 7324: 	my $cachetime = 60*60;
1.171     www      7325:         if ($liburi) {
                   7326: 	    $liburi=&declutter($liburi);
                   7327:             $filename=$liburi;
1.401     bowersj2 7328:         } else {
1.599     albertel 7329: 	    &devalidate_cache_new('meta',$uri);
                   7330: 	    undef(%metaentry);
1.401     bowersj2 7331: 	}
1.140     www      7332:         my %metathesekeys=();
1.73      www      7333:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7334: 	my $metastring;
1.924     albertel 7335: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7336: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7337: 	    $metastring = 
1.929     albertel 7338: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7339: 					  ('grade_target' => 'meta'));
                   7340: 	    $cachetime = 1; # only want this cached in the child not long term
                   7341: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7342: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7343: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7344: 	    $metastring=&getfile($file);
1.489     albertel 7345: 	}
1.208     albertel 7346:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7347:         my $token;
1.140     www      7348:         undef %metathesekeys;
1.71      www      7349:         while ($token=$parser->get_token) {
1.339     albertel 7350: 	    if ($token->[0] eq 'S') {
                   7351: 		if (defined($token->[2]->{'package'})) {
1.172     www      7352: #
                   7353: # This is a package - get package info
                   7354: #
1.339     albertel 7355: 		    my $package=$token->[2]->{'package'};
                   7356: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7357: 		    if (defined($token->[2]->{'id'})) { 
                   7358: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7359: 		    }
1.599     albertel 7360: 		    if ($metaentry{':packages'}) {
                   7361: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7362: 		    } else {
1.599     albertel 7363: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7364: 		    }
1.736     albertel 7365: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7366: 			my $part=$keyroot;
                   7367: 			$part=~s/^\_//;
1.736     albertel 7368: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7369: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7370: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7371: 			    # ignore package.tab specified default values
                   7372:                             # here &package_tab_default() will fetch those
                   7373: 			    if ($subp eq 'default') { next; }
1.736     albertel 7374: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7375: 			    my $unikey;
                   7376: 			    if ($pack =~ /_0$/) {
                   7377: 				$unikey='parameter_0_'.$name;
                   7378: 				$part=0;
                   7379: 			    } else {
                   7380: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7381: 			    }
1.339     albertel 7382: 			    if ($subp eq 'display') {
                   7383: 				$value.=' [Part: '.$part.']';
                   7384: 			    }
1.599     albertel 7385: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7386: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7387: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7388: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7389: 			    }
1.599     albertel 7390: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7391: 				$metaentry{':'.$unikey}=
                   7392: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7393: 			    }
1.339     albertel 7394: 			}
                   7395: 		    }
                   7396: 		} else {
1.172     www      7397: #
                   7398: # This is not a package - some other kind of start tag
1.339     albertel 7399: #
                   7400: 		    my $entry=$token->[1];
                   7401: 		    my $unikey;
                   7402: 		    if ($entry eq 'import') {
                   7403: 			$unikey='';
                   7404: 		    } else {
                   7405: 			$unikey=$entry;
                   7406: 		    }
                   7407: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7408: 
                   7409: 		    if (defined($token->[2]->{'id'})) { 
                   7410: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7411: 		    }
1.175     www      7412: 
1.339     albertel 7413: 		    if ($entry eq 'import') {
1.175     www      7414: #
                   7415: # Importing a library here
1.339     albertel 7416: #
                   7417: 			if ($depthcount<20) {
                   7418: 			    my $location=$parser->get_text('/import');
                   7419: 			    my $dir=$filename;
                   7420: 			    $dir=~s|[^/]*$||;
                   7421: 			    $location=&filelocation($dir,$location);
1.736     albertel 7422: 			    my $metadata = 
                   7423: 				&metadata($uri,'keys', $location,$unikey,
                   7424: 					  $depthcount+1);
                   7425: 			    foreach my $meta (split(',',$metadata)) {
                   7426: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7427: 				$metathesekeys{$meta}=1;
1.339     albertel 7428: 			    }
                   7429: 			}
                   7430: 		    } else { 
                   7431: 			
                   7432: 			if (defined($token->[2]->{'name'})) { 
                   7433: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7434: 			}
                   7435: 			$metathesekeys{$unikey}=1;
1.736     albertel 7436: 			foreach my $param (@{$token->[3]}) {
                   7437: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7438: 				$token->[2]->{$param};
1.339     albertel 7439: 			}
                   7440: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7441: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7442: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7443: 		 # only ws inside the tag, and not in default, so use default
                   7444: 		 # as value
1.599     albertel 7445: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7446: 			} elsif ( $internaltext =~ /\S/ ) {
                   7447: 		  # something interesting inside the tag
                   7448: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7449: 			} else {
1.908     albertel 7450: 		  # no interesting values, don't set a default
1.339     albertel 7451: 			}
1.172     www      7452: # end of not-a-package not-a-library import
1.339     albertel 7453: 		    }
1.172     www      7454: # end of not-a-package start tag
1.339     albertel 7455: 		}
1.172     www      7456: # the next is the end of "start tag"
1.339     albertel 7457: 	    }
                   7458: 	}
1.483     albertel 7459: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7460: 	$extension = lc($extension);
                   7461: 	if ($extension eq 'htm') { $extension='html'; }
                   7462: 
1.737     albertel 7463: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7464: 	    #no specific packages #how's our extension
                   7465: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7466: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7467: 					 \%metathesekeys);
                   7468: 	}
1.883     albertel 7469: 
                   7470: 	if (!exists($metaentry{':packages'})
                   7471: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7472: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7473: 		#no specific packages well let's get default then
                   7474: 		if ($key!~/^default&/) { next; }
1.488     albertel 7475: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7476: 					     \%metathesekeys);
                   7477: 	    }
                   7478: 	}
1.338     www      7479: # are there custom rights to evaluate
1.599     albertel 7480: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7481: 
1.338     www      7482:     #
                   7483:     # Importing a rights file here
1.339     albertel 7484:     #
                   7485: 	    unless ($depthcount) {
1.599     albertel 7486: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7487: 		my $dir=$filename;
                   7488: 		$dir=~s|[^/]*$||;
                   7489: 		$location=&filelocation($dir,$location);
1.736     albertel 7490: 		my $rights_metadata =
                   7491: 		    &metadata($uri,'keys',$location,'_rights',
                   7492: 			      $depthcount+1);
                   7493: 		foreach my $rights (split(',',$rights_metadata)) {
                   7494: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7495: 		    $metathesekeys{$rights}=1;
1.339     albertel 7496: 		}
                   7497: 	    }
                   7498: 	}
1.737     albertel 7499: 	# uniqifiy package listing
                   7500: 	my %seen;
                   7501: 	my @uniq_packages =
                   7502: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7503: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7504: 
                   7505: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7506: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7507: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7508: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7509: # this is the end of "was not already recently cached
1.71      www      7510:     }
1.599     albertel 7511:     return $metaentry{':'.$what};
1.261     albertel 7512: }
                   7513: 
1.488     albertel 7514: sub metadata_create_package_def {
1.483     albertel 7515:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7516:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7517:     if ($subp eq 'default') { next; }
                   7518:     
1.599     albertel 7519:     if (defined($metaentry{':packages'})) {
                   7520: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7521:     } else {
1.599     albertel 7522: 	$metaentry{':packages'}=$package;
1.483     albertel 7523:     }
                   7524:     my $value=$packagetab{$key};
                   7525:     my $unikey;
                   7526:     $unikey='parameter_0_'.$name;
1.599     albertel 7527:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7528:     $$metathesekeys{$unikey}=1;
1.599     albertel 7529:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7530: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7531:     }
1.599     albertel 7532:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7533: 	$metaentry{':'.$unikey}=
                   7534: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7535:     }
                   7536: }
                   7537: 
1.261     albertel 7538: sub metadata_generate_part0 {
                   7539:     my ($metadata,$metacache,$uri) = @_;
                   7540:     my %allnames;
1.737     albertel 7541:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7542: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7543: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7544: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7545: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7546: 	    $allnames{$name}=$part;
                   7547: 	  }
                   7548: 	}
                   7549:     }
                   7550:     foreach my $name (keys(%allnames)) {
                   7551:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7552:       my $key=":parameter_0_$name";
1.261     albertel 7553:       $$metacache{"$key.part"}='0';
                   7554:       $$metacache{"$key.name"}=$name;
1.428     albertel 7555:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7556: 					   $allnames{$name}.'_'.$name.
                   7557: 					   '.type'};
1.428     albertel 7558:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7559: 			     '.display'};
1.644     www      7560:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7561:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7562:       $$metacache{"$key.display"}=$olddis;
                   7563:     }
1.71      www      7564: }
                   7565: 
1.764     albertel 7566: # ------------------------------------------------------ Devalidate title cache
                   7567: 
                   7568: sub devalidate_title_cache {
                   7569:     my ($url)=@_;
                   7570:     if (!$env{'request.course.id'}) { return; }
                   7571:     my $symb=&symbread($url);
                   7572:     if (!$symb) { return; }
                   7573:     my $key=$env{'request.course.id'}."\0".$symb;
                   7574:     &devalidate_cache_new('title',$key);
                   7575: }
                   7576: 
1.301     www      7577: # ------------------------------------------------- Get the title of a resource
                   7578: 
                   7579: sub gettitle {
                   7580:     my $urlsymb=shift;
                   7581:     my $symb=&symbread($urlsymb);
1.534     albertel 7582:     if ($symb) {
1.620     albertel 7583: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7584: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7585: 	if (defined($cached)) { 
                   7586: 	    return $result;
                   7587: 	}
1.534     albertel 7588: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7589: 	my $title='';
1.907     albertel 7590: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7591: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7592: 	} else {
                   7593: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7594: 		    &GDBM_READER(),0640)) {
                   7595: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7596: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7597: 		untie(%bighash);
                   7598: 	    }
1.534     albertel 7599: 	}
                   7600: 	$title=~s/\&colon\;/\:/gs;
                   7601: 	if ($title) {
1.599     albertel 7602: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7603: 	}
                   7604: 	$urlsymb=$url;
                   7605:     }
                   7606:     my $title=&metadata($urlsymb,'title');
                   7607:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7608:     return $title;
1.301     www      7609: }
1.613     albertel 7610: 
1.614     albertel 7611: sub get_slot {
                   7612:     my ($which,$cnum,$cdom)=@_;
                   7613:     if (!$cnum || !$cdom) {
1.790     albertel 7614: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7615: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7616: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7617:     }
1.703     albertel 7618:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7619:     my %slotinfo;
                   7620:     if (exists($remembered{$key})) {
                   7621: 	$slotinfo{$which} = $remembered{$key};
                   7622:     } else {
                   7623: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7624: 	&Apache::lonhomework::showhash(%slotinfo);
                   7625: 	my ($tmp)=keys(%slotinfo);
                   7626: 	if ($tmp=~/^error:/) { return (); }
                   7627: 	$remembered{$key} = $slotinfo{$which};
                   7628:     }
1.616     albertel 7629:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7630: 	return %{$slotinfo{$which}};
                   7631:     }
                   7632:     return $slotinfo{$which};
1.614     albertel 7633: }
1.31      www      7634: # ------------------------------------------------- Update symbolic store links
                   7635: 
                   7636: sub symblist {
                   7637:     my ($mapname,%newhash)=@_;
1.438     www      7638:     $mapname=&deversion(&declutter($mapname));
1.31      www      7639:     my %hash;
1.620     albertel 7640:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7641:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7642:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7643: 	    foreach my $url (keys %newhash) {
                   7644: 		next if ($url eq 'last_known'
                   7645: 			 && $env{'form.no_update_last_known'});
                   7646: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7647: 						    $newhash{$url}->[1],
                   7648: 						    $newhash{$url}->[0]);
1.191     harris41 7649:             }
1.31      www      7650:             if (untie(%hash)) {
                   7651: 		return 'ok';
                   7652:             }
                   7653:         }
                   7654:     }
                   7655:     return 'error';
1.212     www      7656: }
                   7657: 
                   7658: # --------------------------------------------------------------- Verify a symb
                   7659: 
                   7660: sub symbverify {
1.510     www      7661:     my ($symb,$thisurl)=@_;
                   7662:     my $thisfn=$thisurl;
1.439     www      7663:     $thisfn=&declutter($thisfn);
1.215     www      7664: # direct jump to resource in page or to a sequence - will construct own symbs
                   7665:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7666: # check URL part
1.409     www      7667:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7668: 
1.431     www      7669:     unless ($url eq $thisfn) { return 0; }
1.213     www      7670: 
1.216     www      7671:     $symb=&symbclean($symb);
1.510     www      7672:     $thisurl=&deversion($thisurl);
1.439     www      7673:     $thisfn=&deversion($thisfn);
1.213     www      7674: 
                   7675:     my %bighash;
                   7676:     my $okay=0;
1.431     www      7677: 
1.620     albertel 7678:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7679:                             &GDBM_READER(),0640)) {
1.510     www      7680:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7681:         unless ($ids) { 
1.510     www      7682:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7683:         }
                   7684:         if ($ids) {
                   7685: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7686: 	    foreach my $id (split(/\,/,$ids)) {
                   7687: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7688:                if (
                   7689:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7690:    eq $symb) { 
1.620     albertel 7691: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7692: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7693: 		       $okay=1; 
                   7694: 		   }
                   7695: 	       }
1.216     www      7696: 	   }
                   7697:         }
1.213     www      7698: 	untie(%bighash);
                   7699:     }
                   7700:     return $okay;
1.31      www      7701: }
                   7702: 
1.210     www      7703: # --------------------------------------------------------------- Clean-up symb
                   7704: 
                   7705: sub symbclean {
                   7706:     my $symb=shift;
1.568     albertel 7707:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7708: # remove version from map
                   7709:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7710: 
1.210     www      7711: # remove version from URL
                   7712:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7713: 
1.507     www      7714: # remove wrapper
                   7715: 
1.510     www      7716:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7717:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7718:     return $symb;
1.409     www      7719: }
                   7720: 
                   7721: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7722: 
                   7723: sub encode_symb {
                   7724:     my ($map,$resid,$url)=@_;
                   7725:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7726: }
1.409     www      7727: 
                   7728: sub decode_symb {
1.568     albertel 7729:     my $symb=shift;
                   7730:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7731:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7732:     return (&fixversion($map),$resid,&fixversion($url));
                   7733: }
                   7734: 
                   7735: sub fixversion {
                   7736:     my $fn=shift;
1.609     banghart 7737:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7738:     my %bighash;
                   7739:     my $uri=&clutter($fn);
1.620     albertel 7740:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7741: # is this cached?
1.599     albertel 7742:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7743:     if (defined($cached)) { return $result; }
                   7744: # unfortunately not cached, or expired
1.620     albertel 7745:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7746: 	    &GDBM_READER(),0640)) {
                   7747:  	if ($bighash{'version_'.$uri}) {
                   7748:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7749:  	    unless (($version eq 'mostrecent') || 
                   7750: 		    ($version==&getversion($uri))) {
1.440     www      7751:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7752:  	    }
                   7753:  	}
                   7754:  	untie %bighash;
1.413     www      7755:     }
1.599     albertel 7756:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7757: }
                   7758: 
                   7759: sub deversion {
                   7760:     my $url=shift;
                   7761:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7762:     return $url;
1.210     www      7763: }
                   7764: 
1.31      www      7765: # ------------------------------------------------------ Return symb list entry
                   7766: 
                   7767: sub symbread {
1.249     www      7768:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7769:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7770:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7771: # no filename provided? try from environment
1.44      www      7772:     unless ($thisfn) {
1.620     albertel 7773:         if ($env{'request.symb'}) {
                   7774: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7775: 	}
1.620     albertel 7776: 	$thisfn=$env{'request.filename'};
1.44      www      7777:     }
1.569     albertel 7778:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7779: # is that filename actually a symb? Verify, clean, and return
                   7780:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7781: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7782: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7783: 	}
1.242     www      7784:     }
1.44      www      7785:     $thisfn=declutter($thisfn);
1.31      www      7786:     my %hash;
1.37      www      7787:     my %bighash;
                   7788:     my $syval='';
1.620     albertel 7789:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7790:         my $targetfn = $thisfn;
1.609     banghart 7791:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7792:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7793:         }
1.687     albertel 7794: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7795: 	    $targetfn=$1;
                   7796: 	}
1.620     albertel 7797:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7798:                       &GDBM_READER(),0640)) {
1.481     raeburn  7799: 	    $syval=$hash{$targetfn};
1.37      www      7800:             untie(%hash);
                   7801:         }
                   7802: # ---------------------------------------------------------- There was an entry
                   7803:         if ($syval) {
1.601     albertel 7804: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7805: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7806: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7807: 		    #return $env{$cache_str}='';
1.601     albertel 7808: 		#}    
                   7809: 		#$syval.=$1;
                   7810: 	    #}
1.37      www      7811:         } else {
                   7812: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7813:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7814:                             &GDBM_READER(),0640)) {
1.37      www      7815: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7816:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7817:               unless ($ids) { 
                   7818:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7819:               }
                   7820:               unless ($ids) {
                   7821: # alias?
                   7822: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7823:               }
1.37      www      7824:               if ($ids) {
                   7825: # ------------------------------------------------------------------- Has ID(s)
                   7826:                  my @possibilities=split(/\,/,$ids);
1.39      www      7827:                  if ($#possibilities==0) {
                   7828: # ----------------------------------------------- There is only one possibility
1.37      www      7829: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7830: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7831: 						    $resid,$thisfn);
1.249     www      7832:                  } elsif (!$donotrecurse) {
1.39      www      7833: # ------------------------------------------ There is more than one possibility
                   7834:                      my $realpossible=0;
1.800     albertel 7835:                      foreach my $id (@possibilities) {
                   7836: 			 my $file=$bighash{'src_'.$id};
1.39      www      7837:                          if (&allowed('bre',$file)) {
1.800     albertel 7838:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7839:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7840: 				$realpossible++;
1.626     albertel 7841:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7842: 						    $resid,$thisfn);
1.39      www      7843:                             }
                   7844: 			 }
1.191     harris41 7845:                      }
1.39      www      7846: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7847:                  } else {
                   7848:                      $syval='';
1.37      www      7849:                  }
                   7850: 	      }
                   7851:               untie(%bighash)
1.481     raeburn  7852:            }
1.31      www      7853:         }
1.62      www      7854:         if ($syval) {
1.620     albertel 7855: 	    return $env{$cache_str}=$syval;
1.62      www      7856:         }
1.31      www      7857:     }
1.949     raeburn  7858:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7859:     return $env{$cache_str}='';
1.31      www      7860: }
                   7861: 
                   7862: # ---------------------------------------------------------- Return random seed
                   7863: 
1.32      www      7864: sub numval {
                   7865:     my $txt=shift;
                   7866:     $txt=~tr/A-J/0-9/;
                   7867:     $txt=~tr/a-j/0-9/;
                   7868:     $txt=~tr/K-T/0-9/;
                   7869:     $txt=~tr/k-t/0-9/;
                   7870:     $txt=~tr/U-Z/0-5/;
                   7871:     $txt=~tr/u-z/0-5/;
                   7872:     $txt=~s/\D//g;
1.564     albertel 7873:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7874:     return int($txt);
1.368     albertel 7875: }
                   7876: 
1.484     albertel 7877: sub numval2 {
                   7878:     my $txt=shift;
                   7879:     $txt=~tr/A-J/0-9/;
                   7880:     $txt=~tr/a-j/0-9/;
                   7881:     $txt=~tr/K-T/0-9/;
                   7882:     $txt=~tr/k-t/0-9/;
                   7883:     $txt=~tr/U-Z/0-5/;
                   7884:     $txt=~tr/u-z/0-5/;
                   7885:     $txt=~s/\D//g;
                   7886:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7887:     my $total;
                   7888:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7889:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7890:     return int($total);
                   7891: }
                   7892: 
1.575     albertel 7893: sub numval3 {
                   7894:     use integer;
                   7895:     my $txt=shift;
                   7896:     $txt=~tr/A-J/0-9/;
                   7897:     $txt=~tr/a-j/0-9/;
                   7898:     $txt=~tr/K-T/0-9/;
                   7899:     $txt=~tr/k-t/0-9/;
                   7900:     $txt=~tr/U-Z/0-5/;
                   7901:     $txt=~tr/u-z/0-5/;
                   7902:     $txt=~s/\D//g;
                   7903:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7904:     my $total;
                   7905:     foreach my $val (@txts) { $total+=$val; }
                   7906:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7907:     return $total;
                   7908: }
                   7909: 
1.675     albertel 7910: sub digest {
                   7911:     my ($data)=@_;
                   7912:     my $digest=&Digest::MD5::md5($data);
                   7913:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7914:     my ($e,$f);
                   7915:     {
                   7916:         use integer;
                   7917:         $e=($a+$b);
                   7918:         $f=($c+$d);
                   7919:         if ($_64bit) {
                   7920:             $e=(($e<<32)>>32);
                   7921:             $f=(($f<<32)>>32);
                   7922:         }
                   7923:     }
                   7924:     if (wantarray) {
                   7925: 	return ($e,$f);
                   7926:     } else {
                   7927: 	my $g;
                   7928: 	{
                   7929: 	    use integer;
                   7930: 	    $g=($e+$f);
                   7931: 	    if ($_64bit) {
                   7932: 		$g=(($g<<32)>>32);
                   7933: 	    }
                   7934: 	}
                   7935: 	return $g;
                   7936:     }
                   7937: }
                   7938: 
1.368     albertel 7939: sub latest_rnd_algorithm_id {
1.675     albertel 7940:     return '64bit5';
1.366     albertel 7941: }
1.32      www      7942: 
1.503     albertel 7943: sub get_rand_alg {
                   7944:     my ($courseid)=@_;
1.790     albertel 7945:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7946:     if ($courseid) {
1.620     albertel 7947: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7948:     }
                   7949:     return &latest_rnd_algorithm_id();
                   7950: }
                   7951: 
1.562     albertel 7952: sub validCODE {
                   7953:     my ($CODE)=@_;
                   7954:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7955:     return 0;
                   7956: }
                   7957: 
1.491     albertel 7958: sub getCODE {
1.620     albertel 7959:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7960:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7961: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7962: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7963: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7964:     }
                   7965:     return undef;
                   7966: }
                   7967: 
1.31      www      7968: sub rndseed {
1.155     albertel 7969:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7970:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7971:     if (!defined($symb)) {
1.366     albertel 7972: 	unless ($symb=$wsymb) { return time; }
                   7973:     }
                   7974:     if (!$courseid) { $courseid=$wcourseid; }
                   7975:     if (!$domain) { $domain=$wdomain; }
                   7976:     if (!$username) { $username=$wusername }
1.503     albertel 7977:     my $which=&get_rand_alg();
1.803     albertel 7978: 
1.491     albertel 7979:     if (defined(&getCODE())) {
1.675     albertel 7980: 	if ($which eq '64bit5') {
                   7981: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7982: 	} elsif ($which eq '64bit4') {
1.575     albertel 7983: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7984: 	} else {
                   7985: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7986: 	}
1.675     albertel 7987:     } elsif ($which eq '64bit5') {
                   7988: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7989:     } elsif ($which eq '64bit4') {
                   7990: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7991:     } elsif ($which eq '64bit3') {
                   7992: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7993:     } elsif ($which eq '64bit2') {
                   7994: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7995:     } elsif ($which eq '64bit') {
                   7996: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7997:     }
                   7998:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7999: }
                   8000: 
                   8001: sub rndseed_32bit {
                   8002:     my ($symb,$courseid,$domain,$username)=@_;
                   8003:     {
                   8004: 	use integer;
                   8005: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8006: 	my $symbseed=numval($symb) << 22;
                   8007: 	my $namechck=unpack("%32C*",$username) << 17;
                   8008: 	my $nameseed=numval($username) << 12;
                   8009: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8010: 	my $courseseed=unpack("%32C*",$courseid);
                   8011: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8012: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8013: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8014: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8015: 	return $num;
                   8016:     }
                   8017: }
                   8018: 
                   8019: sub rndseed_64bit {
                   8020:     my ($symb,$courseid,$domain,$username)=@_;
                   8021:     {
                   8022: 	use integer;
                   8023: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8024: 	my $symbseed=numval($symb) << 10;
                   8025: 	my $namechck=unpack("%32S*",$username);
                   8026: 	
                   8027: 	my $nameseed=numval($username) << 21;
                   8028: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8029: 	my $courseseed=unpack("%32S*",$courseid);
                   8030: 	
                   8031: 	my $num1=$symbchck+$symbseed+$namechck;
                   8032: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8034: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8035: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8036: 	return "$num1,$num2";
1.155     albertel 8037:     }
1.366     albertel 8038: }
                   8039: 
1.443     albertel 8040: sub rndseed_64bit2 {
                   8041:     my ($symb,$courseid,$domain,$username)=@_;
                   8042:     {
                   8043: 	use integer;
                   8044: 	# strings need to be an even # of cahracters long, it it is odd the
                   8045:         # last characters gets thrown away
                   8046: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8047: 	my $symbseed=numval($symb) << 10;
                   8048: 	my $namechck=unpack("%32S*",$username.' ');
                   8049: 	
                   8050: 	my $nameseed=numval($username) << 21;
1.501     albertel 8051: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8052: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8053: 	
                   8054: 	my $num1=$symbchck+$symbseed+$namechck;
                   8055: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8056: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8057: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8058: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8059: 	return "$num1,$num2";
                   8060:     }
                   8061: }
                   8062: 
                   8063: sub rndseed_64bit3 {
                   8064:     my ($symb,$courseid,$domain,$username)=@_;
                   8065:     {
                   8066: 	use integer;
                   8067: 	# strings need to be an even # of cahracters long, it it is odd the
                   8068:         # last characters gets thrown away
                   8069: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8070: 	my $symbseed=numval2($symb) << 10;
                   8071: 	my $namechck=unpack("%32S*",$username.' ');
                   8072: 	
                   8073: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8074: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8075: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8076: 	
                   8077: 	my $num1=$symbchck+$symbseed+$namechck;
                   8078: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8079: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8080: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8081: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8082: 	
1.503     albertel 8083: 	return "$num1:$num2";
1.443     albertel 8084:     }
                   8085: }
                   8086: 
1.575     albertel 8087: sub rndseed_64bit4 {
                   8088:     my ($symb,$courseid,$domain,$username)=@_;
                   8089:     {
                   8090: 	use integer;
                   8091: 	# strings need to be an even # of cahracters long, it it is odd the
                   8092:         # last characters gets thrown away
                   8093: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8094: 	my $symbseed=numval3($symb) << 10;
                   8095: 	my $namechck=unpack("%32S*",$username.' ');
                   8096: 	
                   8097: 	my $nameseed=numval3($username) << 21;
                   8098: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8099: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8100: 	
                   8101: 	my $num1=$symbchck+$symbseed+$namechck;
                   8102: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8103: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8104: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8105: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8106: 	
                   8107: 	return "$num1:$num2";
                   8108:     }
                   8109: }
                   8110: 
1.675     albertel 8111: sub rndseed_64bit5 {
                   8112:     my ($symb,$courseid,$domain,$username)=@_;
                   8113:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8114:     return "$num1:$num2";
                   8115: }
                   8116: 
1.366     albertel 8117: sub rndseed_CODE_64bit {
                   8118:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8119:     {
1.366     albertel 8120: 	use integer;
1.443     albertel 8121: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8122: 	my $symbseed=numval2($symb);
1.491     albertel 8123: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8124: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8125: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8126: 	my $num1=$symbseed+$CODEchck;
                   8127: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8128: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8129: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8130: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8131: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8132: 	return "$num1:$num2";
1.366     albertel 8133:     }
                   8134: }
                   8135: 
1.575     albertel 8136: sub rndseed_CODE_64bit4 {
                   8137:     my ($symb,$courseid,$domain,$username)=@_;
                   8138:     {
                   8139: 	use integer;
                   8140: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8141: 	my $symbseed=numval3($symb);
                   8142: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8143: 	my $CODEseed=numval3(&getCODE());
                   8144: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8145: 	my $num1=$symbseed+$CODEchck;
                   8146: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8147: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8148: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8149: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8150: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8151: 	return "$num1:$num2";
                   8152:     }
                   8153: }
                   8154: 
1.675     albertel 8155: sub rndseed_CODE_64bit5 {
                   8156:     my ($symb,$courseid,$domain,$username)=@_;
                   8157:     my $code = &getCODE();
                   8158:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8159:     return "$num1:$num2";
                   8160: }
                   8161: 
1.366     albertel 8162: sub setup_random_from_rndseed {
                   8163:     my ($rndseed)=@_;
1.503     albertel 8164:     if ($rndseed =~/([,:])/) {
                   8165: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8166: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8167:     } else {
                   8168: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8169:     }
1.36      albertel 8170: }
                   8171: 
1.474     albertel 8172: sub latest_receipt_algorithm_id {
1.835     albertel 8173:     return 'receipt3';
1.474     albertel 8174: }
                   8175: 
1.480     www      8176: sub recunique {
                   8177:     my $fucourseid=shift;
                   8178:     my $unique;
1.835     albertel 8179:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8180: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8181: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8182:     } else {
                   8183: 	$unique=$perlvar{'lonReceipt'};
                   8184:     }
                   8185:     return unpack("%32C*",$unique);
                   8186: }
                   8187: 
                   8188: sub recprefix {
                   8189:     my $fucourseid=shift;
                   8190:     my $prefix;
1.835     albertel 8191:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8192: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8193: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8194:     } else {
                   8195: 	$prefix=$perlvar{'lonHostID'};
                   8196:     }
                   8197:     return unpack("%32C*",$prefix);
                   8198: }
                   8199: 
1.76      www      8200: sub ireceipt {
1.474     albertel 8201:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8202: 
                   8203:     my $return =&recprefix($fucourseid).'-';
                   8204: 
                   8205:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8206: 	$env{'request.state'} eq 'construct') {
                   8207: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8208: 	return $return;
                   8209:     }
                   8210: 
1.76      www      8211:     my $cuname=unpack("%32C*",$funame);
                   8212:     my $cudom=unpack("%32C*",$fudom);
                   8213:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8214:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8215:     my $cunique=&recunique($fucourseid);
1.474     albertel 8216:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8217:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8218: 
1.790     albertel 8219: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8220: 			       
                   8221: 	$return.= ($cunique%$cuname+
                   8222: 		   $cunique%$cudom+
                   8223: 		   $cusymb%$cuname+
                   8224: 		   $cusymb%$cudom+
                   8225: 		   $cucourseid%$cuname+
                   8226: 		   $cucourseid%$cudom+
                   8227: 		   $cpart%$cuname+
                   8228: 		   $cpart%$cudom);
                   8229:     } else {
                   8230: 	$return.= ($cunique%$cuname+
                   8231: 		   $cunique%$cudom+
                   8232: 		   $cusymb%$cuname+
                   8233: 		   $cusymb%$cudom+
                   8234: 		   $cucourseid%$cuname+
                   8235: 		   $cucourseid%$cudom);
                   8236:     }
                   8237:     return $return;
1.76      www      8238: }
                   8239: 
                   8240: sub receipt {
1.474     albertel 8241:     my ($part)=@_;
1.790     albertel 8242:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8243:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8244: }
1.260     ng       8245: 
1.790     albertel 8246: sub whichuser {
                   8247:     my ($passedsymb)=@_;
                   8248:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8249:     if (defined($env{'form.grade_symb'})) {
                   8250: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8251: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8252: 	if (!$allowed &&
                   8253: 	    exists($env{'request.course.sec'}) &&
                   8254: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8255: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8256: 			      '/'.$env{'request.course.sec'});
                   8257: 	}
                   8258: 	if ($allowed) {
                   8259: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8260: 	    $courseid=$tmp_courseid;
                   8261: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8262: 	    ($name)=&get_env_multiple('form.grade_username');
                   8263: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8264: 	}
                   8265:     }
                   8266:     if (!$passedsymb) {
                   8267: 	$symb=&symbread();
                   8268:     } else {
                   8269: 	$symb=$passedsymb;
                   8270:     }
                   8271:     $courseid=$env{'request.course.id'};
                   8272:     $domain=$env{'user.domain'};
                   8273:     $name=$env{'user.name'};
                   8274:     if ($name eq 'public' && $domain eq 'public') {
                   8275: 	if (!defined($env{'form.username'})) {
                   8276: 	    $env{'form.username'}.=time.rand(10000000);
                   8277: 	}
                   8278: 	$name.=$env{'form.username'};
                   8279:     }
                   8280:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8281: 
                   8282: }
                   8283: 
1.36      albertel 8284: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8285: # returns either the contents of the file or 
                   8286: # -1 if the file doesn't exist
1.481     raeburn  8287: #
                   8288: # if the target is a file that was uploaded via DOCS, 
                   8289: # a check will be made to see if a current copy exists on the local server,
                   8290: # if it does this will be served, otherwise a copy will be retrieved from
                   8291: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8292: # the local server.   
1.472     albertel 8293: 
1.36      albertel 8294: sub getfile {
1.538     albertel 8295:     my ($file) = @_;
1.609     banghart 8296:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8297:     &repcopy($file);
                   8298:     return &readfile($file);
                   8299: }
                   8300: 
                   8301: sub repcopy_userfile {
                   8302:     my ($file)=@_;
1.609     banghart 8303:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8304:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8305:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8306: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8307:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8308:     if (-e "$file") {
1.828     www      8309: # we already have a local copy, check it out
1.538     albertel 8310: 	my @fileinfo = stat($file);
1.828     www      8311: 	my $rtncode;
                   8312: 	my $info;
1.538     albertel 8313: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8314: 	if ($lwpresp ne 'ok') {
1.828     www      8315: # there is no such file anymore, even though we had a local copy
1.482     albertel 8316: 	    if ($rtncode eq '404') {
1.538     albertel 8317: 		unlink($file);
1.482     albertel 8318: 	    }
                   8319: 	    return -1;
                   8320: 	}
                   8321: 	if ($info < $fileinfo[9]) {
1.828     www      8322: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8323: 	    return 'ok';
1.828     www      8324: 	} else {
                   8325: # the file is outdated, get rid of it
                   8326: 	    unlink($file);
1.482     albertel 8327: 	}
1.828     www      8328:     }
                   8329: # one way or the other, at this point, we don't have the file
                   8330: # construct the correct path for the file
                   8331:     my @parts = ($cdom,$cnum); 
                   8332:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8333: 	push @parts, split(/\//,$1);
                   8334:     }
                   8335:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8336:     foreach my $part (@parts) {
                   8337: 	$path .= '/'.$part;
                   8338: 	if (!-e $path) {
                   8339: 	    mkdir($path,0770);
1.482     albertel 8340: 	}
                   8341:     }
1.828     www      8342: # now the path exists for sure
                   8343: # get a user agent
                   8344:     my $ua=new LWP::UserAgent;
                   8345:     my $transferfile=$file.'.in.transfer';
                   8346: # FIXME: this should flock
                   8347:     if (-e $transferfile) { return 'ok'; }
                   8348:     my $request;
                   8349:     $uri=~s/^\///;
1.980     raeburn  8350:     my $homeserver = &homeserver($cnum,$cdom);
                   8351:     my $protocol = $protocol{$homeserver};
                   8352:     $protocol = 'http' if ($protocol ne 'https');
                   8353:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8354:     my $response=$ua->request($request,$transferfile);
                   8355: # did it work?
                   8356:     if ($response->is_error()) {
                   8357: 	unlink($transferfile);
                   8358: 	&logthis("Userfile repcopy failed for $uri");
                   8359: 	return -1;
                   8360:     }
                   8361: # worked, rename the transfer file
                   8362:     rename($transferfile,$file);
1.607     raeburn  8363:     return 'ok';
1.481     raeburn  8364: }
                   8365: 
1.517     albertel 8366: sub tokenwrapper {
                   8367:     my $uri=shift;
1.980     raeburn  8368:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8369:     $uri=~s|^/||;
1.620     albertel 8370:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8371:     my $token=$1;
1.552     albertel 8372:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8373:     if ($udom && $uname && $file) {
                   8374: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8375:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8376:         my $homeserver = &homeserver($uname,$udom);
                   8377:         my $protocol = $protocol{$homeserver};
                   8378:         $protocol = 'http' if ($protocol ne 'https');
                   8379:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8380:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8381:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8382:     } else {
                   8383:         return '/adm/notfound.html';
                   8384:     }
                   8385: }
                   8386: 
1.828     www      8387: # call with reqtype HEAD: get last modification time
                   8388: # call with reqtype GET: get the file contents
                   8389: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8390: #
1.481     raeburn  8391: sub getuploaded {
                   8392:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8393:     $uri=~s/^\///;
1.980     raeburn  8394:     my $homeserver = &homeserver($cnum,$cdom);
                   8395:     my $protocol = $protocol{$homeserver};
                   8396:     $protocol = 'http' if ($protocol ne 'https');
                   8397:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8398:     my $ua=new LWP::UserAgent;
                   8399:     my $request=new HTTP::Request($reqtype,$uri);
                   8400:     my $response=$ua->request($request);
                   8401:     $$rtncode = $response->code;
1.482     albertel 8402:     if (! $response->is_success()) {
                   8403: 	return 'failed';
                   8404:     }      
                   8405:     if ($reqtype eq 'HEAD') {
1.486     www      8406: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8407:     } elsif ($reqtype eq 'GET') {
                   8408: 	$$info = $response->content;
1.472     albertel 8409:     }
1.482     albertel 8410:     return 'ok';
1.36      albertel 8411: }
                   8412: 
1.481     raeburn  8413: sub readfile {
                   8414:     my $file = shift;
                   8415:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8416:     my $fh;
                   8417:     open($fh,"<$file");
                   8418:     my $a='';
1.800     albertel 8419:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8420:     return $a;
                   8421: }
                   8422: 
1.36      albertel 8423: sub filelocation {
1.590     banghart 8424:     my ($dir,$file) = @_;
                   8425:     my $location;
                   8426:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8427: 
                   8428:     if ($file =~ m-^/adm/-) {
                   8429: 	$file=~s-^/adm/wrapper/-/-;
                   8430: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8431:     }
1.882     albertel 8432: 
1.590     banghart 8433:     if ($file=~m:^/~:) { # is a contruction space reference
                   8434:         $location = $file;
                   8435:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8436:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8437: 	# is a correct contruction space reference
                   8438:         $location = $file;
1.956     raeburn  8439:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8440:         $location = $file;
1.609     banghart 8441:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8442:         my ($udom,$uname,$filename)=
1.811     albertel 8443:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8444:         my $home=&homeserver($uname,$udom);
                   8445:         my $is_me=0;
                   8446:         my @ids=&current_machine_ids();
                   8447:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8448:         if ($is_me) {
1.955     raeburn  8449:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8450:         } else {
                   8451:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8452:   	      $udom.'/'.$uname.'/'.$filename;
                   8453:         }
1.882     albertel 8454:     } elsif ($file =~ m-^/adm/-) {
                   8455: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8456:     } else {
                   8457:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8458:         $file=~s:^/res/:/:;
                   8459:         if ( !( $file =~ m:^/:) ) {
                   8460:             $location = $dir. '/'.$file;
                   8461:         } else {
                   8462:             $location = '/home/httpd/html/res'.$file;
                   8463:         }
1.59      albertel 8464:     }
1.590     banghart 8465:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8466:     while ($location=~m{/\.\./}) {
                   8467: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8468: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8469: 	} else {
                   8470: 	    $location=~ s{/\.\./}{/}g;
                   8471: 	}
                   8472:     } #remove dir/..
1.590     banghart 8473:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8474:     return $location;
1.46      www      8475: }
1.36      albertel 8476: 
1.46      www      8477: sub hreflocation {
                   8478:     my ($dir,$file)=@_;
1.980     raeburn  8479:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8480: 	$file=filelocation($dir,$file);
1.700     albertel 8481:     } elsif ($file=~m-^/adm/-) {
                   8482: 	$file=~s-^/adm/wrapper/-/-;
                   8483: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8484:     }
                   8485:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8486: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8487:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8488: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8489:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8490: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8491: 	    -/uploaded/$1/$2/-x;
1.46      www      8492:     }
1.913     albertel 8493:     if ($file=~ m{^/userfiles/}) {
                   8494: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8495:     }
1.462     albertel 8496:     return $file;
1.465     albertel 8497: }
                   8498: 
                   8499: sub current_machine_domains {
1.853     albertel 8500:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8501: }
                   8502: 
                   8503: sub machine_domains {
                   8504:     my ($hostname) = @_;
1.465     albertel 8505:     my @domains;
1.838     albertel 8506:     my %hostname = &all_hostnames();
1.465     albertel 8507:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8508: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8509: 	if ($hostname eq $name) {
1.844     albertel 8510: 	    push(@domains,&host_domain($id));
1.465     albertel 8511: 	}
                   8512:     }
                   8513:     return @domains;
                   8514: }
                   8515: 
                   8516: sub current_machine_ids {
1.853     albertel 8517:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8518: }
                   8519: 
                   8520: sub machine_ids {
                   8521:     my ($hostname) = @_;
                   8522:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8523:     my @ids;
1.888     albertel 8524:     my %name_to_host = &all_names();
1.889     albertel 8525:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8526: 	return @{ $name_to_host{$hostname} };
                   8527:     }
                   8528:     return;
1.31      www      8529: }
                   8530: 
1.824     raeburn  8531: sub additional_machine_domains {
                   8532:     my @domains;
                   8533:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8534:     while( my $line = <$fh>) {
                   8535:         $line =~ s/\s//g;
                   8536:         push(@domains,$line);
                   8537:     }
                   8538:     return @domains;
                   8539: }
                   8540: 
                   8541: sub default_login_domain {
                   8542:     my $domain = $perlvar{'lonDefDomain'};
                   8543:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8544:     foreach my $posdom (&current_machine_domains(),
                   8545:                         &additional_machine_domains()) {
                   8546:         if (lc($posdom) eq lc($testdomain)) {
                   8547:             $domain=$posdom;
                   8548:             last;
                   8549:         }
                   8550:     }
                   8551:     return $domain;
                   8552: }
                   8553: 
1.31      www      8554: # ------------------------------------------------------------- Declutters URLs
                   8555: 
                   8556: sub declutter {
                   8557:     my $thisfn=shift;
1.569     albertel 8558:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8559:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8560:     $thisfn=~s/^\///;
1.697     albertel 8561:     $thisfn=~s|^adm/wrapper/||;
                   8562:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8563:     $thisfn=~s/^res\///;
1.235     www      8564:     $thisfn=~s/\?.+$//;
1.268     www      8565:     return $thisfn;
                   8566: }
                   8567: 
                   8568: # ------------------------------------------------------------- Clutter up URLs
                   8569: 
                   8570: sub clutter {
                   8571:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8572:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8573: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8574:        $thisfn='/res'.$thisfn; 
                   8575:     }
1.694     albertel 8576:     if ($thisfn !~m|/adm|) {
1.695     albertel 8577: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8578: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8579: 	} else {
                   8580: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8581: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8582: 	    if ($embstyle eq 'ssi'
                   8583: 		|| ($embstyle eq 'hdn')
                   8584: 		|| ($embstyle eq 'rat')
                   8585: 		|| ($embstyle eq 'prv')
                   8586: 		|| ($embstyle eq 'ign')) {
                   8587: 		#do nothing with these
                   8588: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8589: 		|| ($embstyle eq 'emb')
                   8590: 		|| ($embstyle eq 'wrp')) {
                   8591: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8592: 	    } elsif ($embstyle eq 'unk'
                   8593: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8594: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8595: 	    } else {
1.718     www      8596: #		&logthis("Got a blank emb style");
1.695     albertel 8597: 	    }
1.694     albertel 8598: 	}
                   8599:     }
1.31      www      8600:     return $thisfn;
1.12      www      8601: }
                   8602: 
1.787     albertel 8603: sub clutter_with_no_wrapper {
                   8604:     my $uri = &clutter(shift);
                   8605:     if ($uri =~ m-^/adm/-) {
                   8606: 	$uri =~ s-^/adm/wrapper/-/-;
                   8607: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8608:     }
                   8609:     return $uri;
                   8610: }
                   8611: 
1.557     albertel 8612: sub freeze_escape {
                   8613:     my ($value)=@_;
                   8614:     if (ref($value)) {
                   8615: 	$value=&nfreeze($value);
                   8616: 	return '__FROZEN__'.&escape($value);
                   8617:     }
                   8618:     return &escape($value);
                   8619: }
                   8620: 
1.11      www      8621: 
1.557     albertel 8622: sub thaw_unescape {
                   8623:     my ($value)=@_;
                   8624:     if ($value =~ /^__FROZEN__/) {
                   8625: 	substr($value,0,10,undef);
                   8626: 	$value=&unescape($value);
                   8627: 	return &thaw($value);
                   8628:     }
                   8629:     return &unescape($value);
                   8630: }
                   8631: 
1.436     albertel 8632: sub correct_line_ends {
                   8633:     my ($result)=@_;
                   8634:     $$result =~s/\r\n/\n/mg;
                   8635:     $$result =~s/\r/\n/mg;
1.415     albertel 8636: }
1.1       albertel 8637: # ================================================================ Main Program
                   8638: 
1.184     www      8639: sub goodbye {
1.204     albertel 8640:    &logthis("Starting Shut down");
1.443     albertel 8641: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8642:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8643: #converted
1.599     albertel 8644: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8645:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8646: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8647: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8648: #1.1 only
1.870     albertel 8649: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8650: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8651: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8652: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8653:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8654:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8655:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8656:    &flushcourselogs();
                   8657:    &logthis("Shutting down");
                   8658: }
                   8659: 
1.852     albertel 8660: sub get_dns {
1.869     albertel 8661:     my ($url,$func,$ignore_cache) = @_;
                   8662:     if (!$ignore_cache) {
                   8663: 	my ($content,$cached)=
                   8664: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8665: 	if ($cached) {
                   8666: 	    &$func($content);
                   8667: 	    return;
                   8668: 	}
                   8669:     }
                   8670: 
                   8671:     my %alldns;
1.852     albertel 8672:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8673:     foreach my $dns (<$config>) {
                   8674: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8675:         my $line = $1;
                   8676:         my ($host,$protocol) = split(/:/,$line);
                   8677:         if ($protocol ne 'https') {
                   8678:             $protocol = 'http';
                   8679:         }
                   8680: 	$alldns{$host} = $protocol;
1.869     albertel 8681:     }
                   8682:     while (%alldns) {
                   8683: 	my ($dns) = keys(%alldns);
1.852     albertel 8684: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8685: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8686: 	my $response=$ua->request($request);
1.979     raeburn  8687:         delete($alldns{$dns});
1.852     albertel 8688: 	next if ($response->is_error());
                   8689: 	my @content = split("\n",$response->content);
1.869     albertel 8690: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8691: 	&$func(\@content);
1.869     albertel 8692: 	return;
1.852     albertel 8693:     }
                   8694:     close($config);
1.871     albertel 8695:     my $which = (split('/',$url))[3];
                   8696:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8697:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8698:     my @content = <$config>;
                   8699:     &$func(\@content);
                   8700:     return;
1.852     albertel 8701: }
1.327     albertel 8702: # ------------------------------------------------------------ Read domain file
                   8703: {
1.852     albertel 8704:     my $loaded;
1.846     albertel 8705:     my %domain;
                   8706: 
1.852     albertel 8707:     sub parse_domain_tab {
                   8708: 	my ($lines) = @_;
                   8709: 	foreach my $line (@$lines) {
                   8710: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8711: 
1.846     albertel 8712: 	    chomp($line);
1.852     albertel 8713: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8714: 	    my %this_domain;
                   8715: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8716: 			       'lang_def', 'city', 'longi', 'lati',
                   8717: 			       'primary') {
                   8718: 		$this_domain{$field} = shift(@elements);
                   8719: 	    }
                   8720: 	    $domain{$name} = \%this_domain;
1.852     albertel 8721: 	}
                   8722:     }
1.864     albertel 8723: 
                   8724:     sub reset_domain_info {
                   8725: 	undef($loaded);
                   8726: 	undef(%domain);
                   8727:     }
                   8728: 
1.852     albertel 8729:     sub load_domain_tab {
1.869     albertel 8730: 	my ($ignore_cache) = @_;
                   8731: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8732: 	my $fh;
                   8733: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8734: 	    my @lines = <$fh>;
                   8735: 	    &parse_domain_tab(\@lines);
1.448     albertel 8736: 	}
1.852     albertel 8737: 	close($fh);
                   8738: 	$loaded = 1;
1.327     albertel 8739:     }
1.846     albertel 8740: 
                   8741:     sub domain {
1.852     albertel 8742: 	&load_domain_tab() if (!$loaded);
                   8743: 
1.846     albertel 8744: 	my ($name,$what) = @_;
                   8745: 	return if ( !exists($domain{$name}) );
                   8746: 
                   8747: 	if (!$what) {
                   8748: 	    return $domain{$name}{'description'};
                   8749: 	}
                   8750: 	return $domain{$name}{$what};
                   8751:     }
1.974     raeburn  8752: 
                   8753:     sub domain_info {
                   8754:         &load_domain_tab() if (!$loaded);
                   8755:         return %domain;
                   8756:     }
                   8757: 
1.327     albertel 8758: }
                   8759: 
                   8760: 
1.1       albertel 8761: # ------------------------------------------------------------- Read hosts file
                   8762: {
1.838     albertel 8763:     my %hostname;
1.844     albertel 8764:     my %hostdom;
1.845     albertel 8765:     my %libserv;
1.852     albertel 8766:     my $loaded;
1.888     albertel 8767:     my %name_to_host;
1.852     albertel 8768: 
                   8769:     sub parse_hosts_tab {
                   8770: 	my ($file) = @_;
                   8771: 	foreach my $configline (@$file) {
                   8772: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8773: 	    next if ($configline =~ /^\^/);
                   8774: 	    chomp($configline);
1.968     raeburn  8775: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8776: 	    $name=~s/\s//g;
                   8777: 	    if ($id && $domain && $role && $name) {
                   8778: 		$hostname{$id}=$name;
1.888     albertel 8779: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8780: 		$hostdom{$id}=$domain;
                   8781: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8782:                 if (defined($protocol)) {
                   8783:                     if ($protocol eq 'https') {
                   8784:                         $protocol{$id} = $protocol;
                   8785:                     } else {
                   8786:                         $protocol{$id} = 'http'; 
                   8787:                     }
1.968     raeburn  8788:                 } else {
1.969     raeburn  8789:                     $protocol{$id} = 'http';
1.968     raeburn  8790:                 }
1.852     albertel 8791: 	    }
                   8792: 	}
                   8793:     }
1.864     albertel 8794:     
                   8795:     sub reset_hosts_info {
1.897     albertel 8796: 	&purge_remembered();
1.864     albertel 8797: 	&reset_domain_info();
                   8798: 	&reset_hosts_ip_info();
1.892     albertel 8799: 	undef(%name_to_host);
1.864     albertel 8800: 	undef(%hostname);
                   8801: 	undef(%hostdom);
                   8802: 	undef(%libserv);
                   8803: 	undef($loaded);
                   8804:     }
1.1       albertel 8805: 
1.852     albertel 8806:     sub load_hosts_tab {
1.869     albertel 8807: 	my ($ignore_cache) = @_;
                   8808: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8809: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8810: 	my @config = <$config>;
                   8811: 	&parse_hosts_tab(\@config);
                   8812: 	close($config);
                   8813: 	$loaded=1;
1.1       albertel 8814:     }
1.852     albertel 8815: 
1.838     albertel 8816:     sub hostname {
1.852     albertel 8817: 	&load_hosts_tab() if (!$loaded);
                   8818: 
1.838     albertel 8819: 	my ($lonid) = @_;
                   8820: 	return $hostname{$lonid};
                   8821:     }
1.845     albertel 8822: 
1.838     albertel 8823:     sub all_hostnames {
1.852     albertel 8824: 	&load_hosts_tab() if (!$loaded);
                   8825: 
1.838     albertel 8826: 	return %hostname;
                   8827:     }
1.845     albertel 8828: 
1.888     albertel 8829:     sub all_names {
                   8830: 	&load_hosts_tab() if (!$loaded);
                   8831: 
                   8832: 	return %name_to_host;
                   8833:     }
                   8834: 
1.974     raeburn  8835:     sub all_host_domain {
                   8836:         &load_hosts_tab() if (!$loaded);
                   8837:         return %hostdom;
                   8838:     }
                   8839: 
1.845     albertel 8840:     sub is_library {
1.852     albertel 8841: 	&load_hosts_tab() if (!$loaded);
                   8842: 
1.845     albertel 8843: 	return exists($libserv{$_[0]});
                   8844:     }
                   8845: 
                   8846:     sub all_library {
1.852     albertel 8847: 	&load_hosts_tab() if (!$loaded);
                   8848: 
1.845     albertel 8849: 	return %libserv;
                   8850:     }
                   8851: 
1.841     albertel 8852:     sub get_servers {
1.852     albertel 8853: 	&load_hosts_tab() if (!$loaded);
                   8854: 
1.841     albertel 8855: 	my ($domain,$type) = @_;
                   8856: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8857: 	                                          : %hostname;
                   8858: 	my %result;
1.842     albertel 8859: 	if (ref($domain) eq 'ARRAY') {
                   8860: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8861: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8862: 		    $result{$host} = $hostname;
                   8863: 		}
                   8864: 	    }
                   8865: 	} else {
                   8866: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8867: 		if ($hostdom{$host} eq $domain) {
                   8868: 		    $result{$host} = $hostname;
                   8869: 		}
1.841     albertel 8870: 	    }
                   8871: 	}
                   8872: 	return %result;
                   8873:     }
1.845     albertel 8874: 
1.844     albertel 8875:     sub host_domain {
1.852     albertel 8876: 	&load_hosts_tab() if (!$loaded);
                   8877: 
1.844     albertel 8878: 	my ($lonid) = @_;
                   8879: 	return $hostdom{$lonid};
                   8880:     }
                   8881: 
1.841     albertel 8882:     sub all_domains {
1.852     albertel 8883: 	&load_hosts_tab() if (!$loaded);
                   8884: 
1.841     albertel 8885: 	my %seen;
                   8886: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8887: 	return @uniq;
                   8888:     }
1.1       albertel 8889: }
                   8890: 
1.847     albertel 8891: { 
                   8892:     my %iphost;
1.856     albertel 8893:     my %name_to_ip;
                   8894:     my %lonid_to_ip;
1.869     albertel 8895: 
1.847     albertel 8896:     sub get_hosts_from_ip {
                   8897: 	my ($ip) = @_;
                   8898: 	my %iphosts = &get_iphost();
                   8899: 	if (ref($iphosts{$ip})) {
                   8900: 	    return @{$iphosts{$ip}};
                   8901: 	}
                   8902: 	return;
1.839     albertel 8903:     }
1.864     albertel 8904:     
                   8905:     sub reset_hosts_ip_info {
                   8906: 	undef(%iphost);
                   8907: 	undef(%name_to_ip);
                   8908: 	undef(%lonid_to_ip);
                   8909:     }
1.856     albertel 8910: 
                   8911:     sub get_host_ip {
                   8912: 	my ($lonid) = @_;
                   8913: 	if (exists($lonid_to_ip{$lonid})) {
                   8914: 	    return $lonid_to_ip{$lonid};
                   8915: 	}
                   8916: 	my $name=&hostname($lonid);
                   8917:    	my $ip = gethostbyname($name);
                   8918: 	return if (!$ip || length($ip) ne 4);
                   8919: 	$ip=inet_ntoa($ip);
                   8920: 	$name_to_ip{$name}   = $ip;
                   8921: 	$lonid_to_ip{$lonid} = $ip;
                   8922: 	return $ip;
                   8923:     }
1.847     albertel 8924:     
                   8925:     sub get_iphost {
1.869     albertel 8926: 	my ($ignore_cache) = @_;
1.894     albertel 8927: 
1.869     albertel 8928: 	if (!$ignore_cache) {
                   8929: 	    if (%iphost) {
                   8930: 		return %iphost;
                   8931: 	    }
                   8932: 	    my ($ip_info,$cached)=
                   8933: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8934: 	    if ($cached) {
                   8935: 		%iphost      = %{$ip_info->[0]};
                   8936: 		%name_to_ip  = %{$ip_info->[1]};
                   8937: 		%lonid_to_ip = %{$ip_info->[2]};
                   8938: 		return %iphost;
                   8939: 	    }
                   8940: 	}
1.894     albertel 8941: 
                   8942: 	# get yesterday's info for fallback
                   8943: 	my %old_name_to_ip;
                   8944: 	my ($ip_info,$cached)=
                   8945: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8946: 	if ($cached) {
                   8947: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8948: 	}
                   8949: 
1.888     albertel 8950: 	my %name_to_host = &all_names();
                   8951: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8952: 	    my $ip;
                   8953: 	    if (!exists($name_to_ip{$name})) {
                   8954: 		$ip = gethostbyname($name);
                   8955: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8956: 		    if (defined($old_name_to_ip{$name})) {
                   8957: 			$ip = $old_name_to_ip{$name};
                   8958: 			&logthis("Can't find $name defaulting to old $ip");
                   8959: 		    } else {
                   8960: 			&logthis("Name $name no IP found");
                   8961: 			next;
                   8962: 		    }
                   8963: 		} else {
                   8964: 		    $ip=inet_ntoa($ip);
1.847     albertel 8965: 		}
                   8966: 		$name_to_ip{$name} = $ip;
                   8967: 	    } else {
                   8968: 		$ip = $name_to_ip{$name};
1.653     albertel 8969: 	    }
1.888     albertel 8970: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8971: 		$lonid_to_ip{$id} = $ip;
                   8972: 	    }
                   8973: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8974: 	}
1.869     albertel 8975: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8976: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8977: 				      48*60*60);
1.869     albertel 8978: 
1.847     albertel 8979: 	return %iphost;
1.598     albertel 8980:     }
                   8981: }
                   8982: 
1.862     albertel 8983: BEGIN {
                   8984: 
                   8985: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8986:     unless ($readit) {
                   8987: {
                   8988:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8989:     %perlvar = (%perlvar,%{$configvars});
                   8990: }
                   8991: 
                   8992: 
1.1       albertel 8993: # ------------------------------------------------------ Read spare server file
                   8994: {
1.448     albertel 8995:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8996: 
                   8997:     while (my $configline=<$config>) {
                   8998:        chomp($configline);
1.284     matthew  8999:        if ($configline) {
1.784     albertel 9000: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9001: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9002: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9003:        }
                   9004:     }
1.448     albertel 9005:     close($config);
1.1       albertel 9006: }
1.11      www      9007: # ------------------------------------------------------------ Read permissions
                   9008: {
1.448     albertel 9009:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9010: 
                   9011:     while (my $configline=<$config>) {
1.448     albertel 9012: 	chomp($configline);
                   9013: 	if ($configline) {
                   9014: 	    my ($role,$perm)=split(/ /,$configline);
                   9015: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9016: 	}
1.11      www      9017:     }
1.448     albertel 9018:     close($config);
1.11      www      9019: }
                   9020: 
                   9021: # -------------------------------------------- Read plain texts for permissions
                   9022: {
1.448     albertel 9023:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9024: 
                   9025:     while (my $configline=<$config>) {
1.448     albertel 9026: 	chomp($configline);
                   9027: 	if ($configline) {
1.742     raeburn  9028: 	    my ($short,@plain)=split(/:/,$configline);
                   9029:             %{$prp{$short}} = ();
                   9030: 	    if (@plain > 0) {
                   9031:                 $prp{$short}{'std'} = $plain[0];
                   9032:                 for (my $i=1; $i<@plain; $i++) {
                   9033:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9034:                 }
                   9035:             }
1.448     albertel 9036: 	}
1.135     www      9037:     }
1.448     albertel 9038:     close($config);
1.135     www      9039: }
                   9040: 
                   9041: # ---------------------------------------------------------- Read package table
                   9042: {
1.448     albertel 9043:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9044: 
                   9045:     while (my $configline=<$config>) {
1.483     albertel 9046: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9047: 	chomp($configline);
                   9048: 	my ($short,$plain)=split(/:/,$configline);
                   9049: 	my ($pack,$name)=split(/\&/,$short);
                   9050: 	if ($plain ne '') {
                   9051: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9052: 	    $packagetab{$short}=$plain; 
                   9053: 	}
1.11      www      9054:     }
1.448     albertel 9055:     close($config);
1.329     matthew  9056: }
                   9057: 
                   9058: # ------------- set up temporary directory
                   9059: {
                   9060:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9061: 
1.11      www      9062: }
                   9063: 
1.794     albertel 9064: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9065: 				'compress_threshold'=> 20_000,
                   9066:  			        });
1.185     www      9067: 
1.281     www      9068: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9069: $dumpcount=0;
1.958     www      9070: $locknum=0;
1.22      www      9071: 
1.163     harris41 9072: &logtouch();
1.672     albertel 9073: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9074: $readit=1;
1.564     albertel 9075:     {
                   9076: 	use integer;
                   9077: 	my $test=(2**32)+1;
1.568     albertel 9078: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9079: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9080:     }
1.195     www      9081: }
1.1       albertel 9082: }
1.179     www      9083: 
1.1       albertel 9084: 1;
1.191     harris41 9085: __END__
                   9086: 
1.243     albertel 9087: =pod
                   9088: 
1.191     harris41 9089: =head1 NAME
                   9090: 
1.243     albertel 9091: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9092: 
                   9093: =head1 SYNOPSIS
                   9094: 
1.243     albertel 9095: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9096: 
                   9097:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9098: 
1.243     albertel 9099: Common parameters:
                   9100: 
                   9101: =over 4
                   9102: 
                   9103: =item *
                   9104: 
                   9105: $uname : an internal username (if $cname expecting a course Id specifically)
                   9106: 
                   9107: =item *
                   9108: 
                   9109: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9110: 
                   9111: =item *
                   9112: 
                   9113: $symb : a resource instance identifier
                   9114: 
                   9115: =item *
                   9116: 
                   9117: $namespace : the name of a .db file that contains the data needed or
                   9118: being set.
                   9119: 
                   9120: =back
                   9121: 
1.394     bowersj2 9122: =head1 OVERVIEW
1.191     harris41 9123: 
1.394     bowersj2 9124: lonnet provides subroutines which interact with the
                   9125: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9126: about classes, users, and resources.
1.243     albertel 9127: 
                   9128: For many of these objects you can also use this to store data about
                   9129: them or modify them in various ways.
1.191     harris41 9130: 
1.394     bowersj2 9131: =head2 Symbs
1.191     harris41 9132: 
1.394     bowersj2 9133: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9134: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9135: map, the resource number of the resource in the map, and the URL of
                   9136: the resource itself. The latter is somewhat redundant, but might help
                   9137: if maps change.
                   9138: 
                   9139: An example is
                   9140: 
                   9141:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9142: 
                   9143: The respective map entry is
                   9144: 
                   9145:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9146:   title="Problem 2">
                   9147:  </resource>
                   9148: 
                   9149: Symbs are used by the random number generator, as well as to store and
                   9150: restore data specific to a certain instance of for example a problem.
                   9151: 
                   9152: =head2 Storing And Retrieving Data
                   9153: 
                   9154: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9155: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9156: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9157: is is the non-critical message twin of cstore. These functions are for
                   9158: handlers to store a perl hash to a user's permanent data space in an
                   9159: easy manner, and to retrieve it again on another call. It is expected
                   9160: that a handler would use this once at the beginning to retrieve data,
                   9161: and then again once at the end to send only the new data back.
                   9162: 
                   9163: The data is stored in the user's data directory on the user's
                   9164: homeserver under the ID of the course.
                   9165: 
                   9166: The hash that is returned by restore will have all of the previous
                   9167: value for all of the elements of the hash.
                   9168: 
                   9169: Example:
                   9170: 
                   9171:  #creating a hash
                   9172:  my %hash;
                   9173:  $hash{'foo'}='bar';
                   9174: 
                   9175:  #storing it
                   9176:  &Apache::lonnet::cstore(\%hash);
                   9177: 
                   9178:  #changing a value
                   9179:  $hash{'foo'}='notbar';
                   9180: 
                   9181:  #adding a new value
                   9182:  $hash{'bar'}='foo';
                   9183:  &Apache::lonnet::cstore(\%hash);
                   9184: 
                   9185:  #retrieving the hash
                   9186:  my %history=&Apache::lonnet::restore();
                   9187: 
                   9188:  #print the hash
                   9189:  foreach my $key (sort(keys(%history))) {
                   9190:    print("\%history{$key} = $history{$key}");
                   9191:  }
                   9192: 
                   9193: Will print out:
1.191     harris41 9194: 
1.394     bowersj2 9195:  %history{1:foo} = bar
                   9196:  %history{1:keys} = foo:timestamp
                   9197:  %history{1:timestamp} = 990455579
                   9198:  %history{2:bar} = foo
                   9199:  %history{2:foo} = notbar
                   9200:  %history{2:keys} = foo:bar:timestamp
                   9201:  %history{2:timestamp} = 990455580
                   9202:  %history{bar} = foo
                   9203:  %history{foo} = notbar
                   9204:  %history{timestamp} = 990455580
                   9205:  %history{version} = 2
                   9206: 
                   9207: Note that the special hash entries C<keys>, C<version> and
                   9208: C<timestamp> were added to the hash. C<version> will be equal to the
                   9209: total number of versions of the data that have been stored. The
                   9210: C<timestamp> attribute will be the UNIX time the hash was
                   9211: stored. C<keys> is available in every historical section to list which
                   9212: keys were added or changed at a specific historical revision of a
                   9213: hash.
                   9214: 
                   9215: B<Warning>: do not store the hash that restore returns directly. This
                   9216: will cause a mess since it will restore the historical keys as if the
                   9217: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9218: 
1.394     bowersj2 9219: Calling convention:
1.191     harris41 9220: 
1.394     bowersj2 9221:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9222:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9223: 
1.394     bowersj2 9224: For more detailed information, see lonnet specific documentation.
1.191     harris41 9225: 
1.394     bowersj2 9226: =head1 RETURN MESSAGES
1.191     harris41 9227: 
1.394     bowersj2 9228: =over 4
1.191     harris41 9229: 
1.394     bowersj2 9230: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9231: 
1.394     bowersj2 9232: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9233: when the connection is brought back up
1.191     harris41 9234: 
1.394     bowersj2 9235: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9236: for later delivery
1.191     harris41 9237: 
1.967     bisitz   9238: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9239: 
1.394     bowersj2 9240: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9241: that was requested
1.191     harris41 9242: 
1.243     albertel 9243: =back
1.191     harris41 9244: 
1.243     albertel 9245: =head1 PUBLIC SUBROUTINES
1.191     harris41 9246: 
1.243     albertel 9247: =head2 Session Environment Functions
1.191     harris41 9248: 
1.243     albertel 9249: =over 4
1.191     harris41 9250: 
1.394     bowersj2 9251: =item * 
                   9252: X<appenv()>
1.949     raeburn  9253: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9254: the user envirnoment file, and will be restored for each access this
1.620     albertel 9255: user makes during this session, also modifies the %env for the current
1.949     raeburn  9256: process. Optional rolesarrayref - if defined contains a reference to an array
                   9257: of roles which are exempt from the restriction on modifying user.role entries 
                   9258: in the user's environment.db and in %env.    
1.191     harris41 9259: 
                   9260: =item *
1.394     bowersj2 9261: X<delenv()>
                   9262: B<delenv($regexp)>: removes all items from the session
                   9263: environment file that matches the regular expression in $regexp. The
1.620     albertel 9264: values are also delted from the current processes %env.
1.191     harris41 9265: 
1.795     albertel 9266: =item * get_env_multiple($name) 
                   9267: 
                   9268: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9269: values may be defined and end up as an array ref.
                   9270: 
                   9271: returns an array of values
                   9272: 
1.243     albertel 9273: =back
                   9274: 
                   9275: =head2 User Information
1.191     harris41 9276: 
1.243     albertel 9277: =over 4
1.191     harris41 9278: 
                   9279: =item *
1.394     bowersj2 9280: X<queryauthenticate()>
                   9281: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9282: authentication scheme
                   9283: 
                   9284: =item *
1.394     bowersj2 9285: X<authenticate()>
                   9286: B<authenticate($uname,$upass,$udom)>: try to
                   9287: authenticate user from domain's lib servers (first use the current
                   9288: one). C<$upass> should be the users password.
1.191     harris41 9289: 
                   9290: =item *
1.394     bowersj2 9291: X<homeserver()>
                   9292: B<homeserver($uname,$udom)>: find the server which has
                   9293: the user's directory and files (there must be only one), this caches
                   9294: the answer, and also caches if there is a borken connection.
1.191     harris41 9295: 
                   9296: =item *
1.394     bowersj2 9297: X<idget()>
                   9298: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9299: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9300: username, and only 1 username per ID in a specific domain) (returns
                   9301: hash: id=>name,id=>name)
1.191     harris41 9302: 
                   9303: =item *
1.394     bowersj2 9304: X<idrget()>
                   9305: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9306: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9307: 
                   9308: =item *
1.394     bowersj2 9309: X<idput()>
                   9310: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9311: 
                   9312: =item *
1.394     bowersj2 9313: X<rolesinit()>
                   9314: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9315: 
                   9316: =item *
1.551     albertel 9317: X<getsection()>
                   9318: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9319: course $cname, return section name/number or '' for "not in course"
                   9320: and '-1' for "no section"
                   9321: 
                   9322: =item *
1.394     bowersj2 9323: X<userenvironment()>
                   9324: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9325: passed in @what from the requested user's environment, returns a hash
                   9326: 
1.858     raeburn  9327: =item * 
                   9328: X<userlog_query()>
1.859     albertel 9329: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9330: activity.log file. %filters defines filters applied when parsing the
                   9331: log file. These can be start or end timestamps, or the type of action
                   9332: - log to look for Login or Logout events, check for Checkin or
                   9333: Checkout, role for role selection. The response is in the form
                   9334: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9335: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9336: 
1.243     albertel 9337: =back
                   9338: 
                   9339: =head2 User Roles
                   9340: 
                   9341: =over 4
                   9342: 
                   9343: =item *
                   9344: 
1.810     raeburn  9345: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9346:  F: full access
                   9347:  U,I,K: authentication modes (cxx only)
                   9348:  '': forbidden
                   9349:  1: user needs to choose course
                   9350:  2: browse allowed
1.766     albertel 9351:  A: passphrase authentication needed
1.243     albertel 9352: 
                   9353: =item *
                   9354: 
                   9355: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9356: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9357: and course level
                   9358: 
                   9359: =item *
                   9360: 
                   9361: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9362: explanation of a user role term
                   9363: 
1.832     raeburn  9364: =item *
                   9365: 
1.935     raeburn  9366: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9367: All arguments are optional. Returns a hash of a roles, either for
                   9368: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9369: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9370: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9371: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9372: For each key, value is set to colon-separated start and end times for
                   9373: the role.  If no username and domain are specified, will default to
1.934     raeburn  9374: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9375: of role statuses (active, future or previous), roles 
                   9376: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9377: to restrict the list of roles reported. If no array ref is 
                   9378: provided for types, will default to return only active roles.
1.834     albertel 9379: 
1.243     albertel 9380: =back
                   9381: 
                   9382: =head2 User Modification
                   9383: 
                   9384: =over 4
                   9385: 
                   9386: =item *
                   9387: 
1.957     raeburn  9388: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9389: user for the level given by URL.  Optional start and end dates (leave empty
                   9390: string or zero for "no date")
1.191     harris41 9391: 
                   9392: =item *
                   9393: 
1.243     albertel 9394: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9395: change a users, password, possible return values are: ok,
                   9396: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9397: refused
1.191     harris41 9398: 
                   9399: =item *
                   9400: 
1.243     albertel 9401: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9402: 
                   9403: =item *
                   9404: 
1.963     raeburn  9405: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9406:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9407: modify user
1.191     harris41 9408: 
                   9409: =item *
                   9410: 
1.286     matthew  9411: modifystudent
                   9412: 
1.957     raeburn  9413: modify a student's enrollment and identification information.
1.286     matthew  9414: The course id is resolved based on the current users environment.  
                   9415: This means the envoking user must be a course coordinator or otherwise
                   9416: associated with a course.
                   9417: 
1.297     matthew  9418: This call is essentially a wrapper for lonnet::modifyuser and
                   9419: lonnet::modify_student_enrollment
1.286     matthew  9420: 
                   9421: Inputs: 
                   9422: 
                   9423: =over 4
                   9424: 
1.957     raeburn  9425: =item B<$udom> Student's loncapa domain
1.286     matthew  9426: 
1.957     raeburn  9427: =item B<$uname> Student's loncapa login name
1.286     matthew  9428: 
1.964     bisitz   9429: =item B<$uid> Student/Employee ID
1.286     matthew  9430: 
1.957     raeburn  9431: =item B<$umode> Student's authentication mode
1.286     matthew  9432: 
1.957     raeburn  9433: =item B<$upass> Student's password
1.286     matthew  9434: 
1.957     raeburn  9435: =item B<$first> Student's first name
1.286     matthew  9436: 
1.957     raeburn  9437: =item B<$middle> Student's middle name
1.286     matthew  9438: 
1.957     raeburn  9439: =item B<$last> Student's last name
1.286     matthew  9440: 
1.957     raeburn  9441: =item B<$gene> Student's generation
1.286     matthew  9442: 
1.957     raeburn  9443: =item B<$usec> Student's section in course
1.286     matthew  9444: 
                   9445: =item B<$end> Unix time of the roles expiration
                   9446: 
                   9447: =item B<$start> Unix time of the roles start date
                   9448: 
                   9449: =item B<$forceid> If defined, allow $uid to be changed
                   9450: 
                   9451: =item B<$desiredhome> server to use as home server for student
                   9452: 
1.957     raeburn  9453: =item B<$email> Student's permanent e-mail address
                   9454: 
                   9455: =item B<$type> Type of enrollment (auto or manual)
                   9456: 
1.963     raeburn  9457: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9458: 
                   9459: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9460: 
1.963     raeburn  9461: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9462: 
1.963     raeburn  9463: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9464: 
1.963     raeburn  9465: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9466: 
1.286     matthew  9467: =back
1.297     matthew  9468: 
                   9469: =item *
                   9470: 
                   9471: modify_student_enrollment
                   9472: 
                   9473: Change a students enrollment status in a class.  The environment variable
                   9474: 'role.request.course' must be defined for this function to proceed.
                   9475: 
                   9476: Inputs:
                   9477: 
                   9478: =over 4
                   9479: 
                   9480: =item $udom, students domain
                   9481: 
                   9482: =item $uname, students name
                   9483: 
                   9484: =item $uid, students user id
                   9485: 
                   9486: =item $first, students first name
                   9487: 
                   9488: =item $middle
                   9489: 
                   9490: =item $last
                   9491: 
                   9492: =item $gene
                   9493: 
                   9494: =item $usec
                   9495: 
                   9496: =item $end
                   9497: 
                   9498: =item $start
                   9499: 
1.957     raeburn  9500: =item $type
                   9501: 
                   9502: =item $locktype
                   9503: 
                   9504: =item $cid
                   9505: 
                   9506: =item $selfenroll
                   9507: 
                   9508: =item $context
                   9509: 
1.297     matthew  9510: =back
                   9511: 
1.191     harris41 9512: 
                   9513: =item *
                   9514: 
1.243     albertel 9515: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9516: custom role; give a custom role to a user for the level given by URL.  Specify
                   9517: name and domain of role author, and role name
1.191     harris41 9518: 
                   9519: =item *
                   9520: 
1.243     albertel 9521: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9522: 
                   9523: =item *
                   9524: 
1.243     albertel 9525: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9526: 
                   9527: =back
                   9528: 
                   9529: =head2 Course Infomation
                   9530: 
                   9531: =over 4
1.191     harris41 9532: 
                   9533: =item *
                   9534: 
1.631     albertel 9535: coursedescription($courseid) : returns a hash of information about the
                   9536: specified course id, including all environment settings for the
                   9537: course, the description of the course will be in the hash under the
                   9538: key 'description'
1.191     harris41 9539: 
                   9540: =item *
                   9541: 
1.624     albertel 9542: resdata($name,$domain,$type,@which) : request for current parameter
                   9543: setting for a specific $type, where $type is either 'course' or 'user',
                   9544: @what should be a list of parameters to ask about. This routine caches
                   9545: answers for 5 minutes.
1.243     albertel 9546: 
1.877     foxr     9547: =item *
                   9548: 
                   9549: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9550: data base, returning a hash that is keyed by the resource name and has
                   9551: values that are the resource value.  I believe that the timestamps and
                   9552: versions are also returned.
                   9553: 
                   9554: 
1.243     albertel 9555: =back
                   9556: 
                   9557: =head2 Course Modification
                   9558: 
                   9559: =over 4
1.191     harris41 9560: 
                   9561: =item *
                   9562: 
1.243     albertel 9563: writecoursepref($courseid,%prefs) : write preferences (environment
                   9564: database) for a course
1.191     harris41 9565: 
                   9566: =item *
                   9567: 
1.243     albertel 9568: createcourse($udom,$description,$url) : make/modify course
                   9569: 
                   9570: =back
                   9571: 
                   9572: =head2 Resource Subroutines
                   9573: 
                   9574: =over 4
1.191     harris41 9575: 
                   9576: =item *
                   9577: 
1.243     albertel 9578: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9579: 
                   9580: =item *
                   9581: 
1.243     albertel 9582: repcopy($filename) : subscribes to the requested file, and attempts to
                   9583: replicate from the owning library server, Might return
1.607     raeburn  9584: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9585: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9586: resource. Expects the local filesystem pathname
                   9587: (/home/httpd/html/res/....)
                   9588: 
                   9589: =back
                   9590: 
                   9591: =head2 Resource Information
                   9592: 
                   9593: =over 4
1.191     harris41 9594: 
                   9595: =item *
                   9596: 
1.243     albertel 9597: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9598: a vairety of different possible values, $varname should be a request
                   9599: string, and the other parameters can be used to specify who and what
                   9600: one is asking about.
                   9601: 
                   9602: Possible values for $varname are environment.lastname (or other item
                   9603: from the envirnment hash), user.name (or someother aspect about the
                   9604: user), resource.0.maxtries (or some other part and parameter of a
                   9605: resource)
1.204     albertel 9606: 
                   9607: =item *
                   9608: 
1.243     albertel 9609: directcondval($number) : get current value of a condition; reads from a state
                   9610: string
1.204     albertel 9611: 
                   9612: =item *
                   9613: 
1.243     albertel 9614: condval($condidx) : value of condition index based on state
1.204     albertel 9615: 
                   9616: =item *
                   9617: 
1.243     albertel 9618: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9619: resource's metadata, $what should be either a specific key, or either
                   9620: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9621: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9622: 
                   9623: this function automatically caches all requests
1.191     harris41 9624: 
                   9625: =item *
                   9626: 
1.243     albertel 9627: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9628: network of library servers; returns file handle of where SQL and regex results
                   9629: will be stored for query
1.191     harris41 9630: 
                   9631: =item *
                   9632: 
1.243     albertel 9633: symbread($filename) : return symbolic list entry (filename argument optional);
                   9634: returns the data handle
1.191     harris41 9635: 
                   9636: =item *
                   9637: 
1.243     albertel 9638: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9639: a possible symb for the URL in $thisfn, and if is an encryypted
                   9640: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9641: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9642: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9643: 
1.191     harris41 9644: 
                   9645: =item *
                   9646: 
1.243     albertel 9647: symbclean($symb) : removes versions numbers from a symb, returns the
                   9648: cleaned symb
1.191     harris41 9649: 
                   9650: =item *
                   9651: 
1.243     albertel 9652: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9653: course map, user must be in a course for it to work.
1.191     harris41 9654: 
                   9655: =item *
                   9656: 
1.243     albertel 9657: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9658: 
                   9659: =item *
                   9660: 
1.243     albertel 9661: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9662: a random seed, all arguments are optional, if they aren't sent it uses the
                   9663: environment to derive them. Note: if symb isn't sent and it can't get one
                   9664: from &symbread it will use the current time as its return value
1.191     harris41 9665: 
                   9666: =item *
                   9667: 
1.243     albertel 9668: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9669: unfakeable, receipt
1.191     harris41 9670: 
                   9671: =item *
                   9672: 
1.620     albertel 9673: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9674: 
                   9675: =item *
                   9676: 
1.243     albertel 9677: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9678: 
                   9679: =item *
                   9680: 
1.243     albertel 9681: 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 9682: 
                   9683: =item *
                   9684: 
1.243     albertel 9685: 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 9686: 
                   9687: =item *
                   9688: 
1.243     albertel 9689: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9690: 
                   9691: =item *
                   9692: 
1.243     albertel 9693: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9694: forcing spreadsheet to reevaluate the resource scores next time.
                   9695: 
                   9696: =back
                   9697: 
                   9698: =head2 Storing/Retreiving Data
                   9699: 
                   9700: =over 4
1.191     harris41 9701: 
                   9702: =item *
                   9703: 
1.243     albertel 9704: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9705: for this url; hashref needs to be given and should be a \%hashname; the
                   9706: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9707: be derived from the env
1.191     harris41 9708: 
                   9709: =item *
                   9710: 
1.243     albertel 9711: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9712: uses critical subroutine
1.191     harris41 9713: 
                   9714: =item *
                   9715: 
1.243     albertel 9716: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9717: all args are optional
1.191     harris41 9718: 
                   9719: =item *
                   9720: 
1.717     albertel 9721: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9722: dumps the complete (or key matching regexp) namespace into a hash
                   9723: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9724: normally &store()ed into
                   9725: 
                   9726: $range should be either an integer '100' (give me the first 100
                   9727:                                            matching records)
                   9728:               or be  two integers sperated by a - with no spaces
                   9729:                  '30-50' (give me the 30th through the 50th matching
                   9730:                           records)
                   9731: 
                   9732: 
                   9733: =item *
                   9734: 
                   9735: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9736: replaces a &store() version of data with a replacement set of data
                   9737: for a particular resource in a namespace passed in the $storehash hash 
                   9738: reference
                   9739: 
                   9740: =item *
                   9741: 
1.243     albertel 9742: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9743: works very similar to store/cstore, but all data is stored in a
                   9744: temporary location and can be reset using tmpreset, $storehash should
                   9745: be a hash reference, returns nothing on success
1.191     harris41 9746: 
                   9747: =item *
                   9748: 
1.243     albertel 9749: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9750: similar to restore, but all data is stored in a temporary location and
                   9751: can be reset using tmpreset. Returns a hash of values on success,
                   9752: error string otherwise.
1.191     harris41 9753: 
                   9754: =item *
                   9755: 
1.243     albertel 9756: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9757: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9758: 
                   9759: =item *
                   9760: 
1.243     albertel 9761: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9762: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9763: 
                   9764: =item *
                   9765: 
1.243     albertel 9766: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9767: namesp ($udom and $uname are optional)
1.191     harris41 9768: 
                   9769: =item *
                   9770: 
1.702     albertel 9771: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9772: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9773: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9774: 
1.702     albertel 9775: $range should be either an integer '100' (give me the first 100
                   9776:                                            matching records)
                   9777:               or be  two integers sperated by a - with no spaces
                   9778:                  '30-50' (give me the 30th through the 50th matching
                   9779:                           records)
1.449     matthew  9780: =item *
                   9781: 
                   9782: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9783: $store can be a scalar, an array reference, or if the amount to be 
                   9784: incremented is > 1, a hash reference.
                   9785: 
                   9786: ($udom and $uname are optional)
1.191     harris41 9787: 
                   9788: =item *
                   9789: 
1.243     albertel 9790: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9791: ($udom and $uname are optional)
1.191     harris41 9792: 
                   9793: =item *
                   9794: 
1.243     albertel 9795: cput($namespace,$storehash,$udom,$uname) : critical put
                   9796: ($udom and $uname are optional)
1.191     harris41 9797: 
                   9798: =item *
                   9799: 
1.748     albertel 9800: newput($namespace,$storehash,$udom,$uname) :
                   9801: 
                   9802: Attempts to store the items in the $storehash, but only if they don't
                   9803: currently exist, if this succeeds you can be certain that you have 
                   9804: successfully created a new key value pair in the $namespace db.
                   9805: 
                   9806: 
                   9807: Args:
                   9808:  $namespace: name of database to store values to
                   9809:  $storehash: hashref to store to the db
                   9810:  $udom: (optional) domain of user containing the db
                   9811:  $uname: (optional) name of user caontaining the db
                   9812: 
                   9813: Returns:
                   9814:  'ok' -> succeeded in storing all keys of $storehash
                   9815:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9816:                         least <key> already existed in the db (other
                   9817:                         requested keys may also already exist)
1.967     bisitz   9818:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9819:  'con_lost' -> unable to contact request server
                   9820:  'refused' -> action was not allowed by remote machine
                   9821: 
                   9822: 
                   9823: =item *
                   9824: 
1.243     albertel 9825: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9826: reference filled in from namesp (encrypts the return communication)
                   9827: ($udom and $uname are optional)
1.191     harris41 9828: 
                   9829: =item *
                   9830: 
1.243     albertel 9831: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9832: critical subroutine
                   9833: 
1.806     raeburn  9834: =item *
                   9835: 
1.860     raeburn  9836: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9837: array reference filled in from namespace found in domain level on either
                   9838: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9839: 
                   9840: =item *
                   9841: 
1.860     raeburn  9842: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9843: domain level either on specified domain server ($uhome) or primary domain 
                   9844: server ($udom and $uhome are optional)
1.806     raeburn  9845: 
1.943     raeburn  9846: =item * 
                   9847: 
                   9848: get_domain_defaults($target_domain) : returns hash with defaults for
                   9849: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9850: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9851: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9852: Values are retrieved from cache (if current), or from domain's configuration.db
                   9853: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9854: or lonTabs/domain.tab. 
                   9855: 
                   9856: %domdefaults = &get_auth_defaults($target_domain);
                   9857: 
1.243     albertel 9858: =back
                   9859: 
                   9860: =head2 Network Status Functions
                   9861: 
                   9862: =over 4
1.191     harris41 9863: 
                   9864: =item *
                   9865: 
                   9866: dirlist($uri) : return directory list based on URI
                   9867: 
                   9868: =item *
                   9869: 
1.243     albertel 9870: spareserver() : find server with least workload from spare.tab
                   9871: 
                   9872: =back
                   9873: 
                   9874: =head2 Apache Request
                   9875: 
                   9876: =over 4
1.191     harris41 9877: 
                   9878: =item *
                   9879: 
1.243     albertel 9880: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9881: localhost, posts hash
                   9882: 
                   9883: =back
                   9884: 
                   9885: =head2 Data to String to Data
                   9886: 
                   9887: =over 4
1.191     harris41 9888: 
                   9889: =item *
                   9890: 
1.243     albertel 9891: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9892: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9893: 
                   9894: =item *
                   9895: 
1.243     albertel 9896: hashref2str($hashref) : convert a hashref into a string complete with
                   9897: escaping and '=' and '&' separators, supports elements that are
                   9898: arrayrefs and hashrefs
1.191     harris41 9899: 
                   9900: =item *
                   9901: 
1.243     albertel 9902: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9903: with escaping and '&' separators, supports elements that are arrayrefs
                   9904: and hashrefs
1.191     harris41 9905: 
                   9906: =item *
                   9907: 
1.243     albertel 9908: str2hash($string) : convert string to hash using unescaping and
                   9909: splitting on '=' and '&', supports elements that are arrayrefs and
                   9910: hashrefs
1.191     harris41 9911: 
                   9912: =item *
                   9913: 
1.243     albertel 9914: str2array($string) : convert string to hash using unescaping and
                   9915: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9916: 
                   9917: =back
                   9918: 
                   9919: =head2 Logging Routines
                   9920: 
                   9921: =over 4
                   9922: 
                   9923: These routines allow one to make log messages in the lonnet.log and
                   9924: lonnet.perm logfiles.
1.191     harris41 9925: 
                   9926: =item *
                   9927: 
1.243     albertel 9928: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9929: 
                   9930: =item *
                   9931: 
1.243     albertel 9932: logthis() : append message to the normal lonnet.log file, it gets
                   9933: preiodically rolled over and deleted.
1.191     harris41 9934: 
                   9935: =item *
                   9936: 
1.243     albertel 9937: logperm() : append a permanent message to lonnet.perm.log, this log
                   9938: file never gets deleted by any automated portion of the system, only
                   9939: messages of critical importance should go in here.
                   9940: 
                   9941: =back
                   9942: 
                   9943: =head2 General File Helper Routines
                   9944: 
                   9945: =over 4
1.191     harris41 9946: 
                   9947: =item *
                   9948: 
1.481     raeburn  9949: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9950: (a) files in /uploaded
                   9951:   (i) If a local copy of the file exists - 
                   9952:       compares modification date of local copy with last-modified date for 
                   9953:       definitive version stored on home server for course. If local copy is 
                   9954:       stale, requests a new version from the home server and stores it. 
                   9955:       If the original has been removed from the home server, then local copy 
                   9956:       is unlinked.
                   9957:   (ii) If local copy does not exist -
                   9958:       requests the file from the home server and stores it. 
                   9959:   
                   9960:   If $caller is 'uploadrep':  
                   9961:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9962:     for request for files originally uploaded via DOCS. 
                   9963:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9964:   
                   9965:   Otherwise:
                   9966:      This indicates a call from the content generation phase of the request.
                   9967:      -  returns the entire contents of the file or -1.
                   9968:      
                   9969: (b) files in /res
                   9970:    - returns the entire contents of a file or -1; 
                   9971:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9972: 
1.712     albertel 9973: 
                   9974: =item *
                   9975: 
                   9976: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9977:                   reference
                   9978: 
                   9979: returns either a stat() list of data about the file or an empty list
                   9980: if the file doesn't exist or couldn't find out about it (connection
                   9981: problems or user unknown)
                   9982: 
1.191     harris41 9983: =item *
                   9984: 
1.243     albertel 9985: filelocation($dir,$file) : returns file system location of a file
                   9986: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9987: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9988: and a file of ../bob will become /a/bob)
1.191     harris41 9989: 
                   9990: =item *
                   9991: 
                   9992: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9993: filelocation except for hrefs
                   9994: 
                   9995: =item *
                   9996: 
                   9997: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9998: 
1.243     albertel 9999: =back
                   10000: 
1.608     albertel 10001: =head2 Usererfile file routines (/uploaded*)
                   10002: 
                   10003: =over 4
                   10004: 
                   10005: =item *
                   10006: 
                   10007: userfileupload(): main rotine for putting a file in a user or course's
                   10008:                   filespace, arguments are,
                   10009: 
1.620     albertel 10010:  formname - required - this is the name of the element in $env where the
1.608     albertel 10011:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10012:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10013:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10014:  coursedoc - if true, store the file in the course of the active role
                   10015:              of the current user
                   10016:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10017:          if undefined, it will be placed in "unknown"
                   10018: 
                   10019:  (This routine calls clean_filename() to remove any dangerous
                   10020:  characters from the filename, and then calls finuserfileupload() to
                   10021:  complete the transaction)
                   10022: 
                   10023:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10024:  and /adm/notfound.html if unsuccessful
                   10025: 
                   10026: =item *
                   10027: 
                   10028: clean_filename(): routine for cleaing a filename up for storage in
                   10029:                  userfile space, argument is:
                   10030: 
                   10031:  filename - proposed filename
                   10032: 
                   10033: returns: the new clean filename
                   10034: 
                   10035: =item *
                   10036: 
                   10037: finishuserfileupload(): routine that creaes and sends the file to
                   10038: userspace, probably shouldn't be called directly
                   10039: 
                   10040:   docuname: username or courseid of destination for the file
                   10041:   docudom: domain of user/course of destination for the file
                   10042:   formname: same as for userfileupload()
                   10043:   fname: filename (inculding subdirectories) for the file
                   10044: 
                   10045:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10046:  and /adm/notfound.html if unsuccessful
                   10047: 
                   10048: =item *
                   10049: 
                   10050: renameuserfile(): renames an existing userfile to a new name
                   10051: 
                   10052:   Args:
                   10053:    docuname: username or courseid of destination for the file
                   10054:    docudom: domain of user/course of destination for the file
                   10055:    old: current file name (including any subdirs under userfiles)
                   10056:    new: desired file name (including any subdirs under userfiles)
                   10057: 
                   10058: =item *
                   10059: 
                   10060: mkdiruserfile(): creates a directory is a userfiles dir
                   10061: 
                   10062:   Args:
                   10063:    docuname: username or courseid of destination for the file
                   10064:    docudom: domain of user/course of destination for the file
                   10065:    dir: dir to create (including any subdirs under userfiles)
                   10066: 
                   10067: =item *
                   10068: 
                   10069: removeuserfile(): removes a file that exists in userfiles
                   10070: 
                   10071:   Args:
                   10072:    docuname: username or courseid of destination for the file
                   10073:    docudom: domain of user/course of destination for the file
                   10074:    fname: filname to delete (including any subdirs under userfiles)
                   10075: 
                   10076: =item *
                   10077: 
                   10078: removeuploadedurl(): convience function for removeuserfile()
                   10079: 
                   10080:   Args:
                   10081:    url:  a full /uploaded/... url to delete
                   10082: 
1.747     albertel 10083: =item * 
                   10084: 
                   10085: get_portfile_permissions():
                   10086:   Args:
                   10087:     domain: domain of user or course contain the portfolio files
                   10088:     user: name of user or num of course contain the portfolio files
                   10089:   Returns:
                   10090:     hashref of a dump of the proper file_permissions.db
                   10091:    
                   10092: 
                   10093: =item * 
                   10094: 
                   10095: get_access_controls():
                   10096: 
                   10097: Args:
                   10098:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10099:   group: (optional) the group you want the files associated with
                   10100:   file: (optional) the file you want access info on
                   10101: 
                   10102: Returns:
1.749     raeburn  10103:     a hash (keys are file names) of hashes containing
                   10104:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10105:         values are XML containing access control settings (see below) 
1.747     albertel 10106: 
                   10107: Internal notes:
                   10108: 
1.749     raeburn  10109:  access controls are stored in file_permissions.db as key=value pairs.
                   10110:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10111:         where scope -> public,guest,course,group,domains or users.
                   10112:               end -> UNIX time for end of access (0 -> no end date)
                   10113:               start -> UNIX time for start of access
                   10114: 
                   10115:     value -> XML description of access control
                   10116:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10117:             <start></start>
                   10118:             <end></end>
                   10119: 
                   10120:             <password></password>  for scope type = guest
                   10121: 
                   10122:             <domain></domain>     for scope type = course or group
                   10123:             <number></number>
                   10124:             <roles id="">
                   10125:              <role></role>
                   10126:              <access></access>
                   10127:              <section></section>
                   10128:              <group></group>
                   10129:             </roles>
                   10130: 
                   10131:             <dom></dom>         for scope type = domains
                   10132: 
                   10133:             <users>             for scope type = users
                   10134:              <user>
                   10135:               <uname></uname>
                   10136:               <udom></udom>
                   10137:              </user>
                   10138:             </users>
                   10139:            </scope> 
                   10140:               
                   10141:  Access data is also aggregated for each file in an additional key=value pair:
                   10142:  key -> path to file/file_name\0accesscontrol 
                   10143:  value -> reference to hash
                   10144:           hash contains key = value pairs
                   10145:           where key = uniqueID:scope_end_start
                   10146:                 value = UNIX time record was last updated
                   10147: 
                   10148:           Used to improve speed of look-ups of access controls for each file.  
                   10149:  
                   10150:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10151: 
                   10152: modify_access_controls():
                   10153: 
                   10154: Modifies access controls for a portfolio file
                   10155: Args
                   10156: 1. file name
                   10157: 2. reference to hash of required changes,
                   10158: 3. domain
                   10159: 4. username
                   10160:   where domain,username are the domain of the portfolio owner 
                   10161:   (either a user or a course) 
                   10162: 
                   10163: Returns:
                   10164: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10165: 2. result of deletions ('ok' or 'error', with error message).
                   10166: 3. reference to hash of any new or updated access controls.
                   10167: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10168:    key = integer (inbound ID)
                   10169:    value = uniqueID  
1.747     albertel 10170: 
1.608     albertel 10171: =back
                   10172: 
1.243     albertel 10173: =head2 HTTP Helper Routines
                   10174: 
                   10175: =over 4
                   10176: 
1.191     harris41 10177: =item *
                   10178: 
                   10179: escape() : unpack non-word characters into CGI-compatible hex codes
                   10180: 
                   10181: =item *
                   10182: 
                   10183: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10184: 
1.243     albertel 10185: =back
                   10186: 
                   10187: =head1 PRIVATE SUBROUTINES
                   10188: 
                   10189: =head2 Underlying communication routines (Shouldn't call)
                   10190: 
                   10191: =over 4
                   10192: 
                   10193: =item *
                   10194: 
                   10195: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10196: 
                   10197: =item *
                   10198: 
                   10199: reply() : uses subreply to send a message to remote machine, logs all failures
                   10200: 
                   10201: =item *
                   10202: 
                   10203: critical() : passes a critical message to another server; if cannot
                   10204: get through then place message in connection buffer directory and
                   10205: returns con_delayed, if incapable of saving message, returns
                   10206: con_failed
                   10207: 
                   10208: =item *
                   10209: 
                   10210: reconlonc() : tries to reconnect lonc client processes.
                   10211: 
                   10212: =back
                   10213: 
                   10214: =head2 Resource Access Logging
                   10215: 
                   10216: =over 4
                   10217: 
                   10218: =item *
                   10219: 
                   10220: flushcourselogs() : flush (save) buffer logs and access logs
                   10221: 
                   10222: =item *
                   10223: 
                   10224: courselog($what) : save message for course in hash
                   10225: 
                   10226: =item *
                   10227: 
                   10228: courseacclog($what) : save message for course using &courselog().  Perform
                   10229: special processing for specific resource types (problems, exams, quizzes, etc).
                   10230: 
1.191     harris41 10231: =item *
                   10232: 
                   10233: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10234: as a PerlChildExitHandler
1.243     albertel 10235: 
                   10236: =back
                   10237: 
                   10238: =head2 Other
                   10239: 
                   10240: =over 4
                   10241: 
                   10242: =item *
                   10243: 
                   10244: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10245: 
                   10246: =back
                   10247: 
                   10248: =cut
1.877     foxr     10249: 

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