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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.984   ! neumanie    4: # $Id: lonnet.pm,v 1.983 2009/01/02 23:07:49 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: }
1.984   ! neumanie 2032: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
        !          2033: sub resizeImage {
        !          2034: 	my($img_url) = @_;	
        !          2035: 	my $ima = Image::Magick->new;                       
        !          2036:         $ima->Read($img_url);
        !          2037: 	if($ima->Get('width') > 400)
        !          2038: 	{
        !          2039: 		my $factor = $ima->Get('width')/400;
        !          2040:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
        !          2041: 	}
        !          2042: 	if($ima->Get('height') > 500)
        !          2043:         {
        !          2044:         	my $factor = $ima->Get('height')/500;
        !          2045:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
        !          2046:         } 
        !          2047: 		
        !          2048: 	$ima->Write($img_url);
        !          2049: }
1.531     albertel 2050: 
1.977     amueller 2051: #Wrapper function for userphotoupload
                   2052: sub userphotoupload
                   2053: {
                   2054: 	my($formname,$subdir) = @_;
                   2055: 	$upload_photo_form = 1;
                   2056: 	return &userfileupload($formname,undef,$subdir);
                   2057: }
                   2058: 
1.608     albertel 2059: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2060: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2061: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2062: #        $coursedoc - if true up to the current course
                   2063: #                     if false
                   2064: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2065: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2066: #        $allfiles - reference to hash for embedded objects
                   2067: #        $codebase - reference to hash for codebase of java objects
                   2068: #        $desuname - username for permanent storage of uploaded file
                   2069: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2070: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2071: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2072: # 
1.686     albertel 2073: # output: url of file in userspace, or error: <message> 
                   2074: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2075: 
                   2076: 
1.531     albertel 2077: sub userfileupload {
1.860     raeburn  2078:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2079:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2080:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2081:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2082:     $fname=&clean_filename($fname);
1.315     www      2083: # See if there is anything left
1.257     www      2084:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2085:     chop($env{'form.'.$formname});
1.523     raeburn  2086:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2087:         my $now = time;
                   2088:         my $filepath = 'tmp/helprequests/'.$now;
                   2089:         my @parts=split(/\//,$filepath);
                   2090:         my $fullpath = $perlvar{'lonDaemons'};
                   2091:         for (my $i=0;$i<@parts;$i++) {
                   2092:             $fullpath .= '/'.$parts[$i];
                   2093:             if ((-e $fullpath)!=1) {
                   2094:                 mkdir($fullpath,0777);
                   2095:             }
                   2096:         }
                   2097:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2098:         print $fh $env{'form.'.$formname};
1.523     raeburn  2099:         close($fh);
1.741     raeburn  2100:         return $fullpath.'/'.$fname;
                   2101:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2102:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2103:                        '_'.$env{'user.domain'}.'/pending';
                   2104:         my @parts=split(/\//,$filepath);
                   2105:         my $fullpath = $perlvar{'lonDaemons'};
                   2106:         for (my $i=0;$i<@parts;$i++) {
                   2107:             $fullpath .= '/'.$parts[$i];
                   2108:             if ((-e $fullpath)!=1) {
                   2109:                 mkdir($fullpath,0777);
                   2110:             }
                   2111:         }
                   2112:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2113:         print $fh $env{'form.'.$formname};
                   2114:         close($fh);
                   2115:         return $fullpath.'/'.$fname;
1.523     raeburn  2116:     }
1.719     banghart 2117:     
1.258     www      2118: # Create the directory if not present
1.493     albertel 2119:     $fname="$subdir/$fname";
1.259     www      2120:     if ($coursedoc) {
1.638     albertel 2121: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2122: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2123:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2124:             return &finishuserfileupload($docuname,$docudom,
                   2125: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2126: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2127:         } else {
1.620     albertel 2128:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2129:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2130: 				       $fname,$formname,$parser,
                   2131: 				       $allfiles,$codebase);
1.481     raeburn  2132:         }
1.719     banghart 2133:     } elsif (defined($destuname)) {
                   2134:         my $docuname=$destuname;
                   2135:         my $docudom=$destudom;
1.860     raeburn  2136: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2137: 				     $parser,$allfiles,$codebase,
                   2138:                                      $thumbwidth,$thumbheight);
1.719     banghart 2139:         
1.259     www      2140:     } else {
1.638     albertel 2141:         my $docuname=$env{'user.name'};
                   2142:         my $docudom=$env{'user.domain'};
1.714     raeburn  2143:         if (exists($env{'form.group'})) {
                   2144:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2145:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2146:         }
1.860     raeburn  2147: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2148: 				     $parser,$allfiles,$codebase,
                   2149:                                      $thumbwidth,$thumbheight);
1.259     www      2150:     }
1.271     www      2151: }
                   2152: 
                   2153: sub finishuserfileupload {
1.860     raeburn  2154:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2155:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2156:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2157:     my $filepath=$perlvar{'lonDocRoot'};
1.984   ! neumanie 2158:   
1.860     raeburn  2159:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2160:     $file=$fname;
                   2161:     if ($fname=~m|/|) {
                   2162:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2163: 	$path.=$fnamepath.'/';
                   2164:     }
1.259     www      2165:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2166:     my $count;
                   2167:     for ($count=4;$count<=$#parts;$count++) {
                   2168:         $filepath.="/$parts[$count]";
                   2169:         if ((-e $filepath)!=1) {
                   2170: 	    mkdir($filepath,0777);
                   2171:         }
                   2172:     }
1.984   ! neumanie 2173: 
1.258     www      2174: # Save the file
                   2175:     {
1.701     albertel 2176: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2177: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2178: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2179: 	    return '/adm/notfound.html';
                   2180: 	}
                   2181: 	if (!print FH ($env{'form.'.$formname})) {
                   2182: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2183: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2184: 	    return '/adm/notfound.html';
                   2185: 	}
1.570     albertel 2186: 	close(FH);
1.977     amueller 2187: 	if($upload_photo_form==1)
                   2188: 	{
1.984   ! neumanie 2189: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2190: 		$upload_photo_form = 0;
                   2191: 	}
1.258     www      2192:     }
1.637     raeburn  2193:     if ($parser eq 'parse') {
1.961     raeburn  2194:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2195: 						   $codebase);
1.637     raeburn  2196:         unless ($parse_result eq 'ok') {
1.638     albertel 2197:             &logthis('Failed to parse '.$filepath.$file.
                   2198: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2199:         }
                   2200:     }
1.860     raeburn  2201:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2202:         my $input = $filepath.'/'.$file;
                   2203:         my $output = $filepath.'/'.'tn-'.$file;
                   2204:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2205:         system("convert -sample $thumbsize $input $output");
                   2206:         if (-e $filepath.'/'.'tn-'.$file) {
                   2207:             $fetchthumb  = 1; 
                   2208:         }
                   2209:     }
1.858     raeburn  2210:  
1.259     www      2211: # Notify homeserver to grep it
                   2212: #
1.984   ! neumanie 2213:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2214:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2215:     if ($fetchresult eq 'ok') {
1.860     raeburn  2216:         if ($fetchthumb) {
                   2217:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2218:             if ($thumbresult ne 'ok') {
                   2219:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2220:                          $docuhome.': '.$thumbresult);
                   2221:             }
                   2222:         }
1.259     www      2223: #
1.258     www      2224: # Return the URL to it
1.494     albertel 2225:         return '/uploaded/'.$path.$file;
1.263     www      2226:     } else {
1.494     albertel 2227:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2228: 		 ': '.$fetchresult);
1.263     www      2229:         return '/adm/notfound.html';
1.858     raeburn  2230:     }
1.493     albertel 2231: }
                   2232: 
1.637     raeburn  2233: sub extract_embedded_items {
1.961     raeburn  2234:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2235:     my @state = ();
                   2236:     my %javafiles = (
                   2237:                       codebase => '',
                   2238:                       code => '',
                   2239:                       archive => ''
                   2240:                     );
                   2241:     my %mediafiles = (
                   2242:                       src => '',
                   2243:                       movie => '',
                   2244:                      );
1.648     raeburn  2245:     my $p;
                   2246:     if ($content) {
                   2247:         $p = HTML::LCParser->new($content);
                   2248:     } else {
1.961     raeburn  2249:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2250:     }
1.641     albertel 2251:     while (my $t=$p->get_token()) {
1.640     albertel 2252: 	if ($t->[0] eq 'S') {
                   2253: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2254: 	    push(@state, $tagname);
1.648     raeburn  2255:             if (lc($tagname) eq 'allow') {
                   2256:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2257:             }
1.640     albertel 2258: 	    if (lc($tagname) eq 'img') {
                   2259: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2260: 	    }
1.886     albertel 2261: 	    if (lc($tagname) eq 'a') {
                   2262: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2263: 	    }
1.645     raeburn  2264:             if (lc($tagname) eq 'script') {
                   2265:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2266:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2267:                 } else {
                   2268:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2269:                 }
                   2270:             }
                   2271:             if (lc($tagname) eq 'link') {
                   2272:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2273:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2274:                 }
                   2275:             }
1.640     albertel 2276: 	    if (lc($tagname) eq 'object' ||
                   2277: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2278: 		foreach my $item (keys(%javafiles)) {
                   2279: 		    $javafiles{$item} = '';
                   2280: 		}
                   2281: 	    }
                   2282: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2283: 		my $name = lc($attr->{'name'});
                   2284: 		foreach my $item (keys(%javafiles)) {
                   2285: 		    if ($name eq $item) {
                   2286: 			$javafiles{$item} = $attr->{'value'};
                   2287: 			last;
                   2288: 		    }
                   2289: 		}
                   2290: 		foreach my $item (keys(%mediafiles)) {
                   2291: 		    if ($name eq $item) {
                   2292: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2293: 			last;
                   2294: 		    }
                   2295: 		}
                   2296: 	    }
                   2297: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2298: 		foreach my $item (keys(%javafiles)) {
                   2299: 		    if ($attr->{$item}) {
                   2300: 			$javafiles{$item} = $attr->{$item};
                   2301: 			last;
                   2302: 		    }
                   2303: 		}
                   2304: 		foreach my $item (keys(%mediafiles)) {
                   2305: 		    if ($attr->{$item}) {
                   2306: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2307: 			last;
                   2308: 		    }
                   2309: 		}
                   2310: 	    }
                   2311: 	} elsif ($t->[0] eq 'E') {
                   2312: 	    my ($tagname) = ($t->[1]);
                   2313: 	    if ($javafiles{'codebase'} ne '') {
                   2314: 		$javafiles{'codebase'} .= '/';
                   2315: 	    }  
                   2316: 	    if (lc($tagname) eq 'applet' ||
                   2317: 		lc($tagname) eq 'object' ||
                   2318: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2319: 		) {
                   2320: 		foreach my $item (keys(%javafiles)) {
                   2321: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2322: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2323: 			&add_filetype($allfiles,$file,$item);
                   2324: 		    }
                   2325: 		}
                   2326: 	    } 
                   2327: 	    pop @state;
                   2328: 	}
                   2329:     }
1.637     raeburn  2330:     return 'ok';
                   2331: }
                   2332: 
1.639     albertel 2333: sub add_filetype {
                   2334:     my ($allfiles,$file,$type)=@_;
                   2335:     if (exists($allfiles->{$file})) {
                   2336: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2337: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2338: 	}
                   2339:     } else {
                   2340: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2341:     }
                   2342: }
                   2343: 
1.493     albertel 2344: sub removeuploadedurl {
1.984   ! neumanie 2345:     my ($url)=@_;	
        !          2346:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2347:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2348: }
                   2349: 
                   2350: sub removeuserfile {
                   2351:     my ($docuname,$docudom,$fname)=@_;
1.984   ! neumanie 2352:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2353:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984   ! neumanie 2354:     if ($result eq 'ok') {	
1.798     raeburn  2355:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2356:             my $metafile = $fname.'.meta';
                   2357:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2358: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984   ! neumanie 2359:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2360:             my $sqlresult = 
1.823     albertel 2361:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2362:                                         'portfolio_metadata',$group,
                   2363:                                         'delete');
1.798     raeburn  2364:         }
                   2365:     }
                   2366:     return $result;
1.257     www      2367: }
1.15      www      2368: 
1.530     albertel 2369: sub mkdiruserfile {
                   2370:     my ($docuname,$docudom,$dir)=@_;
                   2371:     my $home=&homeserver($docuname,$docudom);
                   2372:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2373: }
                   2374: 
1.531     albertel 2375: sub renameuserfile {
                   2376:     my ($docuname,$docudom,$old,$new)=@_;
                   2377:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2378:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2379:                         &escape("$old").':'.&escape("$new"),$home);
                   2380:     if ($result eq 'ok') {
                   2381:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2382:             my $oldmeta = $old.'.meta';
                   2383:             my $newmeta = $new.'.meta';
                   2384:             my $metaresult = 
                   2385:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2386: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2387:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2388:             my $sqlresult = 
1.823     albertel 2389:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2390:                                         'portfolio_metadata',$group,
                   2391:                                         'delete');
1.798     raeburn  2392:         }
                   2393:     }
                   2394:     return $result;
1.531     albertel 2395: }
                   2396: 
1.14      www      2397: # ------------------------------------------------------------------------- Log
                   2398: 
                   2399: sub log {
                   2400:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2401:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2402: }
                   2403: 
                   2404: # ------------------------------------------------------------------ Course Log
1.352     www      2405: #
                   2406: # This routine flushes several buffers of non-mission-critical nature
                   2407: #
1.157     www      2408: 
                   2409: sub flushcourselogs {
1.352     www      2410:     &logthis('Flushing log buffers');
                   2411: #
                   2412: # course logs
                   2413: # This is a log of all transactions in a course, which can be used
                   2414: # for data mining purposes
                   2415: #
                   2416: # It also collects the courseid database, which lists last transaction
                   2417: # times and course titles for all courseids
                   2418: #
                   2419:     my %courseidbuffer=();
1.921     raeburn  2420:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2421:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2422: 		          &escape($courselogs{$crsid}),
                   2423: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2424: 	    delete $courselogs{$crsid};
                   2425:         } else {
                   2426:             &logthis('Failed to flush log buffer for '.$crsid);
                   2427:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2428:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2429:                         " exceeded maximum size, deleting.</font>");
                   2430:                delete $courselogs{$crsid};
                   2431:             }
1.352     www      2432:         }
1.920     raeburn  2433:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2434:             'description' => $coursedescrbuf{$crsid},
                   2435:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2436:             'type'        => $coursetypebuf{$crsid},
                   2437:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2438:         };
1.191     harris41 2439:     }
1.352     www      2440: #
                   2441: # Write course id database (reverse lookup) to homeserver of courses 
                   2442: # Is used in pickcourse
                   2443: #
1.840     albertel 2444:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2445:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2446:                                     $courseidbuffer{$crs_home},
                   2447:                                     $crs_home,'timeonly');
1.352     www      2448:     }
                   2449: #
                   2450: # File accesses
                   2451: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2452: #
1.449     matthew  2453:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2454:         if ($entry =~ /___count$/) {
                   2455:             my ($dom,$name);
1.807     albertel 2456:             ($dom,$name,undef)=
1.811     albertel 2457: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2458:             if (! defined($dom) || $dom eq '' || 
                   2459:                 ! defined($name) || $name eq '') {
1.620     albertel 2460:                 my $cid = $env{'request.course.id'};
                   2461:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2462:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2463:             }
1.450     matthew  2464:             my $value = $accesshash{$entry};
                   2465:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2466:             my %temphash=($url => $value);
1.449     matthew  2467:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2468:             if ($result eq 'ok') {
                   2469:                 delete $accesshash{$entry};
                   2470:             } elsif ($result eq 'unknown_cmd') {
                   2471:                 # Target server has old code running on it.
1.450     matthew  2472:                 my %temphash=($entry => $value);
1.449     matthew  2473:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2474:                     delete $accesshash{$entry};
                   2475:                 }
                   2476:             }
                   2477:         } else {
1.811     albertel 2478:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2479:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2480:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2481:                 delete $accesshash{$entry};
                   2482:             }
1.185     www      2483:         }
1.191     harris41 2484:     }
1.352     www      2485: #
                   2486: # Roles
                   2487: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2488: #
1.800     albertel 2489:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2490:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2491: 	    split(/\:/,$entry);
                   2492:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2493:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2494:                 $rudom,$runame) eq 'ok') {
                   2495: 	    delete $userrolehash{$entry};
                   2496:         }
                   2497:     }
1.662     raeburn  2498: #
                   2499: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2500: #
                   2501:     my %domrolebuffer = ();
                   2502:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2503:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2504:         if ($domrolebuffer{$rudom}) {
                   2505:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2506:                       '='.&escape($domainrolehash{$entry});
                   2507:         } else {
                   2508:             $domrolebuffer{$rudom}.=&escape($entry).
                   2509:                       '='.&escape($domainrolehash{$entry});
                   2510:         }
                   2511:         delete $domainrolehash{$entry};
                   2512:     }
                   2513:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2514: 	my %servers = &get_servers($dom,'library');
                   2515: 	foreach my $tryserver (keys(%servers)) {
                   2516: 	    unless (&reply('domroleput:'.$dom.':'.
                   2517: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2518: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2519: 	    }
1.662     raeburn  2520:         }
                   2521:     }
1.186     www      2522:     $dumpcount++;
1.157     www      2523: }
                   2524: 
                   2525: sub courselog {
                   2526:     my $what=shift;
1.158     www      2527:     $what=time.':'.$what;
1.620     albertel 2528:     unless ($env{'request.course.id'}) { return ''; }
                   2529:     $coursedombuf{$env{'request.course.id'}}=
                   2530:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2531:     $coursenumbuf{$env{'request.course.id'}}=
                   2532:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2533:     $coursehombuf{$env{'request.course.id'}}=
                   2534:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2535:     $coursedescrbuf{$env{'request.course.id'}}=
                   2536:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2537:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2538:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2539:     $courseownerbuf{$env{'request.course.id'}}=
                   2540:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2541:     $coursetypebuf{$env{'request.course.id'}}=
                   2542:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2543:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2544: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2545:     } else {
1.620     albertel 2546: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2547:     }
1.620     albertel 2548:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2549: 	&flushcourselogs();
                   2550:     }
1.158     www      2551: }
                   2552: 
                   2553: sub courseacclog {
                   2554:     my $fnsymb=shift;
1.620     albertel 2555:     unless ($env{'request.course.id'}) { return ''; }
                   2556:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2557:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2558:         $what.=':POST';
1.583     matthew  2559:         # FIXME: Probably ought to escape things....
1.800     albertel 2560: 	foreach my $key (keys(%env)) {
                   2561:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2562:                 my $formitem = $1;
                   2563:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2564:                     $what.=':'.$formitem.'='.$env{$key};
                   2565:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2566:                     $what.=':'.$formitem.'='.$env{$key};
                   2567:                 }
1.158     www      2568:             }
1.191     harris41 2569:         }
1.583     matthew  2570:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2571:         # FIXME: We should not be depending on a form parameter that someone
                   2572:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2573:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2574:             $what.= ':POST';
                   2575:             # FIXME: Probably ought to escape things....
                   2576:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2577:                                  'crsdiscuss') {
1.620     albertel 2578:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2579:             }
                   2580:         }
1.158     www      2581:     }
                   2582:     &courselog($what);
1.149     www      2583: }
                   2584: 
1.185     www      2585: sub countacc {
                   2586:     my $url=&declutter(shift);
1.458     matthew  2587:     return if (! defined($url) || $url eq '');
1.620     albertel 2588:     unless ($env{'request.course.id'}) { return ''; }
                   2589:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2590:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2591:     $accesshash{$key}++;
1.185     www      2592: }
1.349     www      2593: 
1.361     www      2594: sub linklog {
                   2595:     my ($from,$to)=@_;
                   2596:     $from=&declutter($from);
                   2597:     $to=&declutter($to);
                   2598:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2599:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2600: }
                   2601:   
1.349     www      2602: sub userrolelog {
                   2603:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2604:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2605:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2606:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2607:         ($trole=~/^ta/)) {
1.350     www      2608:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2609:        $userrolehash
                   2610:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2611:                     =$tend.':'.$tstart;
1.662     raeburn  2612:     }
1.898     albertel 2613:     if (($env{'request.role'} =~ /dc\./) &&
                   2614: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2615: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2616: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2617:        $userrolehash
                   2618:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2619:                     =$tend.':'.$tstart;
                   2620:     }
1.662     raeburn  2621:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2622:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2623:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2624:         ($trole=~/^sc/)) {
                   2625:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2626:        $domainrolehash
                   2627:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2628:                     = $tend.':'.$tstart;
                   2629:     }
1.351     www      2630: }
                   2631: 
1.957     raeburn  2632: sub courserolelog {
                   2633:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2634:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2635:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2636:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2637:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2638:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2639:             my $cdom = $1;
                   2640:             my $cnum = $2;
                   2641:             my $sec = $3;
                   2642:             my $namespace = 'rolelog';
                   2643:             my %storehash = (
                   2644:                                role    => $trole,
                   2645:                                start   => $tstart,
                   2646:                                end     => $tend,
                   2647:                                selfenroll => $selfenroll,
                   2648:                                context    => $context,
                   2649:                             );
                   2650:             if ($trole eq 'gr') {
                   2651:                 $namespace = 'groupslog';
                   2652:                 $storehash{'group'} = $sec;
                   2653:             } else {
                   2654:                 $storehash{'section'} = $sec;
                   2655:             }
                   2656:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2657:         }
                   2658:     }
                   2659:     return;
                   2660: }
                   2661: 
1.351     www      2662: sub get_course_adv_roles {
1.948     raeburn  2663:     my ($cid,$codes) = @_;
1.620     albertel 2664:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2665:     my %coursehash=&coursedescription($cid);
1.470     www      2666:     my %nothide=();
1.800     albertel 2667:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2668:         if ($user !~ /:/) {
                   2669: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2670:         } else {
                   2671:             $nothide{$user}=1;
                   2672:         }
1.470     www      2673:     }
1.351     www      2674:     my %returnhash=();
                   2675:     my %dumphash=
                   2676:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2677:     my $now=time;
1.800     albertel 2678:     foreach my $entry (keys %dumphash) {
                   2679: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2680:         if (($tstart) && ($tstart<0)) { next; }
                   2681:         if (($tend) && ($tend<$now)) { next; }
                   2682:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2683:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2684: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2685: 	if ((&privileged($username,$domain)) && 
                   2686: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2687: 	if ($role eq 'cr') { next; }
1.948     raeburn  2688:         if ($codes) {
                   2689:             if ($section) { $role .= ':'.$section; }
                   2690:             if ($returnhash{$role}) {
                   2691:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2692:             } else {
                   2693:                 $returnhash{$role}=$username.':'.$domain;
                   2694:             }
1.351     www      2695:         } else {
1.948     raeburn  2696:             my $key=&plaintext($role);
1.973     bisitz   2697:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2698:             if ($returnhash{$key}) {
                   2699: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2700:             } else {
                   2701:                 $returnhash{$key}=$username.':'.$domain;
                   2702:             }
1.351     www      2703:         }
1.948     raeburn  2704:     }
1.400     www      2705:     return %returnhash;
                   2706: }
                   2707: 
                   2708: sub get_my_roles {
1.937     raeburn  2709:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2710:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2711:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2712:     my (%dumphash,%nothide);
1.858     raeburn  2713:     if ($context eq 'userroles') { 
                   2714:         %dumphash = &dump('roles',$udom,$uname);
                   2715:     } else {
                   2716:         %dumphash=
1.400     www      2717:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2718:         if ($hidepriv) {
                   2719:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2720:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2721:                 if ($user !~ /:/) {
                   2722:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2723:                 } else {
                   2724:                     $nothide{$user} = 1;
                   2725:                 }
                   2726:             }
                   2727:         }
1.858     raeburn  2728:     }
1.400     www      2729:     my %returnhash=();
                   2730:     my $now=time;
1.800     albertel 2731:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2732:         my ($role,$tend,$tstart);
                   2733:         if ($context eq 'userroles') {
                   2734: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2735:         } else {
                   2736:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2737:         }
1.400     www      2738:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2739:         my $status = 'active';
1.939     raeburn  2740:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2741:             $status = 'previous';
                   2742:         } 
                   2743:         if (($tstart) && ($now<$tstart)) {
                   2744:             $status = 'future';
                   2745:         }
                   2746:         if (ref($types) eq 'ARRAY') {
                   2747:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2748:                 next;
                   2749:             } 
                   2750:         } else {
                   2751:             if ($status ne 'active') {
                   2752:                 next;
                   2753:             }
                   2754:         }
1.867     raeburn  2755:         my ($rolecode,$username,$domain,$section,$area);
                   2756:         if ($context eq 'userroles') {
                   2757:             ($area,$rolecode) = split(/_/,$entry);
                   2758:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2759:         } else {
                   2760:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2761:         }
1.832     raeburn  2762:         if (ref($roledoms) eq 'ARRAY') {
                   2763:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2764:                 next;
                   2765:             }
                   2766:         }
                   2767:         if (ref($roles) eq 'ARRAY') {
                   2768:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2769:                 if ($role =~ /^cr\//) {
                   2770:                     if (!grep(/^cr$/,@{$roles})) {
                   2771:                         next;
                   2772:                     }
                   2773:                 } else {
                   2774:                     next;
                   2775:                 }
1.832     raeburn  2776:             }
1.867     raeburn  2777:         }
1.937     raeburn  2778:         if ($hidepriv) {
                   2779:             if ((&privileged($username,$domain)) &&
                   2780:                 (!$nothide{$username.':'.$domain})) { 
                   2781:                 next;
                   2782:             }
                   2783:         }
1.933     raeburn  2784:         if ($withsec) {
                   2785:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2786:                 $tstart.':'.$tend;
                   2787:         } else {
                   2788:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2789:         }
1.832     raeburn  2790:     }
1.373     www      2791:     return %returnhash;
1.399     www      2792: }
                   2793: 
                   2794: # ----------------------------------------------------- Frontpage Announcements
                   2795: #
                   2796: #
                   2797: 
                   2798: sub postannounce {
                   2799:     my ($server,$text)=@_;
1.844     albertel 2800:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2801:     unless ($text=~/\w/) { $text=''; }
                   2802:     return &reply('setannounce:'.&escape($text),$server);
                   2803: }
                   2804: 
                   2805: sub getannounce {
1.448     albertel 2806: 
                   2807:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2808: 	my $announcement='';
1.800     albertel 2809: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2810: 	close($fh);
1.399     www      2811: 	if ($announcement=~/\w/) { 
                   2812: 	    return 
                   2813:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2814:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2815: 	} else {
                   2816: 	    return '';
                   2817: 	}
                   2818:     } else {
                   2819: 	return '';
                   2820:     }
1.351     www      2821: }
1.353     www      2822: 
                   2823: # ---------------------------------------------------------- Course ID routines
                   2824: # Deal with domain's nohist_courseid.db files
                   2825: #
                   2826: 
                   2827: sub courseidput {
1.921     raeburn  2828:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2829:     my $outcome;
                   2830:     if ($caller eq 'timeonly') {
                   2831:         my $cids = '';
                   2832:         foreach my $item (keys(%$storehash)) {
                   2833:             $cids.=&escape($item).'&';
                   2834:         }
                   2835:         $cids=~s/\&$//;
                   2836:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2837:                           $coursehome);       
                   2838:     } else {
                   2839:         my $items = '';
                   2840:         foreach my $item (keys(%$storehash)) {
                   2841:             $items.= &escape($item).'='.
                   2842:                      &freeze_escape($$storehash{$item}).'&';
                   2843:         }
                   2844:         $items=~s/\&$//;
                   2845:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2846:                           $coursehome);
1.918     raeburn  2847:     }
                   2848:     if ($outcome eq 'unknown_cmd') {
                   2849:         my $what;
                   2850:         foreach my $cid (keys(%$storehash)) {
                   2851:             $what .= &escape($cid).'=';
1.921     raeburn  2852:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2853:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2854:             }
                   2855:             $what =~ s/\:$/&/;
                   2856:         }
                   2857:         $what =~ s/\&$//;  
                   2858:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2859:     } else {
                   2860:         return $outcome;
                   2861:     }
1.353     www      2862: }
                   2863: 
                   2864: sub courseiddump {
1.921     raeburn  2865:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2866:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2867:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2868:     my $as_hash = 1;
                   2869:     my %returnhash;
                   2870:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2871:     my %libserv = &all_library();
                   2872:     foreach my $tryserver (keys(%libserv)) {
                   2873:         if ( (  $hostidflag == 1 
                   2874: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2875: 	     || (!defined($hostidflag)) ) {
                   2876: 
1.918     raeburn  2877: 	    if (($domfilter eq '') ||
                   2878: 		(&host_domain($tryserver) eq $domfilter)) {
                   2879:                 my $rep = 
                   2880:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2881:                          $sincefilter.':'.&escape($descfilter).':'.
                   2882:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2883:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2884:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2885:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2886:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2887:                 my @pairs=split(/\&/,$rep);
                   2888:                 foreach my $item (@pairs) {
                   2889:                     my ($key,$value)=split(/\=/,$item,2);
                   2890:                     $key = &unescape($key);
                   2891:                     next if ($key =~ /^error: 2 /);
                   2892:                     my $result = &thaw_unescape($value);
                   2893:                     if (ref($result) eq 'HASH') {
                   2894:                         $returnhash{$key}=$result;
                   2895:                     } else {
1.921     raeburn  2896:                         my @responses = split(/:/,$value);
                   2897:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2898:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2899:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2900:                         }
                   2901:                     } 
1.353     www      2902:                 }
                   2903:             }
                   2904:         }
                   2905:     }
                   2906:     return %returnhash;
                   2907: }
                   2908: 
1.658     raeburn  2909: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2910: 
                   2911: sub dcmailput {
1.685     raeburn  2912:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2913:     my $status = &Apache::lonnet::critical(
1.740     www      2914:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2915:        &escape($message),$server);
1.662     raeburn  2916:     return $status;
                   2917: }
                   2918: 
1.658     raeburn  2919: sub dcmaildump {
                   2920:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2921:     my %returnhash=();
1.846     albertel 2922: 
                   2923:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2924:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2925:                                                          &escape($enddate).':';
                   2926: 	my @esc_senders=map { &escape($_)} @$senders;
                   2927: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2928: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2929:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2930:             if (($key) && ($value)) {
                   2931:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2932:             }
                   2933:         }
                   2934:     }
                   2935:     return %returnhash;
                   2936: }
1.662     raeburn  2937: # ---------------------------------------------------------- Domain roles
                   2938: 
                   2939: sub get_domain_roles {
                   2940:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2941:     if (undef($startdate) || $startdate eq '') {
                   2942:         $startdate = '.';
                   2943:     }
                   2944:     if (undef($enddate) || $enddate eq '') {
                   2945:         $enddate = '.';
                   2946:     }
1.922     raeburn  2947:     my $rolelist;
                   2948:     if (ref($roles) eq 'ARRAY') {
                   2949:         $rolelist = join(':',@{$roles});
                   2950:     }
1.662     raeburn  2951:     my %personnel = ();
1.841     albertel 2952: 
                   2953:     my %servers = &get_servers($dom,'library');
                   2954:     foreach my $tryserver (keys(%servers)) {
                   2955: 	%{$personnel{$tryserver}}=();
                   2956: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2957: 					    &escape($startdate).':'.
                   2958: 					    &escape($enddate).':'.
                   2959: 					    &escape($rolelist), $tryserver))) {
                   2960: 	    my ($key,$value) = split(/\=/,$line,2);
                   2961: 	    if (($key) && ($value)) {
                   2962: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2963: 	    }
                   2964: 	}
1.662     raeburn  2965:     }
                   2966:     return %personnel;
                   2967: }
1.658     raeburn  2968: 
1.149     www      2969: # ----------------------------------------------------------- Check out an item
                   2970: 
1.504     albertel 2971: sub get_first_access {
                   2972:     my ($type,$argsymb)=@_;
1.790     albertel 2973:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2974:     if ($argsymb) { $symb=$argsymb; }
                   2975:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2976:     if ($type eq 'course') {
                   2977: 	$res='course';
                   2978:     } elsif ($type eq 'map') {
1.588     albertel 2979: 	$res=&symbread($map);
                   2980:     } else {
                   2981: 	$res=$symb;
                   2982:     }
                   2983:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2984:     return $times{"$courseid\0$res"};
1.504     albertel 2985: }
                   2986: 
                   2987: sub set_first_access {
                   2988:     my ($type)=@_;
1.790     albertel 2989:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2990:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2991:     if ($type eq 'course') {
                   2992: 	$res='course';
                   2993:     } elsif ($type eq 'map') {
1.588     albertel 2994: 	$res=&symbread($map);
                   2995:     } else {
                   2996: 	$res=$symb;
                   2997:     }
                   2998:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2999:     if (!$firstaccess) {
1.588     albertel 3000: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3001:     }
                   3002:     return 'already_set';
1.504     albertel 3003: }
                   3004: 
1.149     www      3005: sub checkout {
                   3006:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3007:     my $now=time;
                   3008:     my $lonhost=$perlvar{'lonHostID'};
                   3009:     my $infostr=&escape(
1.234     www      3010:                  'CHECKOUTTOKEN&'.
1.149     www      3011:                  $tuname.'&'.
                   3012:                  $tudom.'&'.
                   3013:                  $tcrsid.'&'.
                   3014:                  $symb.'&'.
                   3015: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3016:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3017:     if ($token=~/^error\:/) { 
1.672     albertel 3018:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3019:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3020:                  "</font>");
                   3021:         return ''; 
                   3022:     }
                   3023: 
1.149     www      3024:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3025:     $token=~tr/a-z/A-Z/;
                   3026: 
1.153     www      3027:     my %infohash=('resource.0.outtoken' => $token,
                   3028:                   'resource.0.checkouttime' => $now,
                   3029:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3030: 
                   3031:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3032:        return '';
1.151     www      3033:     } else {
1.672     albertel 3034:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3035:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3036:                  "</font>");
1.149     www      3037:     }    
                   3038: 
                   3039:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3040:                          &escape('Checkout '.$infostr.' - '.
                   3041:                                                  $token)) ne 'ok') {
                   3042: 	return '';
1.151     www      3043:     } else {
1.672     albertel 3044:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3045:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3046:                  "</font>");
1.149     www      3047:     }
1.151     www      3048:     return $token;
1.149     www      3049: }
                   3050: 
                   3051: # ------------------------------------------------------------ Check in an item
                   3052: 
                   3053: sub checkin {
                   3054:     my $token=shift;
1.150     www      3055:     my $now=time;
                   3056:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3057:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3058:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3059:     $dtoken=~s/\W/\_/g;
1.234     www      3060:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3061:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3062: 
1.154     www      3063:     unless (($tuname) && ($tudom)) {
                   3064:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3065:         return '';
                   3066:     }
                   3067:     
                   3068:     unless (&allowed('mgr',$tcrsid)) {
                   3069:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3070:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3071:         return '';
                   3072:     }
                   3073: 
1.153     www      3074:     my %infohash=('resource.0.intoken' => $token,
                   3075:                   'resource.0.checkintime' => $now,
                   3076:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3077: 
                   3078:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3079:        return '';
                   3080:     }    
                   3081: 
                   3082:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3083:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3084: 	return '';
                   3085:     }
                   3086: 
                   3087:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3088: }
                   3089: 
                   3090: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3091: 
                   3092: sub expirespread {
                   3093:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3094:     my $cid=$env{'request.course.id'}; 
1.110     www      3095:     if ($cid) {
                   3096:        my $now=time;
                   3097:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3098:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3099:                             $env{'course.'.$cid.'.num'}.
1.110     www      3100: 	        	    ':nohist_expirationdates:'.
                   3101:                             &escape($key).'='.$now,
1.620     albertel 3102:                             $env{'course.'.$cid.'.home'})
1.110     www      3103:     }
                   3104:     return 'ok';
1.14      www      3105: }
                   3106: 
1.109     www      3107: # ----------------------------------------------------- Devalidate Spreadsheets
                   3108: 
                   3109: sub devalidate {
1.325     www      3110:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3111:     my $cid=$env{'request.course.id'}; 
1.109     www      3112:     if ($cid) {
1.391     matthew  3113:         # delete the stored spreadsheets for
                   3114:         # - the student level sheet of this user in course's homespace
                   3115:         # - the assessment level sheet for this resource 
                   3116:         #   for this user in user's homespace
1.553     albertel 3117: 	# - current conditional state info
1.325     www      3118: 	my $key=$uname.':'.$udom.':';
1.109     www      3119:         my $status=
1.299     matthew  3120: 	    &del('nohist_calculatedsheets',
1.391     matthew  3121: 		 [$key.'studentcalc:'],
1.620     albertel 3122: 		 $env{'course.'.$cid.'.domain'},
                   3123: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3124: 		.' '.
                   3125: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3126: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3127:         unless ($status eq 'ok ok') {
                   3128:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3129:                     $uname.' at '.$udom.' for '.
1.109     www      3130: 		    $symb.': '.$status);
1.133     albertel 3131:         }
1.553     albertel 3132: 	&delenv('user.state.'.$cid);
1.109     www      3133:     }
                   3134: }
                   3135: 
1.265     albertel 3136: sub get_scalar {
                   3137:     my ($string,$end) = @_;
                   3138:     my $value;
                   3139:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3140: 	$value = $1;
                   3141:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3142: 	$value = $1;
                   3143:     }
                   3144:     return &unescape($value);
                   3145: }
                   3146: 
                   3147: sub array2str {
                   3148:   my (@array) = @_;
                   3149:   my $result=&arrayref2str(\@array);
                   3150:   $result=~s/^__ARRAY_REF__//;
                   3151:   $result=~s/__END_ARRAY_REF__$//;
                   3152:   return $result;
                   3153: }
                   3154: 
1.204     albertel 3155: sub arrayref2str {
                   3156:   my ($arrayref) = @_;
1.265     albertel 3157:   my $result='__ARRAY_REF__';
1.204     albertel 3158:   foreach my $elem (@$arrayref) {
1.265     albertel 3159:     if(ref($elem) eq 'ARRAY') {
                   3160:       $result.=&arrayref2str($elem).'&';
                   3161:     } elsif(ref($elem) eq 'HASH') {
                   3162:       $result.=&hashref2str($elem).'&';
                   3163:     } elsif(ref($elem)) {
                   3164:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3165:     } else {
                   3166:       $result.=&escape($elem).'&';
                   3167:     }
                   3168:   }
                   3169:   $result=~s/\&$//;
1.265     albertel 3170:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3171:   return $result;
                   3172: }
                   3173: 
1.168     albertel 3174: sub hash2str {
1.204     albertel 3175:   my (%hash) = @_;
                   3176:   my $result=&hashref2str(\%hash);
1.265     albertel 3177:   $result=~s/^__HASH_REF__//;
                   3178:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3179:   return $result;
                   3180: }
                   3181: 
                   3182: sub hashref2str {
                   3183:   my ($hashref)=@_;
1.265     albertel 3184:   my $result='__HASH_REF__';
1.800     albertel 3185:   foreach my $key (sort(keys(%$hashref))) {
                   3186:     if (ref($key) eq 'ARRAY') {
                   3187:       $result.=&arrayref2str($key).'=';
                   3188:     } elsif (ref($key) eq 'HASH') {
                   3189:       $result.=&hashref2str($key).'=';
                   3190:     } elsif (ref($key)) {
1.265     albertel 3191:       $result.='=';
1.800     albertel 3192:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3193:     } else {
1.800     albertel 3194: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3195:     }
                   3196: 
1.800     albertel 3197:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3198:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3199:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3200:       $result.=&hashref2str($hashref->{$key}).'&';
                   3201:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3202:        $result.='&';
1.800     albertel 3203:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3204:     } else {
1.800     albertel 3205:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3206:     }
                   3207:   }
1.168     albertel 3208:   $result=~s/\&$//;
1.265     albertel 3209:   $result .= '__END_HASH_REF__';
1.168     albertel 3210:   return $result;
                   3211: }
                   3212: 
                   3213: sub str2hash {
1.265     albertel 3214:     my ($string)=@_;
                   3215:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3216:     return %$hash;
                   3217: }
                   3218: 
                   3219: sub str2hashref {
1.168     albertel 3220:   my ($string) = @_;
1.265     albertel 3221: 
                   3222:   my %hash;
                   3223: 
                   3224:   if($string !~ /^__HASH_REF__/) {
                   3225:       if (! ($string eq '' || !defined($string))) {
                   3226: 	  $hash{'error'}='Not hash reference';
                   3227:       }
                   3228:       return (\%hash, $string);
                   3229:   }
                   3230: 
                   3231:   $string =~ s/^__HASH_REF__//;
                   3232: 
                   3233:   while($string !~ /^__END_HASH_REF__/) {
                   3234:       #key
                   3235:       my $key='';
                   3236:       if($string =~ /^__HASH_REF__/) {
                   3237:           ($key, $string)=&str2hashref($string);
                   3238:           if(defined($key->{'error'})) {
                   3239:               $hash{'error'}='Bad data';
                   3240:               return (\%hash, $string);
                   3241:           }
                   3242:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3243:           ($key, $string)=&str2arrayref($string);
                   3244:           if($key->[0] eq 'Array reference error') {
                   3245:               $hash{'error'}='Bad data';
                   3246:               return (\%hash, $string);
                   3247:           }
                   3248:       } else {
                   3249:           $string =~ s/^(.*?)=//;
1.267     albertel 3250: 	  $key=&unescape($1);
1.265     albertel 3251:       }
                   3252:       $string =~ s/^=//;
                   3253: 
                   3254:       #value
                   3255:       my $value='';
                   3256:       if($string =~ /^__HASH_REF__/) {
                   3257:           ($value, $string)=&str2hashref($string);
                   3258:           if(defined($value->{'error'})) {
                   3259:               $hash{'error'}='Bad data';
                   3260:               return (\%hash, $string);
                   3261:           }
                   3262:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3263:           ($value, $string)=&str2arrayref($string);
                   3264:           if($value->[0] eq 'Array reference error') {
                   3265:               $hash{'error'}='Bad data';
                   3266:               return (\%hash, $string);
                   3267:           }
                   3268:       } else {
                   3269: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3270:       }
                   3271:       $string =~ s/^&//;
                   3272: 
                   3273:       $hash{$key}=$value;
1.204     albertel 3274:   }
1.265     albertel 3275: 
                   3276:   $string =~ s/^__END_HASH_REF__//;
                   3277: 
                   3278:   return (\%hash, $string);
1.204     albertel 3279: }
                   3280: 
                   3281: sub str2array {
1.265     albertel 3282:     my ($string)=@_;
                   3283:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3284:     return @$array;
                   3285: }
                   3286: 
                   3287: sub str2arrayref {
1.204     albertel 3288:   my ($string) = @_;
1.265     albertel 3289:   my @array;
                   3290: 
                   3291:   if($string !~ /^__ARRAY_REF__/) {
                   3292:       if (! ($string eq '' || !defined($string))) {
                   3293: 	  $array[0]='Array reference error';
                   3294:       }
                   3295:       return (\@array, $string);
                   3296:   }
                   3297: 
                   3298:   $string =~ s/^__ARRAY_REF__//;
                   3299: 
                   3300:   while($string !~ /^__END_ARRAY_REF__/) {
                   3301:       my $value='';
                   3302:       if($string =~ /^__HASH_REF__/) {
                   3303:           ($value, $string)=&str2hashref($string);
                   3304:           if(defined($value->{'error'})) {
                   3305:               $array[0] ='Array reference error';
                   3306:               return (\@array, $string);
                   3307:           }
                   3308:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3309:           ($value, $string)=&str2arrayref($string);
                   3310:           if($value->[0] eq 'Array reference error') {
                   3311:               $array[0] ='Array reference error';
                   3312:               return (\@array, $string);
                   3313:           }
                   3314:       } else {
                   3315: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3316:       }
                   3317:       $string =~ s/^&//;
                   3318: 
                   3319:       push(@array, $value);
1.191     harris41 3320:   }
1.265     albertel 3321: 
                   3322:   $string =~ s/^__END_ARRAY_REF__//;
                   3323: 
                   3324:   return (\@array, $string);
1.168     albertel 3325: }
                   3326: 
1.167     albertel 3327: # -------------------------------------------------------------------Temp Store
                   3328: 
1.168     albertel 3329: sub tmpreset {
                   3330:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3331:   if (!$symb) {
                   3332:     $symb=&symbread();
1.620     albertel 3333:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3334:   }
                   3335:   $symb=escape($symb);
                   3336: 
1.620     albertel 3337:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3338:   $namespace=~s/\//\_/g;
                   3339:   $namespace=~s/\W//g;
                   3340: 
1.620     albertel 3341:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3342:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3343:   if ($domain eq 'public' && $stuname eq 'public') {
                   3344:       $stuname=$ENV{'REMOTE_ADDR'};
                   3345:   }
1.168     albertel 3346:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3347:   my %hash;
                   3348:   if (tie(%hash,'GDBM_File',
                   3349: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3350: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3351:     foreach my $key (keys %hash) {
1.180     albertel 3352:       if ($key=~ /:$symb/) {
1.168     albertel 3353: 	delete($hash{$key});
                   3354:       }
                   3355:     }
                   3356:   }
                   3357: }
                   3358: 
1.167     albertel 3359: sub tmpstore {
1.168     albertel 3360:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3361: 
                   3362:   if (!$symb) {
                   3363:     $symb=&symbread();
1.620     albertel 3364:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3365:   }
                   3366:   $symb=escape($symb);
                   3367: 
                   3368:   if (!$namespace) {
                   3369:     # I don't think we would ever want to store this for a course.
                   3370:     # it seems this will only be used if we don't have a course.
1.620     albertel 3371:     #$namespace=$env{'request.course.id'};
1.168     albertel 3372:     #if (!$namespace) {
1.620     albertel 3373:       $namespace=$env{'request.state'};
1.168     albertel 3374:     #}
                   3375:   }
                   3376:   $namespace=~s/\//\_/g;
                   3377:   $namespace=~s/\W//g;
1.620     albertel 3378:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3379:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3380:   if ($domain eq 'public' && $stuname eq 'public') {
                   3381:       $stuname=$ENV{'REMOTE_ADDR'};
                   3382:   }
1.168     albertel 3383:   my $now=time;
                   3384:   my %hash;
                   3385:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3386:   if (tie(%hash,'GDBM_File',
                   3387: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3388: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3389:     $hash{"version:$symb"}++;
                   3390:     my $version=$hash{"version:$symb"};
                   3391:     my $allkeys=''; 
                   3392:     foreach my $key (keys(%$storehash)) {
                   3393:       $allkeys.=$key.':';
1.591     albertel 3394:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3395:     }
                   3396:     $hash{"$version:$symb:timestamp"}=$now;
                   3397:     $allkeys.='timestamp';
                   3398:     $hash{"$version:keys:$symb"}=$allkeys;
                   3399:     if (untie(%hash)) {
                   3400:       return 'ok';
                   3401:     } else {
                   3402:       return "error:$!";
                   3403:     }
                   3404:   } else {
                   3405:     return "error:$!";
                   3406:   }
                   3407: }
1.167     albertel 3408: 
1.168     albertel 3409: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3410: 
1.168     albertel 3411: sub tmprestore {
                   3412:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3413: 
1.168     albertel 3414:   if (!$symb) {
                   3415:     $symb=&symbread();
1.620     albertel 3416:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3417:   }
                   3418:   $symb=escape($symb);
                   3419: 
1.620     albertel 3420:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3421: 
1.620     albertel 3422:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3423:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3424:   if ($domain eq 'public' && $stuname eq 'public') {
                   3425:       $stuname=$ENV{'REMOTE_ADDR'};
                   3426:   }
1.168     albertel 3427:   my %returnhash;
                   3428:   $namespace=~s/\//\_/g;
                   3429:   $namespace=~s/\W//g;
                   3430:   my %hash;
                   3431:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3432:   if (tie(%hash,'GDBM_File',
                   3433: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3434: 	  &GDBM_READER(),0640)) {
1.168     albertel 3435:     my $version=$hash{"version:$symb"};
                   3436:     $returnhash{'version'}=$version;
                   3437:     my $scope;
                   3438:     for ($scope=1;$scope<=$version;$scope++) {
                   3439:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3440:       my @keys=split(/:/,$vkeys);
                   3441:       my $key;
                   3442:       $returnhash{"$scope:keys"}=$vkeys;
                   3443:       foreach $key (@keys) {
1.591     albertel 3444: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3445: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3446:       }
                   3447:     }
1.168     albertel 3448:     if (!(untie(%hash))) {
                   3449:       return "error:$!";
                   3450:     }
                   3451:   } else {
                   3452:     return "error:$!";
                   3453:   }
                   3454:   return %returnhash;
1.167     albertel 3455: }
                   3456: 
1.9       www      3457: # ----------------------------------------------------------------------- Store
                   3458: 
                   3459: sub store {
1.124     www      3460:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3461:     my $home='';
                   3462: 
1.168     albertel 3463:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3464: 
1.213     www      3465:     $symb=&symbclean($symb);
1.122     albertel 3466:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3467: 
1.620     albertel 3468:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3469:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3470: 
                   3471:     &devalidate($symb,$stuname,$domain);
1.109     www      3472: 
                   3473:     $symb=escape($symb);
1.187     www      3474:     if (!$namespace) { 
1.620     albertel 3475:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3476:           return ''; 
                   3477:        } 
                   3478:     }
1.620     albertel 3479:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3480: 
                   3481:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3482:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3483: 
1.12      www      3484:     my $namevalue='';
1.800     albertel 3485:     foreach my $key (keys(%$storehash)) {
                   3486:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3487:     }
1.12      www      3488:     $namevalue=~s/\&$//;
1.187     www      3489:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3490:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3491: }
                   3492: 
1.47      www      3493: # -------------------------------------------------------------- Critical Store
                   3494: 
                   3495: sub cstore {
1.124     www      3496:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3497:     my $home='';
                   3498: 
1.168     albertel 3499:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3500: 
1.213     www      3501:     $symb=&symbclean($symb);
1.122     albertel 3502:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3503: 
1.620     albertel 3504:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3505:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3506: 
                   3507:     &devalidate($symb,$stuname,$domain);
1.109     www      3508: 
                   3509:     $symb=escape($symb);
1.187     www      3510:     if (!$namespace) { 
1.620     albertel 3511:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3512:           return ''; 
                   3513:        } 
                   3514:     }
1.620     albertel 3515:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3516: 
                   3517:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3518:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3519: 
1.47      www      3520:     my $namevalue='';
1.800     albertel 3521:     foreach my $key (keys(%$storehash)) {
                   3522:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3523:     }
1.47      www      3524:     $namevalue=~s/\&$//;
1.187     www      3525:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3526:     return critical
                   3527:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3528: }
                   3529: 
1.9       www      3530: # --------------------------------------------------------------------- Restore
                   3531: 
                   3532: sub restore {
1.124     www      3533:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3534:     my $home='';
                   3535: 
1.168     albertel 3536:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3537: 
1.122     albertel 3538:     if (!$symb) {
                   3539:       unless ($symb=escape(&symbread())) { return ''; }
                   3540:     } else {
1.213     www      3541:       $symb=&escape(&symbclean($symb));
1.122     albertel 3542:     }
1.188     www      3543:     if (!$namespace) { 
1.620     albertel 3544:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3545:           return ''; 
                   3546:        } 
                   3547:     }
1.620     albertel 3548:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3549:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3550:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3551:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3552: 
1.12      www      3553:     my %returnhash=();
1.800     albertel 3554:     foreach my $line (split(/\&/,$answer)) {
                   3555: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3556:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3557:     }
1.75      www      3558:     my $version;
                   3559:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3560:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3561:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3562:        }
1.75      www      3563:     }
1.13      www      3564:     return %returnhash;
1.34      www      3565: }
                   3566: 
                   3567: # ---------------------------------------------------------- Course Description
                   3568: 
                   3569: sub coursedescription {
1.731     albertel 3570:     my ($courseid,$args)=@_;
1.34      www      3571:     $courseid=~s/^\///;
1.49      www      3572:     $courseid=~s/\_/\//g;
1.34      www      3573:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3574:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3575:     my $normalid=$cdomain.'_'.$cnum;
                   3576:     # need to always cache even if we get errors otherwise we keep 
                   3577:     # trying and trying and trying to get the course description.
                   3578:     my %envhash=();
                   3579:     my %returnhash=();
1.731     albertel 3580:     
                   3581:     my $expiretime=600;
                   3582:     if ($env{'request.course.id'} eq $normalid) {
                   3583: 	$expiretime=120;
                   3584:     }
                   3585: 
                   3586:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3587:     if (!$args->{'freshen_cache'}
                   3588: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3589: 	foreach my $key (keys(%env)) {
                   3590: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3591: 	    my ($setting) = $1;
                   3592: 	    $returnhash{$setting} = $env{$key};
                   3593: 	}
                   3594: 	return %returnhash;
                   3595:     }
                   3596: 
                   3597:     # get the data agin
                   3598:     if (!$args->{'one_time'}) {
                   3599: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3600:     }
1.811     albertel 3601: 
1.34      www      3602:     if ($chome ne 'no_host') {
1.302     albertel 3603:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3604:        if (!exists($returnhash{'con_lost'})) {
                   3605:            $returnhash{'home'}= $chome;
                   3606: 	   $returnhash{'domain'} = $cdomain;
                   3607: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3608:            if (!defined($returnhash{'type'})) {
                   3609:                $returnhash{'type'} = 'Course';
                   3610:            }
1.130     albertel 3611:            while (my ($name,$value) = each %returnhash) {
1.53      www      3612:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3613:            }
1.270     www      3614:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3615:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3616: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3617:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3618:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3619:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3620:        }
                   3621:     }
1.731     albertel 3622:     if (!$args->{'one_time'}) {
1.949     raeburn  3623: 	&appenv(\%envhash);
1.731     albertel 3624:     }
1.302     albertel 3625:     return %returnhash;
1.461     www      3626: }
                   3627: 
                   3628: # -------------------------------------------------See if a user is privileged
                   3629: 
                   3630: sub privileged {
                   3631:     my ($username,$domain)=@_;
                   3632:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3633: 			&homeserver($username,$domain));
                   3634:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3635:     my $now=time;
                   3636:     if ($rolesdump ne '') {
1.800     albertel 3637:         foreach my $entry (split(/&/,$rolesdump)) {
                   3638: 	    if ($entry!~/^rolesdef_/) {
                   3639: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3640: 		$area=~s/\_\w\w$//;
                   3641: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3642: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3643: 		    my $active=1;
                   3644: 		    if ($tend) {
                   3645: 			if ($tend<$now) { $active=0; }
                   3646: 		    }
                   3647: 		    if ($tstart) {
                   3648: 			if ($tstart>$now) { $active=0; }
                   3649: 		    }
                   3650: 		    if ($active) { return 1; }
                   3651: 		}
                   3652: 	    }
                   3653: 	}
                   3654:     }
                   3655:     return 0;
1.9       www      3656: }
1.1       albertel 3657: 
1.103     harris41 3658: # -------------------------------------------------------- Get user privileges
1.11      www      3659: 
                   3660: sub rolesinit {
                   3661:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3662:     my %userroles;
1.11      www      3663:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3664:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3665:     my %allroles=();
1.678     raeburn  3666:     my %allgroups=();   
1.11      www      3667:     my $now=time;
1.966     raeburn  3668:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3669:     my $group_privs;
1.11      www      3670: 
                   3671:     if ($rolesdump ne '') {
1.800     albertel 3672:         foreach my $entry (split(/&/,$rolesdump)) {
                   3673: 	  if ($entry!~/^rolesdef_/) {
                   3674:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3675: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3676:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3677: 	    if ($role=~/^cr/) { 
1.807     albertel 3678: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3679: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3680: 		    ($tend,$tstart)=split('_',$trest);
                   3681: 		} else {
                   3682: 		    $trole=$role;
                   3683: 		}
1.678     raeburn  3684:             } elsif ($role =~ m|^gr/|) {
                   3685:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3686:                 ($trole,$group_privs) = split(/\//,$trole);
                   3687:                 $group_privs = &unescape($group_privs);
1.587     albertel 3688: 	    } else {
                   3689: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3690: 	    }
1.743     albertel 3691: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3692: 					 $username);
                   3693: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3694:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3695:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3696:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3697: 		my $spec=$trole.'.'.$area;
                   3698: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3699: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3700:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3701:                 } elsif ($trole eq 'gr') {
                   3702:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3703: 		} else {
1.567     raeburn  3704:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3705: 		}
1.12      www      3706:             }
1.662     raeburn  3707:           }
1.191     harris41 3708:         }
1.743     albertel 3709:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3710:         $userroles{'user.adv'}    = $adv;
                   3711: 	$userroles{'user.author'} = $author;
1.620     albertel 3712:         $env{'user.adv'}=$adv;
1.11      www      3713:     }
1.743     albertel 3714:     return \%userroles;  
1.11      www      3715: }
                   3716: 
1.567     raeburn  3717: sub set_arearole {
                   3718:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3719: # log the associated role with the area
                   3720:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3721:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3722: }
                   3723: 
                   3724: sub custom_roleprivs {
                   3725:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3726:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3727:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3728:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3729:         my ($rdummy,$roledef)=
                   3730:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3731:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3732:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3733:             if (defined($syspriv)) {
                   3734:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3735:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3736:             }
                   3737:             if ($tdomain ne '') {
                   3738:                 if (defined($dompriv)) {
                   3739:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3740:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3741:                 }
                   3742:                 if (($trest ne '') && (defined($coursepriv))) {
                   3743:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3744:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3745:                 }
                   3746:             }
                   3747:         }
                   3748:     }
                   3749: }
                   3750: 
1.678     raeburn  3751: sub group_roleprivs {
                   3752:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3753:     my $access = 1;
                   3754:     my $now = time;
                   3755:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3756:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3757:     if ($access) {
1.811     albertel 3758:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3759:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3760:     }
                   3761: }
1.567     raeburn  3762: 
                   3763: sub standard_roleprivs {
                   3764:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3765:     if (defined($pr{$trole.':s'})) {
                   3766:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3767:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3768:     }
                   3769:     if ($tdomain ne '') {
                   3770:         if (defined($pr{$trole.':d'})) {
                   3771:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3772:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3773:         }
                   3774:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3775:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3776:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3777:         }
                   3778:     }
                   3779: }
                   3780: 
                   3781: sub set_userprivs {
1.678     raeburn  3782:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3783:     my $author=0;
                   3784:     my $adv=0;
1.678     raeburn  3785:     my %grouproles = ();
                   3786:     if (keys(%{$allgroups}) > 0) {
                   3787:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3788:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3789:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3790:                 $trole = $1;
                   3791:                 $area = $2;
1.681     raeburn  3792:                 $sec = $3;
                   3793:                 $extendedarea = $area.$sec;
                   3794:                 if (exists($$allgroups{$area})) {
                   3795:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3796:                         my $spec = $trole.'.'.$extendedarea;
                   3797:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3798:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3799:                     }
                   3800:                 }
                   3801:             }
                   3802:         }
                   3803:     }
1.800     albertel 3804:     foreach my $group (keys(%grouproles)) {
                   3805:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3806:     }
1.800     albertel 3807:     foreach my $role (keys(%{$allroles})) {
                   3808:         my %thesepriv;
1.941     raeburn  3809:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3810:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3811:             if ($item ne '') {
                   3812:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3813:                 if ($restrictions eq '') {
                   3814:                     $thesepriv{$privilege}='F';
                   3815:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3816:                     $thesepriv{$privilege}.=$restrictions;
                   3817:                 }
                   3818:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3819:             }
                   3820:         }
                   3821:         my $thesestr='';
1.800     albertel 3822:         foreach my $priv (keys(%thesepriv)) {
                   3823: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3824: 	}
                   3825:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3826:     }
                   3827:     return ($author,$adv);
                   3828: }
                   3829: 
1.12      www      3830: # --------------------------------------------------------------- get interface
                   3831: 
                   3832: sub get {
1.131     albertel 3833:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3834:    my $items='';
1.800     albertel 3835:    foreach my $item (@$storearr) {
                   3836:        $items.=&escape($item).'&';
1.191     harris41 3837:    }
1.12      www      3838:    $items=~s/\&$//;
1.620     albertel 3839:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3840:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3841:    my $uhome=&homeserver($uname,$udomain);
                   3842: 
1.133     albertel 3843:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3844:    my @pairs=split(/\&/,$rep);
1.273     albertel 3845:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3846:      return @pairs;
                   3847:    }
1.15      www      3848:    my %returnhash=();
1.42      www      3849:    my $i=0;
1.800     albertel 3850:    foreach my $item (@$storearr) {
                   3851:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3852:       $i++;
1.191     harris41 3853:    }
1.15      www      3854:    return %returnhash;
1.27      www      3855: }
                   3856: 
                   3857: # --------------------------------------------------------------- del interface
                   3858: 
                   3859: sub del {
1.133     albertel 3860:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3861:    my $items='';
1.800     albertel 3862:    foreach my $item (@$storearr) {
                   3863:        $items.=&escape($item).'&';
1.191     harris41 3864:    }
1.984   ! neumanie 3865: 
1.27      www      3866:    $items=~s/\&$//;
1.620     albertel 3867:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3868:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3869:    my $uhome=&homeserver($uname,$udomain);
                   3870:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3871: }
                   3872: 
                   3873: # -------------------------------------------------------------- dump interface
                   3874: 
                   3875: sub dump {
1.755     albertel 3876:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3878:     if (!$uname) { $uname=$env{'user.name'}; }
                   3879:     my $uhome=&homeserver($uname,$udomain);
                   3880:     if ($regexp) {
                   3881: 	$regexp=&escape($regexp);
                   3882:     } else {
                   3883: 	$regexp='.';
                   3884:     }
                   3885:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3886:     my @pairs=split(/\&/,$rep);
                   3887:     my %returnhash=();
                   3888:     foreach my $item (@pairs) {
                   3889: 	my ($key,$value)=split(/=/,$item,2);
                   3890: 	$key = &unescape($key);
                   3891: 	next if ($key =~ /^error: 2 /);
                   3892: 	$returnhash{$key}=&thaw_unescape($value);
                   3893:     }
                   3894:     return %returnhash;
1.407     www      3895: }
                   3896: 
1.717     albertel 3897: # --------------------------------------------------------- dumpstore interface
                   3898: 
                   3899: sub dumpstore {
                   3900:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3901:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3902:    if (!$uname) { $uname=$env{'user.name'}; }
                   3903:    my $uhome=&homeserver($uname,$udomain);
                   3904:    if ($regexp) {
                   3905:        $regexp=&escape($regexp);
                   3906:    } else {
                   3907:        $regexp='.';
                   3908:    }
                   3909:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3910:    my @pairs=split(/\&/,$rep);
                   3911:    my %returnhash=();
                   3912:    foreach my $item (@pairs) {
                   3913:        my ($key,$value)=split(/=/,$item,2);
                   3914:        next if ($key =~ /^error: 2 /);
                   3915:        $returnhash{$key}=&thaw_unescape($value);
                   3916:    }
                   3917:    return %returnhash;
1.717     albertel 3918: }
                   3919: 
1.407     www      3920: # -------------------------------------------------------------- keys interface
                   3921: 
                   3922: sub getkeys {
                   3923:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3924:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3925:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3926:    my $uhome=&homeserver($uname,$udomain);
                   3927:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3928:    my @keyarray=();
1.800     albertel 3929:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3930:       next if ($key =~ /^error: 2 /);
1.800     albertel 3931:       push(@keyarray,&unescape($key));
1.407     www      3932:    }
                   3933:    return @keyarray;
1.318     matthew  3934: }
                   3935: 
1.319     matthew  3936: # --------------------------------------------------------------- currentdump
                   3937: sub currentdump {
1.328     matthew  3938:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3939:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3940:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3941:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3942:    my $uhome = &homeserver($sname,$sdom);
                   3943:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3944:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3945:    #
1.318     matthew  3946:    my %returnhash=();
1.319     matthew  3947:    #
                   3948:    if ($rep eq "unknown_cmd") { 
                   3949:        # an old lond will not know currentdump
                   3950:        # Do a dump and make it look like a currentdump
1.822     albertel 3951:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3952:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3953:        my %hash = @tmp;
                   3954:        @tmp=();
1.424     matthew  3955:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3956:    } else {
                   3957:        my @pairs=split(/\&/,$rep);
1.800     albertel 3958:        foreach my $pair (@pairs) {
                   3959:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3960:            my ($symb,$param) = split(/:/,$key);
                   3961:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3962:                                                         &thaw_unescape($value);
1.319     matthew  3963:        }
1.191     harris41 3964:    }
1.12      www      3965:    return %returnhash;
1.424     matthew  3966: }
                   3967: 
                   3968: sub convert_dump_to_currentdump{
                   3969:     my %hash = %{shift()};
                   3970:     my %returnhash;
                   3971:     # Code ripped from lond, essentially.  The only difference
                   3972:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3973:     # we might run in to problems with parameter names =~ /^v\./
                   3974:     while (my ($key,$value) = each(%hash)) {
                   3975:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3976: 	$symb  = &unescape($symb);
                   3977: 	$param = &unescape($param);
1.424     matthew  3978:         next if ($v eq 'version' || $symb eq 'keys');
                   3979:         next if (exists($returnhash{$symb}) &&
                   3980:                  exists($returnhash{$symb}->{$param}) &&
                   3981:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3982:         $returnhash{$symb}->{$param}=$value;
                   3983:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3984:     }
                   3985:     #
                   3986:     # Remove all of the keys in the hashes which keep track of
                   3987:     # the version of the parameter.
                   3988:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3989:         # use a foreach because we are going to delete from the hash.
                   3990:         foreach my $key (keys(%$param_hash)) {
                   3991:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3992:         }
                   3993:     }
                   3994:     return \%returnhash;
1.12      www      3995: }
                   3996: 
1.627     albertel 3997: # ------------------------------------------------------ critical inc interface
                   3998: 
                   3999: sub cinc {
                   4000:     return &inc(@_,'critical');
                   4001: }
                   4002: 
1.449     matthew  4003: # --------------------------------------------------------------- inc interface
                   4004: 
                   4005: sub inc {
1.627     albertel 4006:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4007:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4008:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4009:     my $uhome=&homeserver($uname,$udomain);
                   4010:     my $items='';
                   4011:     if (! ref($store)) {
                   4012:         # got a single value, so use that instead
                   4013:         $items = &escape($store).'=&';
                   4014:     } elsif (ref($store) eq 'SCALAR') {
                   4015:         $items = &escape($$store).'=&';        
                   4016:     } elsif (ref($store) eq 'ARRAY') {
                   4017:         $items = join('=&',map {&escape($_);} @{$store});
                   4018:     } elsif (ref($store) eq 'HASH') {
                   4019:         while (my($key,$value) = each(%{$store})) {
                   4020:             $items.= &escape($key).'='.&escape($value).'&';
                   4021:         }
                   4022:     }
                   4023:     $items=~s/\&$//;
1.627     albertel 4024:     if ($critical) {
                   4025: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4026:     } else {
                   4027: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4028:     }
1.449     matthew  4029: }
                   4030: 
1.12      www      4031: # --------------------------------------------------------------- put interface
                   4032: 
                   4033: sub put {
1.134     albertel 4034:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4036:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4037:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4038:    my $items='';
1.800     albertel 4039:    foreach my $item (keys(%$storehash)) {
                   4040:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4041:    }
1.12      www      4042:    $items=~s/\&$//;
1.134     albertel 4043:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4044: }
                   4045: 
1.631     albertel 4046: # ------------------------------------------------------------ newput interface
                   4047: 
                   4048: sub newput {
                   4049:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4050:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4051:    if (!$uname) { $uname=$env{'user.name'}; }
                   4052:    my $uhome=&homeserver($uname,$udomain);
                   4053:    my $items='';
                   4054:    foreach my $key (keys(%$storehash)) {
                   4055:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4056:    }
                   4057:    $items=~s/\&$//;
                   4058:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4059: }
                   4060: 
                   4061: # ---------------------------------------------------------  putstore interface
                   4062: 
1.524     raeburn  4063: sub putstore {
1.715     albertel 4064:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4066:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4067:    my $uhome=&homeserver($uname,$udomain);
                   4068:    my $items='';
1.715     albertel 4069:    foreach my $key (keys(%$storehash)) {
                   4070:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4071:    }
1.715     albertel 4072:    $items=~s/\&$//;
1.716     albertel 4073:    my $esc_symb=&escape($symb);
                   4074:    my $esc_v=&escape($version);
1.715     albertel 4075:    my $reply =
1.716     albertel 4076:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4077: 	      $uhome);
                   4078:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4079:        # gfall back to way things use to be done
1.715     albertel 4080:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4081: 			    $uname);
1.524     raeburn  4082:    }
1.715     albertel 4083:    return $reply;
                   4084: }
                   4085: 
                   4086: sub old_putstore {
1.716     albertel 4087:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4088:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4089:     if (!$uname) { $uname=$env{'user.name'}; }
                   4090:     my $uhome=&homeserver($uname,$udomain);
                   4091:     my %newstorehash;
1.800     albertel 4092:     foreach my $item (keys(%$storehash)) {
                   4093: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4094: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4095:     }
                   4096:     my $items='';
                   4097:     my %allitems = ();
1.800     albertel 4098:     foreach my $item (keys(%newstorehash)) {
                   4099: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4100: 	    my $key = $1.':keys:'.$2;
                   4101: 	    $allitems{$key} .= $3.':';
                   4102: 	}
1.800     albertel 4103: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4104:     }
1.800     albertel 4105:     foreach my $item (keys(%allitems)) {
                   4106: 	$allitems{$item} =~ s/\:$//;
                   4107: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4108:     }
                   4109:     $items=~s/\&$//;
                   4110:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4111: }
                   4112: 
1.47      www      4113: # ------------------------------------------------------ critical put interface
                   4114: 
                   4115: sub cput {
1.134     albertel 4116:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4118:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4119:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4120:    my $items='';
1.800     albertel 4121:    foreach my $item (keys(%$storehash)) {
                   4122:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4123:    }
1.47      www      4124:    $items=~s/\&$//;
1.134     albertel 4125:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4126: }
                   4127: 
                   4128: # -------------------------------------------------------------- eget interface
                   4129: 
                   4130: sub eget {
1.133     albertel 4131:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4132:    my $items='';
1.800     albertel 4133:    foreach my $item (@$storearr) {
                   4134:        $items.=&escape($item).'&';
1.191     harris41 4135:    }
1.12      www      4136:    $items=~s/\&$//;
1.620     albertel 4137:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4138:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4139:    my $uhome=&homeserver($uname,$udomain);
                   4140:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4141:    my @pairs=split(/\&/,$rep);
                   4142:    my %returnhash=();
1.42      www      4143:    my $i=0;
1.800     albertel 4144:    foreach my $item (@$storearr) {
                   4145:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4146:       $i++;
1.191     harris41 4147:    }
1.12      www      4148:    return %returnhash;
                   4149: }
                   4150: 
1.667     albertel 4151: # ------------------------------------------------------------ tmpput interface
                   4152: sub tmpput {
1.802     raeburn  4153:     my ($storehash,$server,$context)=@_;
1.667     albertel 4154:     my $items='';
1.800     albertel 4155:     foreach my $item (keys(%$storehash)) {
                   4156: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4157:     }
                   4158:     $items=~s/\&$//;
1.802     raeburn  4159:     if (defined($context)) {
                   4160:         $items .= ':'.&escape($context);
                   4161:     }
1.667     albertel 4162:     return &reply("tmpput:$items",$server);
                   4163: }
                   4164: 
                   4165: # ------------------------------------------------------------ tmpget interface
                   4166: sub tmpget {
1.688     albertel 4167:     my ($token,$server)=@_;
                   4168:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4169:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4170:     my %returnhash;
                   4171:     foreach my $item (split(/\&/,$rep)) {
                   4172: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4173:         next if ($key =~ /^error: 2 /);
1.667     albertel 4174: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4175:     }
                   4176:     return %returnhash;
                   4177: }
                   4178: 
1.688     albertel 4179: # ------------------------------------------------------------ tmpget interface
                   4180: sub tmpdel {
                   4181:     my ($token,$server)=@_;
                   4182:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4183:     return &reply("tmpdel:$token",$server);
                   4184: }
                   4185: 
1.765     albertel 4186: # -------------------------------------------------- portfolio access checking
                   4187: 
                   4188: sub portfolio_access {
1.766     albertel 4189:     my ($requrl) = @_;
1.765     albertel 4190:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4191:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4192:     if ($result) {
                   4193:         my %setters;
                   4194:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4195:             my ($startblock,$endblock) =
                   4196:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4197:             if ($startblock && $endblock) {
                   4198:                 return 'B';
                   4199:             }
                   4200:         } else {
                   4201:             my ($startblock,$endblock) =
                   4202:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4203:             if ($startblock && $endblock) {
                   4204:                 return 'B';
                   4205:             }
                   4206:         }
                   4207:     }
1.765     albertel 4208:     if ($result eq 'ok') {
1.766     albertel 4209:        return 'F';
1.765     albertel 4210:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4211:        return 'A';
1.765     albertel 4212:     }
1.766     albertel 4213:     return '';
1.765     albertel 4214: }
                   4215: 
                   4216: sub get_portfolio_access {
1.767     albertel 4217:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4218: 
                   4219:     if (!ref($access_hash)) {
                   4220: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4221: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4222: 						   $file_name);
                   4223: 	$access_hash = $access_controls{$file_name};
                   4224:     }
                   4225: 
1.765     albertel 4226:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4227:     my $now = time;
                   4228:     if (ref($access_hash) eq 'HASH') {
                   4229:         foreach my $key (keys(%{$access_hash})) {
                   4230:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4231:             if ($start > $now) {
                   4232:                 next;
                   4233:             }
                   4234:             if ($end && $end<$now) {
                   4235:                 next;
                   4236:             }
                   4237:             if ($scope eq 'public') {
                   4238:                 $public = $key;
                   4239:                 last;
                   4240:             } elsif ($scope eq 'guest') {
                   4241:                 $guest = $key;
                   4242:             } elsif ($scope eq 'domains') {
                   4243:                 push(@domains,$key);
                   4244:             } elsif ($scope eq 'users') {
                   4245:                 push(@users,$key);
                   4246:             } elsif ($scope eq 'course') {
                   4247:                 push(@courses,$key);
                   4248:             } elsif ($scope eq 'group') {
                   4249:                 push(@groups,$key);
                   4250:             }
                   4251:         }
                   4252:         if ($public) {
                   4253:             return 'ok';
                   4254:         }
                   4255:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4256:             if ($guest) {
                   4257:                 return $guest;
                   4258:             }
                   4259:         } else {
                   4260:             if (@domains > 0) {
                   4261:                 foreach my $domkey (@domains) {
                   4262:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4263:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4264:                             return 'ok';
                   4265:                         }
                   4266:                     }
                   4267:                 }
                   4268:             }
                   4269:             if (@users > 0) {
                   4270:                 foreach my $userkey (@users) {
1.865     raeburn  4271:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4272:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4273:                             if (ref($item) eq 'HASH') {
                   4274:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4275:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4276:                                     return 'ok';
                   4277:                                 }
                   4278:                             }
                   4279:                         }
                   4280:                     } 
1.765     albertel 4281:                 }
                   4282:             }
                   4283:             my %roleshash;
                   4284:             my @courses_and_groups = @courses;
                   4285:             push(@courses_and_groups,@groups); 
                   4286:             if (@courses_and_groups > 0) {
                   4287:                 my (%allgroups,%allroles); 
                   4288:                 my ($start,$end,$role,$sec,$group);
                   4289:                 foreach my $envkey (%env) {
1.811     albertel 4290:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4291:                         my $cid = $2.'_'.$3; 
                   4292:                         if ($1 eq 'gr') {
                   4293:                             $group = $4;
                   4294:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4295:                         } else {
                   4296:                             if ($4 eq '') {
                   4297:                                 $sec = 'none';
                   4298:                             } else {
                   4299:                                 $sec = $4;
                   4300:                             }
                   4301:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4302:                         }
1.811     albertel 4303:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4304:                         my $cid = $2.'_'.$3;
                   4305:                         if ($4 eq '') {
                   4306:                             $sec = 'none';
                   4307:                         } else {
                   4308:                             $sec = $4;
                   4309:                         }
                   4310:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4311:                     }
                   4312:                 }
                   4313:                 if (keys(%allroles) == 0) {
                   4314:                     return;
                   4315:                 }
                   4316:                 foreach my $key (@courses_and_groups) {
                   4317:                     my %content = %{$$access_hash{$key}};
                   4318:                     my $cnum = $content{'number'};
                   4319:                     my $cdom = $content{'domain'};
                   4320:                     my $cid = $cdom.'_'.$cnum;
                   4321:                     if (!exists($allroles{$cid})) {
                   4322:                         next;
                   4323:                     }    
                   4324:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4325:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4326:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4327:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4328:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4329:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4330:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4331:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4332:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4333:                                         if (grep/^all$/,@sections) {
                   4334:                                             return 'ok';
                   4335:                                         } else {
                   4336:                                             if (grep/^$sec$/,@sections) {
                   4337:                                                 return 'ok';
                   4338:                                             }
                   4339:                                         }
                   4340:                                     }
                   4341:                                 }
                   4342:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4343:                                     if (grep/^none$/,@groups) {
                   4344:                                         return 'ok';
                   4345:                                     }
                   4346:                                 } else {
                   4347:                                     if (grep/^all$/,@groups) {
                   4348:                                         return 'ok';
                   4349:                                     } 
                   4350:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4351:                                         if (grep/^$group$/,@groups) {
                   4352:                                             return 'ok';
                   4353:                                         }
                   4354:                                     }
                   4355:                                 } 
                   4356:                             }
                   4357:                         }
                   4358:                     }
                   4359:                 }
                   4360:             }
                   4361:             if ($guest) {
                   4362:                 return $guest;
                   4363:             }
                   4364:         }
                   4365:     }
                   4366:     return;
                   4367: }
                   4368: 
                   4369: sub course_group_datechecker {
                   4370:     my ($dates,$now,$status) = @_;
                   4371:     my ($start,$end) = split(/\./,$dates);
                   4372:     if (!$start && !$end) {
                   4373:         return 'ok';
                   4374:     }
                   4375:     if (grep/^active$/,@{$status}) {
                   4376:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4377:             return 'ok';
                   4378:         }
                   4379:     }
                   4380:     if (grep/^previous$/,@{$status}) {
                   4381:         if ($end > $now ) {
                   4382:             return 'ok';
                   4383:         }
                   4384:     }
                   4385:     if (grep/^future$/,@{$status}) {
                   4386:         if ($start > $now) {
                   4387:             return 'ok';
                   4388:         }
                   4389:     }
                   4390:     return; 
                   4391: }
                   4392: 
                   4393: sub parse_portfolio_url {
                   4394:     my ($url) = @_;
                   4395: 
                   4396:     my ($type,$udom,$unum,$group,$file_name);
                   4397:     
1.823     albertel 4398:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4399: 	$type = 1;
                   4400:         $udom = $1;
                   4401:         $unum = $2;
                   4402:         $file_name = $3;
1.823     albertel 4403:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4404: 	$type = 2;
                   4405:         $udom = $1;
                   4406:         $unum = $2;
                   4407:         $group = $3;
                   4408:         $file_name = $3.'/'.$4;
                   4409:     }
                   4410:     if (wantarray) {
                   4411: 	return ($type,$udom,$unum,$file_name,$group);
                   4412:     }
                   4413:     return $type;
                   4414: }
                   4415: 
                   4416: sub is_portfolio_url {
                   4417:     my ($url) = @_;
                   4418:     return scalar(&parse_portfolio_url($url));
                   4419: }
                   4420: 
1.798     raeburn  4421: sub is_portfolio_file {
                   4422:     my ($file) = @_;
1.820     raeburn  4423:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4424:         return 1;
                   4425:     }
                   4426:     return;
                   4427: }
                   4428: 
1.976     raeburn  4429: sub usertools_access {
1.978     raeburn  4430:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4431:     my $access;
                   4432:     my %tools = (
                   4433:                   aboutme   => 1,
                   4434:                   blog      => 1,
                   4435:                   portfolio => 1,
                   4436:                 );
                   4437:     return if (!defined($tools{$tool}));
                   4438: 
                   4439:     if ((!defined($udom)) || (!defined($uname))) {
                   4440:         $udom = $env{'user.domain'};
                   4441:         $uname = $env{'user.name'};
                   4442:     }
                   4443: 
1.978     raeburn  4444:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4445:         if ($action ne 'reload') {
                   4446:             return $env{'environment.availabletools.'.$tool};
                   4447:         } 
1.976     raeburn  4448:     }
                   4449: 
                   4450:     my ($toolstatus,$inststatus);
                   4451: 
                   4452:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4453:         $toolstatus = $env{'environment.tools.'.$tool};
                   4454:         $inststatus = $env{'environment.inststatus'};
                   4455:     } else {
                   4456:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4457:         $toolstatus = $userenv{'tools.'.$tool};
                   4458:         $inststatus = $userenv{'inststatus'};
                   4459:     }
                   4460: 
                   4461:     if ($toolstatus ne '') {
                   4462:         if ($toolstatus) {
                   4463:             $access = 1;
                   4464:         } else {
                   4465:             $access = 0;
                   4466:         }
                   4467:         return $access;
                   4468:     }
                   4469: 
                   4470:     my $is_adv = &is_advanced_user($udom,$uname);
                   4471:     my %domdef = &get_domain_defaults($udom);
                   4472:     if (ref($domdef{$tool}) eq 'HASH') {
                   4473:         if ($is_adv) {
                   4474:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4475:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4476:                     $access = 1;
                   4477:                 } else {
                   4478:                     $access = 0;
                   4479:                 }
                   4480:                 return $access;
                   4481:             }
                   4482:         }
                   4483:         if ($inststatus ne '') {
                   4484:             my ($hasaccess,$hasnoaccess);
                   4485:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4486:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4487:                     if ($domdef{$tool}{$affiliation}) {
                   4488:                         $hasaccess = 1;
                   4489:                     } else {
                   4490:                         $hasnoaccess = 1;
                   4491:                     }
                   4492:                 }
                   4493:             }
                   4494:             if ($hasaccess || $hasnoaccess) {
                   4495:                 if ($hasaccess) {
                   4496:                     $access = 1;
                   4497:                 } elsif ($hasnoaccess) {
                   4498:                     $access = 0; 
                   4499:                 }
                   4500:                 return $access;
                   4501:             }
                   4502:         } else {
                   4503:             if ($domdef{$tool}{'default'} ne '') {
                   4504:                 if ($domdef{$tool}{'default'}) {
                   4505:                     $access = 1;
                   4506:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4507:                     $access = 0;
                   4508:                 }
                   4509:                 return $access;
                   4510:             }
                   4511:         }
                   4512:     } else {
                   4513:         $access = 1;
                   4514:         return $access;
                   4515:     }
                   4516: }
                   4517: 
                   4518: sub is_advanced_user {
                   4519:     my ($udom,$uname) = @_;
                   4520:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4521:     my %allroles;
                   4522:     my $is_adv;
                   4523:     foreach my $role (keys(%roleshash)) {
                   4524:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4525:         my $area = '/'.$tdomain.'/'.$trest;
                   4526:         if ($sec ne '') {
                   4527:             $area .= '/'.$sec;
                   4528:         }
                   4529:         if (($area ne '') && ($trole ne '')) {
                   4530:             my $spec=$trole.'.'.$area;
                   4531:             if ($trole =~ /^cr\//) {
                   4532:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4533:             } elsif ($trole ne 'gr') {
                   4534:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4535:             }
                   4536:         }
                   4537:     }
                   4538:     foreach my $role (keys(%allroles)) {
                   4539:         last if ($is_adv);
                   4540:         foreach my $item (split(/:/,$allroles{$role})) {
                   4541:             if ($item ne '') {
                   4542:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4543:                 if ($privilege eq 'adv') {
                   4544:                     $is_adv = 1;
                   4545:                     last;
                   4546:                 }
                   4547:             }
                   4548:         }
                   4549:     }
                   4550:     return $is_adv;
                   4551: }
1.798     raeburn  4552: 
1.341     www      4553: # ---------------------------------------------- Custom access rule evaluation
                   4554: 
                   4555: sub customaccess {
                   4556:     my ($priv,$uri)=@_;
1.807     albertel 4557:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4558:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4559:     $udom = &LONCAPA::clean_domain($udom);
                   4560:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4561:     my $access=0;
1.800     albertel 4562:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4563: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4564: 	if ($type eq 'user') {
                   4565: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4566: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4567: 		if ($tdom) {
                   4568: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4569: 		}
1.896     albertel 4570: 		if ($tuname) {
                   4571: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4572: 		}
                   4573: 		$access=($effect eq 'allow');
                   4574: 		last;
                   4575: 	    }
                   4576: 	} else {
                   4577: 	    if ($role) {
                   4578: 		if ($role ne $urole) { next; }
                   4579: 	    }
                   4580: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4581: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4582: 		if ($tdom) {
                   4583: 		    if ($tdom ne $udom) { next; }
                   4584: 		}
                   4585: 		if ($tcrs) {
                   4586: 		    if ($tcrs ne $ucrs) { next; }
                   4587: 		}
                   4588: 		if ($tsec) {
                   4589: 		    if ($tsec ne $usec) { next; }
                   4590: 		}
                   4591: 		$access=($effect eq 'allow');
                   4592: 		last;
                   4593: 	    }
                   4594: 	    if ($realm eq '' && $role eq '') {
                   4595: 		$access=($effect eq 'allow');
                   4596: 	    }
1.402     bowersj2 4597: 	}
1.341     www      4598:     }
                   4599:     return $access;
                   4600: }
                   4601: 
1.103     harris41 4602: # ------------------------------------------------- Check for a user privilege
1.12      www      4603: 
                   4604: sub allowed {
1.810     raeburn  4605:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4606:     my $ver_orguri=$uri;
1.439     www      4607:     $uri=&deversion($uri);
1.152     www      4608:     my $orguri=$uri;
1.52      www      4609:     $uri=&declutter($uri);
1.809     raeburn  4610: 
1.810     raeburn  4611:     if ($priv eq 'evb') {
                   4612: # Evade communication block restrictions for specified role in a course
                   4613:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4614:             return $1;
                   4615:         } else {
                   4616:             return;
                   4617:         }
                   4618:     }
                   4619: 
1.620     albertel 4620:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4621: # Free bre access to adm and meta resources
1.775     albertel 4622:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4623: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4624: 	&& ($priv eq 'bre')) {
1.14      www      4625: 	return 'F';
1.159     www      4626:     }
                   4627: 
1.545     banghart 4628: # Free bre access to user's own portfolio contents
1.714     raeburn  4629:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4630:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4631: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4632:         my %setters;
                   4633:         my ($startblock,$endblock) = 
                   4634:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4635:         if ($startblock && $endblock) {
                   4636:             return 'B';
                   4637:         } else {
                   4638:             return 'F';
                   4639:         }
1.545     banghart 4640:     }
                   4641: 
1.762     raeburn  4642: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4643:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4644:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4645:         if (exists($env{'request.course.id'})) {
                   4646:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4647:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4648:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4649:                 my $courseprivid=$env{'request.course.id'};
                   4650:                 $courseprivid=~s/\_/\//;
                   4651:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4652:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4653:                     return $1; 
1.762     raeburn  4654:                 } else {
                   4655:                     if ($env{'request.course.sec'}) {
                   4656:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4657:                     }
                   4658:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4659:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4660:                         return $2;
                   4661:                     }
1.714     raeburn  4662:                 }
                   4663:             }
                   4664:         }
                   4665:     }
                   4666: 
1.159     www      4667: # Free bre to public access
                   4668: 
                   4669:     if ($priv eq 'bre') {
1.238     www      4670:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4671: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4672:            return 'F'; 
                   4673:         }
1.238     www      4674:         if ($copyright eq 'priv') {
                   4675:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4676: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4677: 		return '';
                   4678:             }
                   4679:         }
                   4680:         if ($copyright eq 'domain') {
                   4681:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4682: 	    unless (($env{'user.domain'} eq $1) ||
                   4683:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4684: 		return '';
                   4685:             }
1.262     matthew  4686:         }
1.620     albertel 4687:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4688:             # Library role, so allow browsing of resources in this domain.
                   4689:             return 'F';
1.238     www      4690:         }
1.341     www      4691:         if ($copyright eq 'custom') {
                   4692: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4693:         }
1.14      www      4694:     }
1.264     matthew  4695:     # Domain coordinator is trying to create a course
1.620     albertel 4696:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4697:         # uri is the requested domain in this case.
                   4698:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4699:         # a role of dc for the domain in question.
1.620     albertel 4700:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4701:     }
1.29      www      4702: 
1.52      www      4703:     my $thisallowed='';
                   4704:     my $statecond=0;
                   4705:     my $courseprivid='';
                   4706: 
                   4707: # Course
                   4708: 
1.620     albertel 4709:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4710:        $thisallowed.=$1;
                   4711:     }
1.29      www      4712: 
1.52      www      4713: # Domain
                   4714: 
1.620     albertel 4715:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4716:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4717:        $thisallowed.=$1;
                   4718:     }
1.52      www      4719: 
                   4720: # Course: uri itself is a course
1.66      www      4721:     my $courseuri=$uri;
                   4722:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4723:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4724: 
1.620     albertel 4725:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4726:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4727:        $thisallowed.=$1;
                   4728:     }
1.29      www      4729: 
1.665     albertel 4730: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4731: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4732:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4733: 	$thisallowed='';
1.671     raeburn  4734:         my ($match)=&is_on_map($uri);
                   4735:         if ($match) {
                   4736:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4737:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4738:                 $thisallowed.=$1;
                   4739:             }
                   4740:         } else {
1.705     albertel 4741:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4742:             if ($refuri) {
                   4743:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4744:                     $thisallowed='F';
1.671     raeburn  4745:                 } else {
                   4746:                     $refuri=&declutter($refuri);
                   4747:                     my ($match) = &is_on_map($refuri);
                   4748:                     if ($match) {
                   4749:                         $thisallowed='F';
                   4750:                     }
1.669     raeburn  4751:                 }
1.671     raeburn  4752:             }
                   4753:         }
1.314     www      4754:     }
1.492     albertel 4755: 
1.766     albertel 4756:     if ($priv eq 'bre'
                   4757: 	&& $thisallowed ne 'F' 
                   4758: 	&& $thisallowed ne '2'
                   4759: 	&& &is_portfolio_url($uri)) {
                   4760: 	$thisallowed = &portfolio_access($uri);
                   4761:     }
                   4762:     
1.52      www      4763: # Full access at system, domain or course-wide level? Exit.
1.29      www      4764:     if ($thisallowed=~/F/) {
                   4765: 	return 'F';
                   4766:     }
                   4767: 
1.52      www      4768: # If this is generating or modifying users, exit with special codes
1.29      www      4769: 
1.643     www      4770:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4771: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4772: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4773: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4774: 	    unless ($auname) { return $thisallowed; }
                   4775: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4776: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4777: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4778: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4779: 	}
1.52      www      4780: 	return $thisallowed;
                   4781:     }
                   4782: #
1.103     harris41 4783: # Gathered so far: system, domain and course wide privileges
1.52      www      4784: #
                   4785: # Course: See if uri or referer is an individual resource that is part of 
                   4786: # the course
                   4787: 
1.620     albertel 4788:     if ($env{'request.course.id'}) {
1.232     www      4789: 
1.620     albertel 4790:        $courseprivid=$env{'request.course.id'};
                   4791:        if ($env{'request.course.sec'}) {
                   4792:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4793:        }
                   4794:        $courseprivid=~s/\_/\//;
                   4795:        my $checkreferer=1;
1.232     www      4796:        my ($match,$cond)=&is_on_map($uri);
                   4797:        if ($match) {
                   4798:            $statecond=$cond;
1.620     albertel 4799:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4800:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4801:                $thisallowed.=$1;
                   4802:                $checkreferer=0;
                   4803:            }
1.29      www      4804:        }
1.83      www      4805:        
1.148     www      4806:        if ($checkreferer) {
1.620     albertel 4807: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4808:             unless ($refuri) {
1.800     albertel 4809:                 foreach my $key (keys(%env)) {
                   4810: 		    if ($key=~/^httpref\..*\*/) {
                   4811: 			my $pattern=$key;
1.156     www      4812:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4813:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4814:                         $pattern=~s/\//\\\//g;
1.152     www      4815:                         if ($orguri=~/$pattern/) {
1.800     albertel 4816: 			    $refuri=$env{$key};
1.148     www      4817:                         }
                   4818:                     }
1.191     harris41 4819:                 }
1.148     www      4820:             }
1.232     www      4821: 
1.148     www      4822:          if ($refuri) { 
1.152     www      4823: 	  $refuri=&declutter($refuri);
1.232     www      4824:           my ($match,$cond)=&is_on_map($refuri);
                   4825:             if ($match) {
                   4826:               my $refstatecond=$cond;
1.620     albertel 4827:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4828:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4829:                   $thisallowed.=$1;
1.53      www      4830:                   $uri=$refuri;
                   4831:                   $statecond=$refstatecond;
1.52      www      4832:               }
                   4833:           }
1.148     www      4834:         }
1.29      www      4835:        }
1.52      www      4836:    }
1.29      www      4837: 
1.52      www      4838: #
1.103     harris41 4839: # Gathered now: all privileges that could apply, and condition number
1.52      www      4840: # 
                   4841: #
                   4842: # Full or no access?
                   4843: #
1.29      www      4844: 
1.52      www      4845:     if ($thisallowed=~/F/) {
                   4846: 	return 'F';
                   4847:     }
1.29      www      4848: 
1.52      www      4849:     unless ($thisallowed) {
                   4850:         return '';
                   4851:     }
1.29      www      4852: 
1.52      www      4853: # Restrictions exist, deal with them
                   4854: #
                   4855: #   C:according to course preferences
                   4856: #   R:according to resource settings
                   4857: #   L:unless locked
                   4858: #   X:according to user session state
                   4859: #
                   4860: 
                   4861: # Possibly locked functionality, check all courses
1.54      www      4862: # Locks might take effect only after 10 minutes cache expiration for other
                   4863: # courses, and 2 minutes for current course
1.52      www      4864: 
                   4865:     my $envkey;
                   4866:     if ($thisallowed=~/L/) {
1.620     albertel 4867:         foreach $envkey (keys %env) {
1.54      www      4868:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4869:                my $courseid=$2;
                   4870:                my $roleid=$1.'.'.$2;
1.92      www      4871:                $courseid=~s/^\///;
1.54      www      4872:                my $expiretime=600;
1.620     albertel 4873:                if ($env{'request.role'} eq $roleid) {
1.54      www      4874: 		  $expiretime=120;
                   4875:                }
                   4876: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4877:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4878:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4879: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4880:                }
1.620     albertel 4881:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4882:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4883: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4884:                        &log($env{'user.domain'},$env{'user.name'},
                   4885:                             $env{'user.home'},
1.57      www      4886:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4887:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4888:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4889: 		       return '';
                   4890:                    }
                   4891:                }
1.620     albertel 4892:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4893:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4894: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4895:                        &log($env{'user.domain'},$env{'user.name'},
                   4896:                             $env{'user.home'},
1.57      www      4897:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4898:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4899:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4900: 		       return '';
                   4901:                    }
                   4902:                }
                   4903: 	   }
1.29      www      4904:        }
1.52      www      4905:     }
                   4906:    
                   4907: #
                   4908: # Rest of the restrictions depend on selected course
                   4909: #
                   4910: 
1.620     albertel 4911:     unless ($env{'request.course.id'}) {
1.766     albertel 4912: 	if ($thisallowed eq 'A') {
                   4913: 	    return 'A';
1.814     raeburn  4914:         } elsif ($thisallowed eq 'B') {
                   4915:             return 'B';
1.766     albertel 4916: 	} else {
                   4917: 	    return '1';
                   4918: 	}
1.52      www      4919:     }
1.29      www      4920: 
1.52      www      4921: #
                   4922: # Now user is definitely in a course
                   4923: #
1.53      www      4924: 
                   4925: 
                   4926: # Course preferences
                   4927: 
                   4928:    if ($thisallowed=~/C/) {
1.620     albertel 4929:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4930:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4931:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4932: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4933: 	   if ($priv ne 'pch') { 
                   4934: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4935: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4936: 			$env{'request.course.id'});
                   4937: 	   }
1.237     www      4938:            return '';
                   4939:        }
                   4940: 
1.620     albertel 4941:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4942: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4943: 	   if ($priv ne 'pch') { 
                   4944: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4945: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4946: 			$env{'request.course.id'});
                   4947: 	   }
1.54      www      4948:            return '';
                   4949:        }
1.53      www      4950:    }
                   4951: 
                   4952: # Resource preferences
                   4953: 
                   4954:    if ($thisallowed=~/R/) {
1.620     albertel 4955:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4956:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4957: 	   if ($priv ne 'pch') { 
                   4958: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4959: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4960: 	   }
                   4961: 	   return '';
1.54      www      4962:        }
1.53      www      4963:    }
1.30      www      4964: 
1.246     www      4965: # Restricted by state or randomout?
1.30      www      4966: 
1.52      www      4967:    if ($thisallowed=~/X/) {
1.620     albertel 4968:       if ($env{'acc.randomout'}) {
1.579     albertel 4969: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4970:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4971:             return ''; 
                   4972:          }
1.247     www      4973:       }
                   4974:       if (&condval($statecond)) {
1.52      www      4975: 	 return '2';
                   4976:       } else {
                   4977:          return '';
                   4978:       }
                   4979:    }
1.30      www      4980: 
1.766     albertel 4981:     if ($thisallowed eq 'A') {
                   4982: 	return 'A';
1.814     raeburn  4983:     } elsif ($thisallowed eq 'B') {
                   4984:         return 'B';
1.766     albertel 4985:     }
1.52      www      4986:    return 'F';
1.232     www      4987: }
                   4988: 
1.710     albertel 4989: sub split_uri_for_cond {
                   4990:     my $uri=&deversion(&declutter(shift));
                   4991:     my @uriparts=split(/\//,$uri);
                   4992:     my $filename=pop(@uriparts);
                   4993:     my $pathname=join('/',@uriparts);
                   4994:     return ($pathname,$filename);
                   4995: }
1.232     www      4996: # --------------------------------------------------- Is a resource on the map?
                   4997: 
                   4998: sub is_on_map {
1.710     albertel 4999:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5000:     #Trying to find the conditional for the file
1.620     albertel 5001:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5002: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5003:     if ($match) {
1.289     bowersj2 5004: 	return (1,$1);
                   5005:     } else {
1.434     www      5006: 	return (0,0);
1.289     bowersj2 5007:     }
1.12      www      5008: }
                   5009: 
1.427     www      5010: # --------------------------------------------------------- Get symb from alias
                   5011: 
                   5012: sub get_symb_from_alias {
                   5013:     my $symb=shift;
                   5014:     my ($map,$resid,$url)=&decode_symb($symb);
                   5015: # Already is a symb
                   5016:     if ($url) { return $symb; }
                   5017: # Must be an alias
                   5018:     my $aliassymb='';
                   5019:     my %bighash;
1.620     albertel 5020:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5021:                             &GDBM_READER(),0640)) {
                   5022:         my $rid=$bighash{'mapalias_'.$symb};
                   5023: 	if ($rid) {
                   5024: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5025: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5026: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5027: 	}
                   5028:         untie %bighash;
                   5029:     }
                   5030:     return $aliassymb;
                   5031: }
                   5032: 
1.12      www      5033: # ----------------------------------------------------------------- Define Role
                   5034: 
                   5035: sub definerole {
                   5036:   if (allowed('mcr','/')) {
                   5037:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5038:     foreach my $role (split(':',$sysrole)) {
                   5039: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5040:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5041:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5042: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5043:                return "refused:s:$crole&$cqual"; 
                   5044:             }
                   5045:         }
1.191     harris41 5046:     }
1.800     albertel 5047:     foreach my $role (split(':',$domrole)) {
                   5048: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5049:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5050:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5051: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5052:                return "refused:d:$crole&$cqual"; 
                   5053:             }
                   5054:         }
1.191     harris41 5055:     }
1.800     albertel 5056:     foreach my $role (split(':',$courole)) {
                   5057: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5058:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5059:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5060: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5061:                return "refused:c:$crole&$cqual"; 
                   5062:             }
                   5063:         }
1.191     harris41 5064:     }
1.620     albertel 5065:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5066:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5067: 	        "rolesdef_$rolename=".
                   5068:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5069:     return reply($command,$env{'user.home'});
1.12      www      5070:   } else {
                   5071:     return 'refused';
                   5072:   }
1.105     harris41 5073: }
                   5074: 
                   5075: # ---------------- Make a metadata query against the network of library servers
                   5076: 
                   5077: sub metadata_query {
1.244     matthew  5078:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5079:     my %rhash;
1.845     albertel 5080:     my %libserv = &all_library();
1.244     matthew  5081:     my @server_list = (defined($server_array) ? @$server_array
                   5082:                                               : keys(%libserv) );
                   5083:     for my $server (@server_list) {
1.118     harris41 5084: 	unless ($custom or $customshow) {
                   5085: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5086: 	    $rhash{$server}=$reply;
                   5087: 	}
                   5088: 	else {
                   5089: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5090: 			     &escape($custom).':'.&escape($customshow),
                   5091: 			     $server);
                   5092: 	    $rhash{$server}=$reply;
                   5093: 	}
1.112     harris41 5094:     }
1.118     harris41 5095:     return \%rhash;
1.240     www      5096: }
                   5097: 
                   5098: # ----------------------------------------- Send log queries and wait for reply
                   5099: 
                   5100: sub log_query {
                   5101:     my ($uname,$udom,$query,%filters)=@_;
                   5102:     my $uhome=&homeserver($uname,$udom);
                   5103:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5104:     my $uhost=&hostname($uhome);
1.800     albertel 5105:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5106:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5107:                        $uhome);
1.479     albertel 5108:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5109:     return get_query_reply($queryid);
                   5110: }
                   5111: 
1.818     raeburn  5112: # -------------------------- Update MySQL table for portfolio file
                   5113: 
                   5114: sub update_portfolio_table {
1.821     raeburn  5115:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5116:     if ($group ne '') {
                   5117:         $file_name =~s /^\Q$group\E//;
                   5118:     }
1.818     raeburn  5119:     my $homeserver = &homeserver($uname,$udom);
                   5120:     my $queryid=
1.821     raeburn  5121:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5122:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5123:     my $reply = &get_query_reply($queryid);
                   5124:     return $reply;
                   5125: }
                   5126: 
1.899     raeburn  5127: # -------------------------- Update MySQL allusers table
                   5128: 
                   5129: sub update_allusers_table {
                   5130:     my ($uname,$udom,$names) = @_;
                   5131:     my $homeserver = &homeserver($uname,$udom);
                   5132:     my $queryid=
                   5133:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5134:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5135:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5136:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5137:                'generation='.&escape($names->{'generation'}).'%%'.
                   5138:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5139:                'id='.&escape($names->{'id'}),$homeserver);
                   5140:     my $reply = &get_query_reply($queryid);
                   5141:     return $reply;
                   5142: }
                   5143: 
1.508     raeburn  5144: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5145: 
                   5146: sub fetch_enrollment_query {
1.511     raeburn  5147:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5148:     my $homeserver;
1.547     raeburn  5149:     my $maxtries = 1;
1.508     raeburn  5150:     if ($context eq 'automated') {
                   5151:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5152:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5153:     } else {
                   5154:         $homeserver = &homeserver($cnum,$dom);
                   5155:     }
1.838     albertel 5156:     my $host=&hostname($homeserver);
1.506     raeburn  5157:     my $cmd = '';
1.800     albertel 5158:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5159:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5160:     }
                   5161:     $cmd =~ s/%%$//;
                   5162:     $cmd = &escape($cmd);
                   5163:     my $query = 'fetchenrollment';
1.620     albertel 5164:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5165:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5166:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5167:         return 'error: '.$queryid;
                   5168:     }
1.506     raeburn  5169:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5170:     my $tries = 1;
                   5171:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5172:         $reply = &get_query_reply($queryid);
                   5173:         $tries ++;
                   5174:     }
1.526     raeburn  5175:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5176:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5177:     } else {
1.901     albertel 5178:         my @responses = split(/:/,$reply);
1.515     raeburn  5179:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5180:             foreach my $line (@responses) {
                   5181:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5182:                 $$replyref{$key} = $value;
                   5183:             }
                   5184:         } else {
1.506     raeburn  5185:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5186:             foreach my $line (@responses) {
                   5187:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5188:                 $$replyref{$key} = $value;
                   5189:                 if ($value > 0) {
1.800     albertel 5190:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5191:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5192:                         my $destname = $pathname.'/'.$filename;
                   5193:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5194:                         if ($xml_classlist =~ /^error/) {
                   5195:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5196:                         } else {
1.506     raeburn  5197:                             if ( open(FILE,">$destname") ) {
                   5198:                                 print FILE &unescape($xml_classlist);
                   5199:                                 close(FILE);
1.526     raeburn  5200:                             } else {
                   5201:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5202:                             }
                   5203:                         }
                   5204:                     }
                   5205:                 }
                   5206:             }
                   5207:         }
                   5208:         return 'ok';
                   5209:     }
                   5210:     return 'error';
                   5211: }
                   5212: 
1.242     www      5213: sub get_query_reply {
                   5214:     my $queryid=shift;
1.240     www      5215:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5216:     my $reply='';
                   5217:     for (1..100) {
                   5218: 	sleep 2;
                   5219:         if (-e $replyfile.'.end') {
1.448     albertel 5220: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5221: 		$reply = join('',<$fh>);
                   5222: 		close($fh);
1.240     www      5223: 	   } else { return 'error: reply_file_error'; }
1.242     www      5224:            return &unescape($reply);
                   5225: 	}
1.240     www      5226:     }
1.242     www      5227:     return 'timeout:'.$queryid;
1.240     www      5228: }
                   5229: 
                   5230: sub courselog_query {
1.241     www      5231: #
                   5232: # possible filters:
                   5233: # url: url or symb
                   5234: # username
                   5235: # domain
                   5236: # action: view, submit, grade
                   5237: # start: timestamp
                   5238: # end: timestamp
                   5239: #
1.240     www      5240:     my (%filters)=@_;
1.620     albertel 5241:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5242:     if ($filters{'url'}) {
                   5243: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5244:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5245:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5246:     }
1.620     albertel 5247:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5248:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5249:     return &log_query($cname,$cdom,'courselog',%filters);
                   5250: }
                   5251: 
                   5252: sub userlog_query {
1.858     raeburn  5253: #
                   5254: # possible filters:
                   5255: # action: log check role
                   5256: # start: timestamp
                   5257: # end: timestamp
                   5258: #
1.240     www      5259:     my ($uname,$udom,%filters)=@_;
                   5260:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5261: }
                   5262: 
1.506     raeburn  5263: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5264: 
                   5265: sub auto_run {
1.508     raeburn  5266:     my ($cnum,$cdom) = @_;
1.876     raeburn  5267:     my $response = 0;
                   5268:     my $settings;
                   5269:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5270:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5271:         $settings = $domconfig{'autoenroll'};
                   5272:         if ($settings->{'run'} eq '1') {
                   5273:             $response = 1;
                   5274:         }
                   5275:     } else {
1.934     raeburn  5276:         my $homeserver;
                   5277:         if (&is_course($cdom,$cnum)) {
                   5278:             $homeserver = &homeserver($cnum,$cdom);
                   5279:         } else {
                   5280:             $homeserver = &domain($cdom,'primary');
                   5281:         }
                   5282:         if ($homeserver ne 'no_host') {
                   5283:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5284:         }
1.876     raeburn  5285:     }
1.506     raeburn  5286:     return $response;
                   5287: }
1.776     albertel 5288: 
1.506     raeburn  5289: sub auto_get_sections {
1.508     raeburn  5290:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5291:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5292:     my @secs = ();
1.511     raeburn  5293:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5294:     unless ($response eq 'refused') {
1.901     albertel 5295:         @secs = split(/:/,$response);
1.506     raeburn  5296:     }
                   5297:     return @secs;
                   5298: }
1.776     albertel 5299: 
1.506     raeburn  5300: sub auto_new_course {
1.508     raeburn  5301:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5302:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5303:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5304:     return $response;
                   5305: }
1.776     albertel 5306: 
1.506     raeburn  5307: sub auto_validate_courseID {
1.508     raeburn  5308:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5309:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5310:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5311:     return $response;
                   5312: }
1.776     albertel 5313: 
1.506     raeburn  5314: sub auto_create_password {
1.873     raeburn  5315:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5316:     my ($homeserver,$response);
1.506     raeburn  5317:     my $create_passwd = 0;
                   5318:     my $authchk = '';
1.873     raeburn  5319:     if ($udom =~ /^$match_domain$/) {
                   5320:         $homeserver = &domain($udom,'primary');
                   5321:     }
                   5322:     if ($homeserver eq '') {
                   5323:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5324:             $homeserver = &homeserver($cnum,$cdom);
                   5325:         }
                   5326:     }
                   5327:     if ($homeserver eq '') {
                   5328:         $authchk = 'nodomain';
1.506     raeburn  5329:     } else {
1.873     raeburn  5330:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5331:         if ($response eq 'refused') {
                   5332:             $authchk = 'refused';
                   5333:         } else {
1.901     albertel 5334:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5335:         }
1.506     raeburn  5336:     }
                   5337:     return ($authparam,$create_passwd,$authchk);
                   5338: }
                   5339: 
1.706     raeburn  5340: sub auto_photo_permission {
                   5341:     my ($cnum,$cdom,$students) = @_;
                   5342:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5343:     my ($outcome,$perm_reqd,$conditions) = 
                   5344: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5345:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5346: 	return (undef,undef);
                   5347:     }
1.706     raeburn  5348:     return ($outcome,$perm_reqd,$conditions);
                   5349: }
                   5350: 
                   5351: sub auto_checkphotos {
                   5352:     my ($uname,$udom,$pid) = @_;
                   5353:     my $homeserver = &homeserver($uname,$udom);
                   5354:     my ($result,$resulttype);
                   5355:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5356: 				   &escape($uname).':'.&escape($pid),
                   5357: 				   $homeserver));
1.709     albertel 5358:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5359: 	return (undef,undef);
                   5360:     }
1.706     raeburn  5361:     if ($outcome) {
                   5362:         ($result,$resulttype) = split(/:/,$outcome);
                   5363:     } 
                   5364:     return ($result,$resulttype);
                   5365: }
                   5366: 
                   5367: sub auto_photochoice {
                   5368:     my ($cnum,$cdom) = @_;
                   5369:     my $homeserver = &homeserver($cnum,$cdom);
                   5370:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5371: 						       &escape($cdom),
                   5372: 						       $homeserver)));
1.709     albertel 5373:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5374: 	return (undef,undef);
                   5375:     }
1.706     raeburn  5376:     return ($update,$comment);
                   5377: }
                   5378: 
                   5379: sub auto_photoupdate {
                   5380:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5381:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5382:     my $host=&hostname($homeserver);
1.706     raeburn  5383:     my $cmd = '';
                   5384:     my $maxtries = 1;
1.800     albertel 5385:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5386:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5387:     }
                   5388:     $cmd =~ s/%%$//;
                   5389:     $cmd = &escape($cmd);
                   5390:     my $query = 'institutionalphotos';
                   5391:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5392:     unless ($queryid=~/^\Q$host\E\_/) {
                   5393:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5394:         return 'error: '.$queryid;
                   5395:     }
                   5396:     my $reply = &get_query_reply($queryid);
                   5397:     my $tries = 1;
                   5398:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5399:         $reply = &get_query_reply($queryid);
                   5400:         $tries ++;
                   5401:     }
                   5402:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5403:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5404:     } else {
                   5405:         my @responses = split(/:/,$reply);
                   5406:         my $outcome = shift(@responses); 
                   5407:         foreach my $item (@responses) {
                   5408:             my ($key,$value) = split(/=/,$item);
                   5409:             $$photo{$key} = $value;
                   5410:         }
                   5411:         return $outcome;
                   5412:     }
                   5413:     return 'error';
                   5414: }
                   5415: 
1.521     raeburn  5416: sub auto_instcode_format {
1.793     albertel 5417:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5418: 	$cat_order) = @_;
1.521     raeburn  5419:     my $courses = '';
1.772     raeburn  5420:     my @homeservers;
1.521     raeburn  5421:     if ($caller eq 'global') {
1.841     albertel 5422: 	my %servers = &get_servers($codedom,'library');
                   5423: 	foreach my $tryserver (keys(%servers)) {
                   5424: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5425: 		push(@homeservers,$tryserver);
                   5426: 	    }
1.584     raeburn  5427:         }
1.521     raeburn  5428:     } else {
1.772     raeburn  5429:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5430:     }
1.793     albertel 5431:     foreach my $code (keys(%{$instcodes})) {
                   5432:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5433:     }
                   5434:     chop($courses);
1.772     raeburn  5435:     my $ok_response = 0;
                   5436:     my $response;
                   5437:     while (@homeservers > 0 && $ok_response == 0) {
                   5438:         my $server = shift(@homeservers); 
                   5439:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5440:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5441:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5442: 		split(/:/,$response);
1.772     raeburn  5443:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5444:             push(@{$codetitles},&str2array($codetitles_str));
                   5445:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5446:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5447:             $ok_response = 1;
                   5448:         }
                   5449:     }
                   5450:     if ($ok_response) {
1.521     raeburn  5451:         return 'ok';
1.772     raeburn  5452:     } else {
                   5453:         return $response;
1.521     raeburn  5454:     }
                   5455: }
                   5456: 
1.792     raeburn  5457: sub auto_instcode_defaults {
                   5458:     my ($domain,$returnhash,$code_order) = @_;
                   5459:     my @homeservers;
1.841     albertel 5460: 
                   5461:     my %servers = &get_servers($domain,'library');
                   5462:     foreach my $tryserver (keys(%servers)) {
                   5463: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5464: 	    push(@homeservers,$tryserver);
                   5465: 	}
1.792     raeburn  5466:     }
1.841     albertel 5467: 
1.792     raeburn  5468:     my $response;
1.841     albertel 5469:     foreach my $server (@homeservers) {
1.792     raeburn  5470:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5471:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5472: 	
                   5473: 	foreach my $pair (split(/\&/,$response)) {
                   5474: 	    my ($name,$value)=split(/\=/,$pair);
                   5475: 	    if ($name eq 'code_order') {
                   5476: 		@{$code_order} = split(/\&/,&unescape($value));
                   5477: 	    } else {
                   5478: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5479: 	    }
                   5480: 	}
                   5481: 	return 'ok';
1.792     raeburn  5482:     }
1.841     albertel 5483: 
                   5484:     return $response;
1.792     raeburn  5485: } 
                   5486: 
1.777     albertel 5487: sub auto_validate_class_sec {
1.918     raeburn  5488:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5489:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5490:     my $ownerlist;
                   5491:     if (ref($owners) eq 'ARRAY') {
                   5492:         $ownerlist = join(',',@{$owners});
                   5493:     } else {
                   5494:         $ownerlist = $owners;
                   5495:     }
1.773     raeburn  5496:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5497:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5498:     return $response;
                   5499: }
                   5500: 
1.679     raeburn  5501: # ------------------------------------------------------- Course Group routines
                   5502: 
                   5503: sub get_coursegroups {
1.809     raeburn  5504:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5505:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5506: }
                   5507: 
1.679     raeburn  5508: sub modify_coursegroup {
                   5509:     my ($cdom,$cnum,$groupsettings) = @_;
                   5510:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5511: }
                   5512: 
1.809     raeburn  5513: sub toggle_coursegroup_status {
                   5514:     my ($cdom,$cnum,$group,$action) = @_;
                   5515:     my ($from_namespace,$to_namespace);
                   5516:     if ($action eq 'delete') {
                   5517:         $from_namespace = 'coursegroups';
                   5518:         $to_namespace = 'deleted_groups';
                   5519:     } else {
                   5520:         $from_namespace = 'deleted_groups';
                   5521:         $to_namespace = 'coursegroups';
                   5522:     }
                   5523:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5524:     if (my $tmp = &error(%curr_group)) {
                   5525:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5526:         return ('read error',$tmp);
                   5527:     } else {
                   5528:         my %savedsettings = %curr_group; 
1.809     raeburn  5529:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5530:         my $deloutcome;
                   5531:         if ($result eq 'ok') {
1.809     raeburn  5532:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5533:         } else {
                   5534:             return ('write error',$result);
                   5535:         }
                   5536:         if ($deloutcome eq 'ok') {
                   5537:             return 'ok';
                   5538:         } else {
                   5539:             return ('delete error',$deloutcome);
                   5540:         }
                   5541:     }
                   5542: }
                   5543: 
1.679     raeburn  5544: sub modify_group_roles {
1.957     raeburn  5545:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5546:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5547:     my $role = 'gr/'.&escape($userprivs);
                   5548:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5549:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5550:     if ($result eq 'ok') {
                   5551:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5552:     }
1.679     raeburn  5553:     return $result;
                   5554: }
                   5555: 
                   5556: sub modify_coursegroup_membership {
                   5557:     my ($cdom,$cnum,$membership) = @_;
                   5558:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5559:     return $result;
                   5560: }
                   5561: 
1.682     raeburn  5562: sub get_active_groups {
                   5563:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5564:     my $now = time;
                   5565:     my %groups = ();
                   5566:     foreach my $key (keys(%env)) {
1.811     albertel 5567:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5568:             my ($start,$end) = split(/\./,$env{$key});
                   5569:             if (($end!=0) && ($end<$now)) { next; }
                   5570:             if (($start!=0) && ($start>$now)) { next; }
                   5571:             if ($1 eq $cdom && $2 eq $cnum) {
                   5572:                 $groups{$3} = $env{$key} ;
                   5573:             }
                   5574:         }
                   5575:     }
                   5576:     return %groups;
                   5577: }
                   5578: 
1.683     raeburn  5579: sub get_group_membership {
                   5580:     my ($cdom,$cnum,$group) = @_;
                   5581:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5582: }
                   5583: 
                   5584: sub get_users_groups {
                   5585:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5586:     my @usersgroups;
1.683     raeburn  5587:     my $cachetime=1800;
                   5588: 
                   5589:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5590:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5591:     if (defined($cached)) {
1.734     albertel 5592:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5593:     } else {  
                   5594:         $grouplist = '';
1.816     raeburn  5595:         my $courseurl = &courseid_to_courseurl($courseid);
                   5596:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5597:         my $access_end = $env{'course.'.$courseid.
                   5598:                               '.default_enrollment_end_date'};
                   5599:         my $now = time;
                   5600:         foreach my $key (keys(%roleshash)) {
                   5601:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5602:                 my $group = $1;
                   5603:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5604:                     my $start = $2;
                   5605:                     my $end = $1;
                   5606:                     if ($start == -1) { next; } # deleted from group
                   5607:                     if (($start!=0) && ($start>$now)) { next; }
                   5608:                     if (($end!=0) && ($end<$now)) {
                   5609:                         if ($access_end && $access_end < $now) {
                   5610:                             if ($access_end - $end < 86400) {
                   5611:                                 push(@usersgroups,$group);
1.733     raeburn  5612:                             }
                   5613:                         }
1.817     raeburn  5614:                         next;
1.733     raeburn  5615:                     }
1.817     raeburn  5616:                     push(@usersgroups,$group);
1.683     raeburn  5617:                 }
                   5618:             }
                   5619:         }
1.817     raeburn  5620:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5621:         $grouplist = join(':',@usersgroups);
                   5622:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5623:     }
1.733     raeburn  5624:     return @usersgroups;
1.683     raeburn  5625: }
                   5626: 
                   5627: sub devalidate_getgroups_cache {
                   5628:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5629:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5630: 
1.683     raeburn  5631:     my $hashid="$udom:$uname:$courseid";
                   5632:     &devalidate_cache_new('getgroups',$hashid);
                   5633: }
                   5634: 
1.12      www      5635: # ------------------------------------------------------------------ Plain Text
                   5636: 
                   5637: sub plaintext {
1.742     raeburn  5638:     my ($short,$type,$cid) = @_;
1.758     albertel 5639:     if ($short =~ /^cr/) {
                   5640: 	return (split('/',$short))[-1];
                   5641:     }
1.742     raeburn  5642:     if (!defined($cid)) {
                   5643:         $cid = $env{'request.course.id'};
                   5644:     }
                   5645:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5646:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5647:                                           '.plaintext'});
                   5648:     }
                   5649:     my %rolenames = (
                   5650:                       Course => 'std',
                   5651:                       Group => 'alt1',
                   5652:                     );
                   5653:     if (defined($type) && 
                   5654:          defined($rolenames{$type}) && 
                   5655:          defined($prp{$short}{$rolenames{$type}})) {
                   5656:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5657:     } else {
                   5658:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5659:     }
1.12      www      5660: }
                   5661: 
                   5662: # ----------------------------------------------------------------- Assign Role
                   5663: 
                   5664: sub assignrole {
1.957     raeburn  5665:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5666:         $context)=@_;
1.21      www      5667:     my $mrole;
                   5668:     if ($role =~ /^cr\//) {
1.393     www      5669:         my $cwosec=$url;
1.811     albertel 5670:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5671: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5672:            &logthis('Refused custom assignrole: '.
                   5673:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5674: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5675:            return 'refused'; 
                   5676:         }
1.21      www      5677:         $mrole='cr';
1.678     raeburn  5678:     } elsif ($role =~ /^gr\//) {
                   5679:         my $cwogrp=$url;
1.811     albertel 5680:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5681:         unless (&allowed('mdg',$cwogrp)) {
                   5682:             &logthis('Refused group assignrole: '.
                   5683:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5684:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5685:             return 'refused';
                   5686:         }
                   5687:         $mrole='gr';
1.21      www      5688:     } else {
1.82      www      5689:         my $cwosec=$url;
1.811     albertel 5690:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5691:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5692:             my $refused;
                   5693:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5694:                 if (!(&allowed('c'.$role,$url))) {
                   5695:                     $refused = 1;
                   5696:                 }
                   5697:             } else {
                   5698:                 $refused = 1;
                   5699:             }
1.947     raeburn  5700:             if ($refused) {
                   5701:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5702:                     $refused = '';
                   5703:                 } else {
                   5704:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5705:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5706: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5707:                     return 'refused';
                   5708:                 }
1.932     raeburn  5709:             }
1.104     www      5710:         }
1.21      www      5711:         $mrole=$role;
                   5712:     }
1.620     albertel 5713:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5714:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5715:     if ($end) { $command.='_'.$end; }
1.21      www      5716:     if ($start) {
                   5717: 	if ($end) { 
1.81      www      5718:            $command.='_'.$start; 
1.21      www      5719:         } else {
1.81      www      5720:            $command.='_0_'.$start;
1.21      www      5721:         }
                   5722:     }
1.739     raeburn  5723:     my $origstart = $start;
                   5724:     my $origend = $end;
1.957     raeburn  5725:     my $delflag;
1.357     www      5726: # actually delete
                   5727:     if ($deleteflag) {
1.373     www      5728: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5729: # modify command to delete the role
1.620     albertel 5730:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5731:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5732: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5733: # set start and finish to negative values for userrolelog
                   5734:            $start=-1;
                   5735:            $end=-1;
1.957     raeburn  5736:            $delflag = 1;
1.357     www      5737:         }
                   5738:     }
                   5739: # send command
1.349     www      5740:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5741: # log new user role if status is ok
1.349     www      5742:     if ($answer eq 'ok') {
1.663     raeburn  5743: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5744: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5745:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5746:         unless ($role =~ /^gr/) {
                   5747:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5748:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5749:         }
1.349     www      5750:     }
                   5751:     return $answer;
1.169     harris41 5752: }
                   5753: 
                   5754: # -------------------------------------------------- Modify user authentication
1.197     www      5755: # Overrides without validation
                   5756: 
1.169     harris41 5757: sub modifyuserauth {
                   5758:     my ($udom,$uname,$umode,$upass)=@_;
                   5759:     my $uhome=&homeserver($uname,$udom);
1.197     www      5760:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5761:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5762:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5763:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5764:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5765: 		     &escape($upass),$uhome);
1.620     albertel 5766:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5767:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5768:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5769:     &log($udom,,$uname,$uhome,
1.620     albertel 5770:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5771:                                      $env{'user.name'}.', '.$umode.
1.197     www      5772:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5773:     unless ($reply eq 'ok') {
1.197     www      5774:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5775: 	return 'error: '.$reply;
                   5776:     }   
1.170     harris41 5777:     return 'ok';
1.80      www      5778: }
                   5779: 
1.81      www      5780: # --------------------------------------------------------------- Modify a user
1.80      www      5781: 
1.81      www      5782: sub modifyuser {
1.206     matthew  5783:     my ($udom,    $uname, $uid,
                   5784:         $umode,   $upass, $first,
                   5785:         $middle,  $last,  $gene,
1.963     raeburn  5786:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5787:     $udom= &LONCAPA::clean_domain($udom);
                   5788:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5789:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5790:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5791: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5792:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5793:                                      ' desiredhome not specified'). 
1.620     albertel 5794:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5795:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5796:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5797: # ----------------------------------------------------------------- Create User
1.406     albertel 5798:     if (($uhome eq 'no_host') && 
                   5799: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5800:         my $unhome='';
1.844     albertel 5801:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5802:             $unhome = $desiredhome;
1.620     albertel 5803: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5804: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5805:         } else { # load balancing routine for determining $unhome
1.81      www      5806:             my $loadm=10000000;
1.841     albertel 5807: 	    my %servers = &get_servers($udom,'library');
                   5808: 	    foreach my $tryserver (keys(%servers)) {
                   5809: 		my $answer=reply('load',$tryserver);
                   5810: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5811: 		    $loadm=$answer;
                   5812: 		    $unhome=$tryserver;
                   5813: 		}
1.80      www      5814: 	    }
                   5815:         }
                   5816:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5817: 	    return 'error: unable to find a home server for '.$uname.
                   5818:                    ' in domain '.$udom;
1.80      www      5819:         }
                   5820:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5821:                          &escape($upass),$unhome);
                   5822: 	unless ($reply eq 'ok') {
                   5823:             return 'error: '.$reply;
                   5824:         }   
1.230     stredwic 5825:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5826:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5827: 	    return 'error: unable verify users home machine.';
1.80      www      5828:         }
1.209     matthew  5829:     }   # End of creation of new user
1.80      www      5830: # ---------------------------------------------------------------------- Add ID
                   5831:     if ($uid) {
                   5832:        $uid=~tr/A-Z/a-z/;
                   5833:        my %uidhash=&idrget($udom,$uname);
1.196     www      5834:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5835:          && (!$forceid)) {
1.80      www      5836: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5837: 	      return 'error: user id "'.$uid.'" does not match '.
                   5838:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5839:           }
                   5840:        } else {
                   5841: 	  &idput($udom,($uname => $uid));
                   5842:        }
                   5843:     }
                   5844: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5845:     my @tmp=&get('environment',
1.899     raeburn  5846: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5847:                     'permanentemail','inststatus'],
1.134     albertel 5848: 		   $udom,$uname);
1.313     matthew  5849:     my %names;
                   5850:     if ($tmp[0] =~ m/^error:.*/) { 
                   5851:         %names=(); 
                   5852:     } else {
                   5853:         %names = @tmp;
                   5854:     }
1.388     www      5855: #
                   5856: # Make sure to not trash student environment if instructor does not bother
                   5857: # to supply name and email information
                   5858: #
                   5859:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5860:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5861:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5862:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5863:     if ($email) {
                   5864:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5865:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5866:     }
1.899     raeburn  5867:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5868:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5869:     my $reply = &put('environment', \%names, $udom,$uname);
                   5870:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5871:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5872:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5873:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5874:                  $umode.', '.$first.', '.$middle.', '.
                   5875: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5876:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5877:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5878:     } else {
                   5879:         $logmsg .= ' during self creation';
                   5880:     }
                   5881:     &logthis($logmsg);
1.134     albertel 5882:     return 'ok';
1.80      www      5883: }
                   5884: 
1.81      www      5885: # -------------------------------------------------------------- Modify student
1.80      www      5886: 
1.81      www      5887: sub modifystudent {
                   5888:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5889:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5890:         $selfenroll,$context)=@_;
1.455     albertel 5891:     if (!$cid) {
1.620     albertel 5892: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5893: 	    return 'not_in_class';
                   5894: 	}
1.80      www      5895:     }
                   5896: # --------------------------------------------------------------- Make the user
1.81      www      5897:     my $reply=&modifyuser
1.209     matthew  5898: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5899:          $desiredhome,$email);
1.80      www      5900:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5901:     # This will cause &modify_student_enrollment to get the uid from the
                   5902:     # students environment
                   5903:     $uid = undef if (!$forceid);
1.455     albertel 5904:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5905: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5906:     return $reply;
                   5907: }
                   5908: 
                   5909: sub modify_student_enrollment {
1.957     raeburn  5910:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5911:     my ($cdom,$cnum,$chome);
                   5912:     if (!$cid) {
1.620     albertel 5913: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5914: 	    return 'not_in_class';
                   5915: 	}
1.620     albertel 5916: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5917: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5918:     } else {
                   5919: 	($cdom,$cnum)=split(/_/,$cid);
                   5920:     }
1.620     albertel 5921:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5922:     if (!$chome) {
1.457     raeburn  5923: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5924:     }
1.455     albertel 5925:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5926:     # Make sure the user exists
1.81      www      5927:     my $uhome=&homeserver($uname,$udom);
                   5928:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5929: 	return 'error: no such user';
                   5930:     }
1.297     matthew  5931:     # Get student data if we were not given enough information
                   5932:     if (!defined($first)  || $first  eq '' || 
                   5933:         !defined($last)   || $last   eq '' || 
                   5934:         !defined($uid)    || $uid    eq '' || 
                   5935:         !defined($middle) || $middle eq '' || 
                   5936:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5937:         # They did not supply us with enough data to enroll the student, so
                   5938:         # we need to pick up more information.
1.297     matthew  5939:         my %tmp = &get('environment',
1.294     matthew  5940:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5941:                        ,$udom,$uname);
                   5942: 
1.800     albertel 5943:         #foreach my $key (keys(%tmp)) {
                   5944:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5945:         #}
1.294     matthew  5946:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5947:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5948:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5949:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5950:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5951:     }
1.556     albertel 5952:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5953:     my $reply=cput('classlist',
                   5954: 		   {"$uname:$udom" => 
1.515     raeburn  5955: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5956: 		   $cdom,$cnum);
1.81      www      5957:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5958: 	return 'error: '.$reply;
1.652     albertel 5959:     } else {
                   5960: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5961:     }
1.297     matthew  5962:     # Add student role to user
1.83      www      5963:     my $uurl='/'.$cid;
1.81      www      5964:     $uurl=~s/\_/\//g;
                   5965:     if ($usec) {
                   5966: 	$uurl.='/'.$usec;
                   5967:     }
1.957     raeburn  5968:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5969: }
                   5970: 
1.556     albertel 5971: sub format_name {
                   5972:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5973:     my $name;
                   5974:     if ($first ne 'lastname') {
                   5975: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5976:     } else {
                   5977: 	if ($lastname=~/\S/) {
                   5978: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5979: 	    $name=~s/\s+,/,/;
                   5980: 	} else {
                   5981: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5982: 	}
                   5983:     }
                   5984:     $name=~s/^\s+//;
                   5985:     $name=~s/\s+$//;
                   5986:     $name=~s/\s+/ /g;
                   5987:     return $name;
                   5988: }
                   5989: 
1.84      www      5990: # ------------------------------------------------- Write to course preferences
                   5991: 
                   5992: sub writecoursepref {
                   5993:     my ($courseid,%prefs)=@_;
                   5994:     $courseid=~s/^\///;
                   5995:     $courseid=~s/\_/\//g;
                   5996:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5997:     my $chome=homeserver($cnum,$cdomain);
                   5998:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5999: 	return 'error: no such course';
                   6000:     }
                   6001:     my $cstring='';
1.800     albertel 6002:     foreach my $pref (keys(%prefs)) {
                   6003: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6004:     }
1.84      www      6005:     $cstring=~s/\&$//;
                   6006:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6007: }
                   6008: 
                   6009: # ---------------------------------------------------------- Make/modify course
                   6010: 
                   6011: sub createcourse {
1.741     raeburn  6012:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6013:         $course_owner,$crstype)=@_;
1.84      www      6014:     $url=&declutter($url);
                   6015:     my $cid='';
1.264     matthew  6016:     unless (&allowed('ccc',$udom)) {
1.84      www      6017:         return 'refused';
                   6018:     }
                   6019: # ------------------------------------------------------------------- Create ID
1.674     www      6020:    my $uname=int(1+rand(9)).
                   6021:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6022:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6023:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6024: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6025:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6026:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6027:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6028:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6029:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6030:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6031:            return 'error: unable to generate unique course-ID';
                   6032:        } 
                   6033:    }
1.264     matthew  6034: # ------------------------------------------------ Check supplied server name
1.620     albertel 6035:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6036:     if (! &is_library($course_server)) {
1.264     matthew  6037:         return 'error:bad server name '.$course_server;
                   6038:     }
1.84      www      6039: # ------------------------------------------------------------- Make the course
                   6040:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6041:                       $course_server);
1.84      www      6042:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6043:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6044:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6045: 	return 'error: no such course';
                   6046:     }
1.271     www      6047: # ----------------------------------------------------------------- Course made
1.516     raeburn  6048: # log existence
1.918     raeburn  6049:     my $newcourse = {
                   6050:                     $udom.'_'.$uname => {
1.921     raeburn  6051:                                      description => $description,
                   6052:                                      inst_code   => $inst_code,
                   6053:                                      owner       => $course_owner,
                   6054:                                      type        => $crstype,
1.918     raeburn  6055:                                                 },
                   6056:                     };
1.921     raeburn  6057:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6058: # set toplevel url
1.271     www      6059:     my $topurl=$url;
                   6060:     unless ($nonstandard) {
                   6061: # ------------------------------------------ For standard courses, make top url
                   6062:         my $mapurl=&clutter($url);
1.278     www      6063:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6064:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6065: <map>
                   6066: <resource id="1" type="start"></resource>
                   6067: <resource id="2" src="$mapurl"></resource>
                   6068: <resource id="3" type="finish"></resource>
                   6069: <link index="1" from="1" to="2"></link>
                   6070: <link index="2" from="2" to="3"></link>
                   6071: </map>
                   6072: ENDINITMAP
                   6073:         $topurl=&declutter(
1.638     albertel 6074:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6075:                           );
                   6076:     }
                   6077: # ----------------------------------------------------------- Write preferences
1.84      www      6078:     &writecoursepref($udom.'_'.$uname,
                   6079:                      ('description' => $description,
1.271     www      6080:                       'url'         => $topurl));
1.84      www      6081:     return '/'.$udom.'/'.$uname;
                   6082: }
                   6083: 
1.813     albertel 6084: sub is_course {
                   6085:     my ($cdom,$cnum) = @_;
                   6086:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6087: 				undef,'.');
1.813     albertel 6088:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6089:         return 1;
                   6090:     }
                   6091:     return 0;
                   6092: }
                   6093: 
1.21      www      6094: # ---------------------------------------------------------- Assign Custom Role
                   6095: 
                   6096: sub assigncustomrole {
1.957     raeburn  6097:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6098:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6099:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6100: }
                   6101: 
                   6102: # ----------------------------------------------------------------- Revoke Role
                   6103: 
                   6104: sub revokerole {
1.957     raeburn  6105:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6106:     my $now=time;
1.965     raeburn  6107:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6108: }
                   6109: 
                   6110: # ---------------------------------------------------------- Revoke Custom Role
                   6111: 
                   6112: sub revokecustomrole {
1.957     raeburn  6113:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6114:     my $now=time;
1.357     www      6115:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6116:            $deleteflag,$selfenroll,$context);
1.17      www      6117: }
                   6118: 
1.533     banghart 6119: # ------------------------------------------------------------ Disk usage
1.535     albertel 6120: sub diskusage {
1.955     raeburn  6121:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6122:     $directorypath =~ s/\/$//;
                   6123:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6124:                        .&escape($getpropath).':'.&escape($uname).':'
                   6125:                        .&escape($udom),homeserver($uname,$udom));
                   6126:     if ($listing eq 'unknown_cmd') {
                   6127:         if ($getpropath) {
                   6128:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6129:         }
                   6130:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6131:     }
1.514     albertel 6132:     return $listing;
1.512     banghart 6133: }
                   6134: 
1.566     banghart 6135: sub is_locked {
                   6136:     my ($file_name, $domain, $user) = @_;
                   6137:     my @check;
                   6138:     my $is_locked;
                   6139:     push @check, $file_name;
1.613     albertel 6140:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6141: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6142:     my ($tmp)=keys(%locked);
                   6143:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6144:     
1.566     banghart 6145:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6146:         $is_locked = 'false';
                   6147:         foreach my $entry (@{$locked{$file_name}}) {
                   6148:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6149:                $is_locked = 'true';
                   6150:                last;
1.745     raeburn  6151:            }
                   6152:        }
1.566     banghart 6153:     } else {
                   6154:         $is_locked = 'false';
                   6155:     }
                   6156: }
                   6157: 
1.759     albertel 6158: sub declutter_portfile {
                   6159:     my ($file) = @_;
1.833     albertel 6160:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6161:     return $file;
                   6162: }
                   6163: 
1.559     banghart 6164: # ------------------------------------------------------------- Mark as Read Only
                   6165: 
                   6166: sub mark_as_readonly {
                   6167:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6168:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6169:     my ($tmp)=keys(%current_permissions);
                   6170:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6171:     foreach my $file (@{$files}) {
1.759     albertel 6172: 	$file = &declutter_portfile($file);
1.561     banghart 6173:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6174:     }
1.613     albertel 6175:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6176:     return;
                   6177: }
                   6178: 
1.572     banghart 6179: # ------------------------------------------------------------Save Selected Files
                   6180: 
                   6181: sub save_selected_files {
                   6182:     my ($user, $path, @files) = @_;
                   6183:     my $filename = $user."savedfiles";
1.573     banghart 6184:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6185:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6186:     foreach my $file (@files) {
1.620     albertel 6187:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6188:     }
                   6189:     foreach my $file (@other_files) {
1.574     banghart 6190:         print (OUT $file."\n");
1.572     banghart 6191:     }
1.574     banghart 6192:     close (OUT);
1.572     banghart 6193:     return 'ok';
                   6194: }
                   6195: 
1.574     banghart 6196: sub clear_selected_files {
                   6197:     my ($user) = @_;
                   6198:     my $filename = $user."savedfiles";
                   6199:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6200:     print (OUT undef);
                   6201:     close (OUT);
                   6202:     return ("ok");    
                   6203: }
                   6204: 
1.572     banghart 6205: sub files_in_path {
                   6206:     my ($user, $path) = @_;
                   6207:     my $filename = $user."savedfiles";
                   6208:     my %return_files;
1.574     banghart 6209:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6210:     while (my $line_in = <IN>) {
1.574     banghart 6211:         chomp ($line_in);
                   6212:         my @paths_and_file = split (m!/!, $line_in);
                   6213:         my $file_part = pop (@paths_and_file);
                   6214:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6215:         $path_part.='/';
                   6216:         my $path_and_file = $path_part.$file_part;
                   6217:         if ($path_part eq $path) {
                   6218:             $return_files{$file_part}= 'selected';
                   6219:         }
                   6220:     }
1.574     banghart 6221:     close (IN);
                   6222:     return (\%return_files);
1.572     banghart 6223: }
                   6224: 
                   6225: # called in portfolio select mode, to show files selected NOT in current directory
                   6226: sub files_not_in_path {
                   6227:     my ($user, $path) = @_;
                   6228:     my $filename = $user."savedfiles";
                   6229:     my @return_files;
                   6230:     my $path_part;
1.800     albertel 6231:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6232:     while (my $line = <IN>) {
1.572     banghart 6233:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6234:         my @paths_and_file = split(m|/|, $line);
                   6235:         my $file_part = pop(@paths_and_file);
                   6236:         chomp($file_part);
                   6237:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6238:         $path_part .= '/';
                   6239:         my $path_and_file = $path_part.$file_part;
                   6240:         if ($path_part ne $path) {
1.800     albertel 6241:             push(@return_files, ($path_and_file));
1.572     banghart 6242:         }
                   6243:     }
1.800     albertel 6244:     close(OUT);
1.574     banghart 6245:     return (@return_files);
1.572     banghart 6246: }
                   6247: 
1.745     raeburn  6248: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6249: 
1.745     raeburn  6250: sub get_portfile_permissions {
                   6251:     my ($domain,$user) = @_;
1.613     albertel 6252:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6253:     my ($tmp)=keys(%current_permissions);
                   6254:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6255:     return \%current_permissions;
                   6256: }
                   6257: 
                   6258: #---------------------------------------------Get portfolio file access controls
                   6259: 
1.749     raeburn  6260: sub get_access_controls {
1.745     raeburn  6261:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6262:     my %access;
                   6263:     my $real_file = $file;
                   6264:     $file =~ s/\.meta$//;
1.745     raeburn  6265:     if (defined($file)) {
1.749     raeburn  6266:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6267:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6268:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6269:             }
                   6270:         }
1.745     raeburn  6271:     } else {
1.749     raeburn  6272:         foreach my $key (keys(%{$current_permissions})) {
                   6273:             if ($key =~ /\0accesscontrol$/) {
                   6274:                 if (defined($group)) {
                   6275:                     if ($key !~ m-^\Q$group\E/-) {
                   6276:                         next;
                   6277:                     }
                   6278:                 }
                   6279:                 my ($fullpath) = split(/\0/,$key);
                   6280:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6281:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6282:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6283:                     }
                   6284:                 }
                   6285:             }
                   6286:         }
                   6287:     }
                   6288:     return %access;
                   6289: }
                   6290: 
                   6291: sub modify_access_controls {
                   6292:     my ($file_name,$changes,$domain,$user)=@_;
                   6293:     my ($outcome,$deloutcome);
                   6294:     my %store_permissions;
                   6295:     my %new_values;
                   6296:     my %new_control;
                   6297:     my %translation;
                   6298:     my @deletions = ();
                   6299:     my $now = time;
                   6300:     if (exists($$changes{'activate'})) {
                   6301:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6302:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6303:             my $numnew = scalar(@newitems);
                   6304:             for (my $i=0; $i<$numnew; $i++) {
                   6305:                 my $newkey = $newitems[$i];
                   6306:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6307:                 if ($newkey =~ /^\d+:/) { 
                   6308:                     $newkey =~ s/^(\d+)/$newid/;
                   6309:                     $translation{$1} = $newid;
                   6310:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6311:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6312:                     $translation{$1} = $newid;
                   6313:                 }
1.749     raeburn  6314:                 $new_values{$file_name."\0".$newkey} = 
                   6315:                                           $$changes{'activate'}{$newitems[$i]};
                   6316:                 $new_control{$newkey} = $now;
                   6317:             }
                   6318:         }
                   6319:     }
                   6320:     my %todelete;
                   6321:     my %changed_items;
                   6322:     foreach my $action ('delete','update') {
                   6323:         if (exists($$changes{$action})) {
                   6324:             if (ref($$changes{$action}) eq 'HASH') {
                   6325:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6326:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6327:                     if ($action eq 'delete') { 
                   6328:                         $todelete{$itemnum} = 1;
                   6329:                     } else {
                   6330:                         $changed_items{$itemnum} = $key;
                   6331:                     }
                   6332:                 }
1.745     raeburn  6333:             }
                   6334:         }
1.749     raeburn  6335:     }
                   6336:     # get lock on access controls for file.
                   6337:     my $lockhash = {
                   6338:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6339:                                                        ':'.$env{'user.domain'},
                   6340:                    }; 
                   6341:     my $tries = 0;
                   6342:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6343:    
                   6344:     while (($gotlock ne 'ok') && $tries <3) {
                   6345:         $tries ++;
                   6346:         sleep 1;
                   6347:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6348:     }
                   6349:     if ($gotlock eq 'ok') {
                   6350:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6351:         my ($tmp)=keys(%curr_permissions);
                   6352:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6353:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6354:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6355:             if (ref($curr_controls) eq 'HASH') {
                   6356:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6357:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6358:                     if (defined($todelete{$itemnum})) {
                   6359:                         push(@deletions,$file_name."\0".$control_item);
                   6360:                     } else {
                   6361:                         if (defined($changed_items{$itemnum})) {
                   6362:                             $new_control{$changed_items{$itemnum}} = $now;
                   6363:                             push(@deletions,$file_name."\0".$control_item);
                   6364:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6365:                         } else {
                   6366:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6367:                         }
                   6368:                     }
1.745     raeburn  6369:                 }
                   6370:             }
                   6371:         }
1.970     raeburn  6372:         my ($group);
                   6373:         if (&is_course($domain,$user)) {
                   6374:             ($group,my $file) = split(/\//,$file_name,2);
                   6375:         }
1.749     raeburn  6376:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6377:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6378:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6379:         #  remove lock
                   6380:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6381:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6382:         my $sqlresult =
1.970     raeburn  6383:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6384:                                     $group);
1.749     raeburn  6385:     } else {
                   6386:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6387:     }
1.749     raeburn  6388:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6389: }
                   6390: 
1.827     raeburn  6391: sub make_public_indefinitely {
                   6392:     my ($requrl) = @_;
                   6393:     my $now = time;
                   6394:     my $action = 'activate';
                   6395:     my $aclnum = 0;
                   6396:     if (&is_portfolio_url($requrl)) {
                   6397:         my (undef,$udom,$unum,$file_name,$group) =
                   6398:             &parse_portfolio_url($requrl);
                   6399:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6400:         my %access_controls = &get_access_controls($current_perms,
                   6401:                                                    $group,$file_name);
                   6402:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6403:             my ($num,$scope,$end,$start) = 
                   6404:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6405:             if ($scope eq 'public') {
                   6406:                 if ($start <= $now && $end == 0) {
                   6407:                     $action = 'none';
                   6408:                 } else {
                   6409:                     $action = 'update';
                   6410:                     $aclnum = $num;
                   6411:                 }
                   6412:                 last;
                   6413:             }
                   6414:         }
                   6415:         if ($action eq 'none') {
                   6416:              return 'ok';
                   6417:         } else {
                   6418:             my %changes;
                   6419:             my $newend = 0;
                   6420:             my $newstart = $now;
                   6421:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6422:             $changes{$action}{$newkey} = {
                   6423:                 type => 'public',
                   6424:                 time => {
                   6425:                     start => $newstart,
                   6426:                     end   => $newend,
                   6427:                 },
                   6428:             };
                   6429:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6430:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6431:             return $outcome;
                   6432:         }
                   6433:     } else {
                   6434:         return 'invalid';
                   6435:     }
                   6436: }
                   6437: 
1.745     raeburn  6438: #------------------------------------------------------Get Marked as Read Only
                   6439: 
                   6440: sub get_marked_as_readonly {
                   6441:     my ($domain,$user,$what,$group) = @_;
                   6442:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6443:     my @readonly_files;
1.629     banghart 6444:     my $cmp1=$what;
                   6445:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6446:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6447:         if (defined($group)) {
                   6448:             if ($file_name !~ m-^\Q$group\E/-) {
                   6449:                 next;
                   6450:             }
                   6451:         }
1.561     banghart 6452:         if (ref($value) eq "ARRAY"){
                   6453:             foreach my $stored_what (@{$value}) {
1.629     banghart 6454:                 my $cmp2=$stored_what;
1.759     albertel 6455:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6456:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6457:                 }
1.629     banghart 6458:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6459:                     push(@readonly_files, $file_name);
1.745     raeburn  6460:                     last;
1.563     banghart 6461:                 } elsif (!defined($what)) {
                   6462:                     push(@readonly_files, $file_name);
1.745     raeburn  6463:                     last;
1.561     banghart 6464:                 }
                   6465:             }
1.745     raeburn  6466:         }
1.561     banghart 6467:     }
                   6468:     return @readonly_files;
                   6469: }
1.577     banghart 6470: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6471: 
1.577     banghart 6472: sub get_marked_as_readonly_hash {
1.745     raeburn  6473:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6474:     my %readonly_files;
1.745     raeburn  6475:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6476:         if (defined($group)) {
                   6477:             if ($file_name !~ m-^\Q$group\E/-) {
                   6478:                 next;
                   6479:             }
                   6480:         }
1.577     banghart 6481:         if (ref($value) eq "ARRAY"){
                   6482:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6483:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6484:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6485:                         if ($lock_descriptor eq 'graded') {
                   6486:                             $readonly_files{$file_name} = 'graded';
                   6487:                         } elsif ($lock_descriptor eq 'handback') {
                   6488:                             $readonly_files{$file_name} = 'handback';
                   6489:                         } else {
                   6490:                             if (!exists($readonly_files{$file_name})) {
                   6491:                                 $readonly_files{$file_name} = 'locked';
                   6492:                             }
                   6493:                         }
1.745     raeburn  6494:                     }
1.750     banghart 6495:                 } 
1.577     banghart 6496:             }
                   6497:         } 
                   6498:     }
                   6499:     return %readonly_files;
                   6500: }
1.559     banghart 6501: # ------------------------------------------------------------ Unmark as Read Only
                   6502: 
                   6503: sub unmark_as_readonly {
1.629     banghart 6504:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6505:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6506:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6507:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6508:     my $symb_crs = $what;
                   6509:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6510:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6511:     my ($tmp)=keys(%current_permissions);
                   6512:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6513:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6514:     foreach my $file (@readonly_files) {
1.759     albertel 6515: 	my $clean_file = &declutter_portfile($file);
                   6516: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6517: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6518:         my @new_locks;
                   6519:         my @del_keys;
                   6520:         if (ref($current_locks) eq "ARRAY"){
                   6521:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6522:                 my $compare=$locker;
1.749     raeburn  6523:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6524:                     $compare=join('',@{$locker});
1.746     raeburn  6525:                     if ($compare ne $symb_crs) {
                   6526:                         push(@new_locks, $locker);
                   6527:                     }
1.563     banghart 6528:                 }
                   6529:             }
1.650     albertel 6530:             if (scalar(@new_locks) > 0) {
1.563     banghart 6531:                 $current_permissions{$file} = \@new_locks;
                   6532:             } else {
                   6533:                 push(@del_keys, $file);
1.613     albertel 6534:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6535:                 delete($current_permissions{$file});
1.563     banghart 6536:             }
                   6537:         }
1.561     banghart 6538:     }
1.613     albertel 6539:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6540:     return;
                   6541: }
1.512     banghart 6542: 
1.17      www      6543: # ------------------------------------------------------------ Directory lister
                   6544: 
                   6545: sub dirlist {
1.955     raeburn  6546:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6547:     $uri=~s/^\///;
                   6548:     $uri=~s/\/$//;
1.253     stredwic 6549:     my ($udom, $uname);
1.955     raeburn  6550:     if ($getuserdir) {
1.253     stredwic 6551:         $udom = $userdomain;
                   6552:         $uname = $username;
1.955     raeburn  6553:     } else {
                   6554:         (undef,$udom,$uname)=split(/\//,$uri);
                   6555:         if(defined($userdomain)) {
                   6556:             $udom = $userdomain;
                   6557:         }
                   6558:         if(defined($username)) {
                   6559:             $uname = $username;
                   6560:         }
1.253     stredwic 6561:     }
1.955     raeburn  6562:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6563: 
1.955     raeburn  6564:     $dirRoot = $perlvar{'lonDocRoot'};
                   6565:     if (defined($getpropath)) {
                   6566:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6567:         $dirRoot =~ s/\/$//;
1.955     raeburn  6568:     } elsif (defined($getuserdir)) {
                   6569:         my $subdir=$uname.'__';
                   6570:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6571:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6572:                    ."/$udom/$subdir/$uname";
                   6573:     } elsif (defined($alternateRoot)) {
                   6574:         $dirRoot = $alternateRoot;
1.751     banghart 6575:     }
1.253     stredwic 6576: 
                   6577:     if($udom) {
                   6578:         if($uname) {
1.955     raeburn  6579:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6580:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6581:                               .':'.&escape($uname).':'.&escape($udom),
                   6582:                               &homeserver($uname,$udom));
                   6583:             if ($listing eq 'unknown_cmd') {
                   6584:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6585:                                   &homeserver($uname,$udom));
                   6586:             } else {
                   6587:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6588:             }
1.605     matthew  6589:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6590:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6591: 				  &homeserver($uname,$udom));
1.605     matthew  6592:                 @listing_results = split(/:/,$listing);
                   6593:             } else {
                   6594:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6595:             }
                   6596:             return @listing_results;
1.955     raeburn  6597:         } elsif(!$alternateRoot) {
1.800     albertel 6598:             my %allusers;
1.841     albertel 6599: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6600:  	    foreach my $tryserver (keys(%servers)) {
                   6601:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6602:                                   &escape($udom),$tryserver);
                   6603:                 if ($listing eq 'unknown_cmd') {
                   6604: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6605: 				      $udom, $tryserver);
                   6606:                 } else {
                   6607:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6608:                 }
1.841     albertel 6609: 		if ($listing eq 'unknown_cmd') {
                   6610: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6611: 				      $udom, $tryserver);
                   6612: 		    @listing_results = split(/:/,$listing);
                   6613: 		} else {
                   6614: 		    @listing_results =
                   6615: 			map { &unescape($_); } split(/:/,$listing);
                   6616: 		}
                   6617: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6618: 		    $listing_results[0] ne 'empty'       &&
                   6619: 		    $listing_results[0] ne 'con_lost') {
                   6620: 		    foreach my $line (@listing_results) {
                   6621: 			my ($entry) = split(/&/,$line,2);
                   6622: 			$allusers{$entry} = 1;
                   6623: 		    }
                   6624: 		}
1.253     stredwic 6625:             }
                   6626:             my $alluserstr='';
1.800     albertel 6627:             foreach my $user (sort(keys(%allusers))) {
                   6628:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6629:             }
                   6630:             $alluserstr=~s/:$//;
                   6631:             return split(/:/,$alluserstr);
                   6632:         } else {
1.800     albertel 6633:             return ('missing user name');
1.253     stredwic 6634:         }
1.955     raeburn  6635:     } elsif(!defined($getpropath)) {
1.841     albertel 6636:         my @all_domains = sort(&all_domains());
1.955     raeburn  6637:         foreach my $domain (@all_domains) {
                   6638:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6639:         }
                   6640:         return @all_domains;
                   6641:     } else {
1.800     albertel 6642:         return ('missing domain');
1.275     stredwic 6643:     }
                   6644: }
                   6645: 
                   6646: # --------------------------------------------- GetFileTimestamp
                   6647: # This function utilizes dirlist and returns the date stamp for
                   6648: # when it was last modified.  It will also return an error of -1
                   6649: # if an error occurs
                   6650: 
                   6651: sub GetFileTimestamp {
1.955     raeburn  6652:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6653:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6654:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6655:     my ($fileStat) = 
                   6656:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6657:                                  undef,$getuserdir);
1.275     stredwic 6658:     my @stats = split('&', $fileStat);
                   6659:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6660:         # @stats contains first the filename, then the stat output
                   6661:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6662:     } else {
                   6663:         return -1;
1.253     stredwic 6664:     }
1.26      www      6665: }
                   6666: 
1.712     albertel 6667: sub stat_file {
                   6668:     my ($uri) = @_;
1.787     albertel 6669:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6670: 
1.955     raeburn  6671:     my ($udom,$uname,$file);
1.712     albertel 6672:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6673: 	($udom,$uname,$file) =
1.811     albertel 6674: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6675: 	$file = 'userfiles/'.$file;
                   6676:     }
                   6677:     if ($uri =~ m-^/res/-) {
                   6678: 	($udom,$uname) = 
1.807     albertel 6679: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6680: 	$file = $uri;
                   6681:     }
                   6682: 
                   6683:     if (!$udom || !$uname || !$file) {
                   6684: 	# unable to handle the uri
                   6685: 	return ();
                   6686:     }
1.956     raeburn  6687:     my $getpropath;
                   6688:     if ($file =~ /^userfiles\//) {
                   6689:         $getpropath = 1;
                   6690:     }
1.955     raeburn  6691:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6692:     my @stats = split('&', $result);
1.721     banghart 6693:     
1.712     albertel 6694:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6695: 	shift(@stats); #filename is first
                   6696: 	return @stats;
                   6697:     }
                   6698:     return ();
                   6699: }
                   6700: 
1.26      www      6701: # -------------------------------------------------------- Value of a Condition
                   6702: 
1.713     albertel 6703: # gets the value of a specific preevaluated condition
                   6704: #    stored in the string  $env{user.state.<cid>}
                   6705: # or looks up a condition reference in the bighash and if if hasn't
                   6706: # already been evaluated recurses into docondval to get the value of
                   6707: # the condition, then memoizing it to 
                   6708: #   $env{user.state.<cid>.<condition>}
1.40      www      6709: sub directcondval {
                   6710:     my $number=shift;
1.620     albertel 6711:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6712: 	&Apache::lonuserstate::evalstate();
                   6713:     }
1.713     albertel 6714:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6715: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6716:     } elsif ($number =~ /^_/) {
                   6717: 	my $sub_condition;
                   6718: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6719: 		&GDBM_READER(),0640)) {
                   6720: 	    $sub_condition=$bighash{'conditions'.$number};
                   6721: 	    untie(%bighash);
                   6722: 	}
                   6723: 	my $value = &docondval($sub_condition);
1.949     raeburn  6724: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6725: 	return $value;
                   6726:     }
1.620     albertel 6727:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6728:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6729:     } else {
                   6730:        return 2;
                   6731:     }
                   6732: }
                   6733: 
1.713     albertel 6734: # get the collection of conditions for this resource
1.26      www      6735: sub condval {
                   6736:     my $condidx=shift;
1.54      www      6737:     my $allpathcond='';
1.713     albertel 6738:     foreach my $cond (split(/\|/,$condidx)) {
                   6739: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6740: 	    $allpathcond.=
                   6741: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6742: 	}
1.191     harris41 6743:     }
1.54      www      6744:     $allpathcond=~s/\|$//;
1.713     albertel 6745:     return &docondval($allpathcond);
                   6746: }
                   6747: 
                   6748: #evaluates an expression of conditions
                   6749: sub docondval {
                   6750:     my ($allpathcond) = @_;
                   6751:     my $result=0;
                   6752:     if ($env{'request.course.id'}
                   6753: 	&& defined($allpathcond)) {
                   6754: 	my $operand='|';
                   6755: 	my @stack;
                   6756: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6757: 	    if ($chunk eq '(') {
                   6758: 		push @stack,($operand,$result);
                   6759: 	    } elsif ($chunk eq ')') {
                   6760: 		my $before=pop @stack;
                   6761: 		if (pop @stack eq '&') {
                   6762: 		    $result=$result>$before?$before:$result;
                   6763: 		} else {
                   6764: 		    $result=$result>$before?$result:$before;
                   6765: 		}
                   6766: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6767: 		$operand=$chunk;
                   6768: 	    } else {
                   6769: 		my $new=directcondval($chunk);
                   6770: 		if ($operand eq '&') {
                   6771: 		    $result=$result>$new?$new:$result;
                   6772: 		} else {
                   6773: 		    $result=$result>$new?$result:$new;
                   6774: 		}
                   6775: 	    }
                   6776: 	}
1.26      www      6777:     }
                   6778:     return $result;
1.421     albertel 6779: }
                   6780: 
                   6781: # ---------------------------------------------------- Devalidate courseresdata
                   6782: 
                   6783: sub devalidatecourseresdata {
                   6784:     my ($coursenum,$coursedomain)=@_;
                   6785:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6786:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6787: }
                   6788: 
1.763     www      6789: 
1.200     www      6790: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6791: #
                   6792: #  Parameters:
                   6793: #      $coursenum    - Number of the course.
                   6794: #      $coursedomain - Domain at which the course was created.
                   6795: #  Returns:
                   6796: #     A hash of the course parameters along (I think) with timestamps
                   6797: #     and version info.
1.877     foxr     6798: 
1.624     albertel 6799: sub get_courseresdata {
                   6800:     my ($coursenum,$coursedomain)=@_;
1.200     www      6801:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6802:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6803:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6804:     my %dumpreply;
1.417     albertel 6805:     unless (defined($cached)) {
1.624     albertel 6806: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6807: 	$result=\%dumpreply;
1.251     albertel 6808: 	my ($tmp) = keys(%dumpreply);
                   6809: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6810: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6811: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6812: 	    return $tmp;
1.416     albertel 6813: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6814: 	    $result=undef;
1.599     albertel 6815: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6816: 	}
                   6817:     }
1.624     albertel 6818:     return $result;
                   6819: }
                   6820: 
1.633     albertel 6821: sub devalidateuserresdata {
                   6822:     my ($uname,$udom)=@_;
                   6823:     my $hashid="$udom:$uname";
                   6824:     &devalidate_cache_new('userres',$hashid);
                   6825: }
                   6826: 
1.624     albertel 6827: sub get_userresdata {
                   6828:     my ($uname,$udom)=@_;
                   6829:     #most student don\'t have any data set, check if there is some data
                   6830:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6831: 
                   6832:     my $hashid="$udom:$uname";
                   6833:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6834:     if (!defined($cached)) {
                   6835: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6836: 	$result=\%resourcedata;
                   6837: 	&do_cache_new('userres',$hashid,$result,600);
                   6838:     }
                   6839:     my ($tmp)=keys(%$result);
                   6840:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6841: 	return $result;
                   6842:     }
                   6843:     #error 2 occurs when the .db doesn't exist
                   6844:     if ($tmp!~/error: 2 /) {
1.672     albertel 6845: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6846: 		 " Trying to get resource data for ".
                   6847: 		 $uname." at ".$udom.": ".
                   6848: 		 $tmp."</font>");
                   6849:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6850: 	#&EXT_cache_set($udom,$uname);
                   6851: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6852: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6853:     }
                   6854:     return $tmp;
                   6855: }
1.879     foxr     6856: #----------------------------------------------- resdata - return resource data
                   6857: #  Purpose:
                   6858: #    Return resource data for either users or for a course.
                   6859: #  Parameters:
                   6860: #     $name      - Course/user name.
                   6861: #     $domain    - Name of the domain the user/course is registered on.
                   6862: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6863: #     @which     - Array of names of resources desired.
                   6864: #  Returns:
                   6865: #     The value of the first reasource in @which that is found in the
                   6866: #     resource hash.
                   6867: #  Exceptional Conditions:
                   6868: #     If the $type passed in is not valid (not the string 'course' or 
                   6869: #     'user', an undefined  reference is returned.
                   6870: #     If none of the resources are found, an undef is returned
1.624     albertel 6871: sub resdata {
                   6872:     my ($name,$domain,$type,@which)=@_;
                   6873:     my $result;
                   6874:     if ($type eq 'course') {
                   6875: 	$result=&get_courseresdata($name,$domain);
                   6876:     } elsif ($type eq 'user') {
                   6877: 	$result=&get_userresdata($name,$domain);
                   6878:     }
                   6879:     if (!ref($result)) { return $result; }    
1.251     albertel 6880:     foreach my $item (@which) {
1.927     albertel 6881: 	if (defined($result->{$item->[0]})) {
                   6882: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6883: 	}
1.250     albertel 6884:     }
1.291     albertel 6885:     return undef;
1.200     www      6886: }
                   6887: 
1.379     matthew  6888: #
                   6889: # EXT resource caching routines
                   6890: #
                   6891: 
                   6892: sub clear_EXT_cache_status {
1.383     albertel 6893:     &delenv('cache.EXT.');
1.379     matthew  6894: }
                   6895: 
                   6896: sub EXT_cache_status {
                   6897:     my ($target_domain,$target_user) = @_;
1.383     albertel 6898:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6899:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6900:         # We know already the user has no data
                   6901:         return 1;
                   6902:     } else {
                   6903:         return 0;
                   6904:     }
                   6905: }
                   6906: 
                   6907: sub EXT_cache_set {
                   6908:     my ($target_domain,$target_user) = @_;
1.383     albertel 6909:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6910:     #&appenv({$cachename => time});
1.379     matthew  6911: }
                   6912: 
1.28      www      6913: # --------------------------------------------------------- Value of a Variable
1.58      www      6914: sub EXT {
1.715     albertel 6915: 
1.395     albertel 6916:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6917:     unless ($varname) { return ''; }
1.218     albertel 6918:     #get real user name/domain, courseid and symb
                   6919:     my $courseid;
1.359     albertel 6920:     my $publicuser;
1.427     www      6921:     if ($symbparm) {
                   6922: 	$symbparm=&get_symb_from_alias($symbparm);
                   6923:     }
1.218     albertel 6924:     if (!($uname && $udom)) {
1.790     albertel 6925:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6926:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6927:     } else {
1.620     albertel 6928: 	$courseid=$env{'request.course.id'};
1.218     albertel 6929:     }
1.48      www      6930:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6931:     my $rest;
1.320     albertel 6932:     if (defined($therest[0])) {
1.48      www      6933:        $rest=join('.',@therest);
                   6934:     } else {
                   6935:        $rest='';
                   6936:     }
1.320     albertel 6937: 
1.57      www      6938:     my $qualifierrest=$qualifier;
                   6939:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6940:     my $spacequalifierrest=$space;
                   6941:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6942:     if ($realm eq 'user') {
1.48      www      6943: # --------------------------------------------------------------- user.resource
                   6944: 	if ($space eq 'resource') {
1.651     albertel 6945: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6946: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6947: 		 &&
1.744     albertel 6948: 		 ($symbparm eq &symbread()) ) {	
                   6949: 		# if we are in the middle of processing the resource the
                   6950: 		# get the value we are planning on committing
                   6951:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6952:                     return $Apache::lonhomework::results{$qualifierrest};
                   6953:                 } else {
                   6954:                     return $Apache::lonhomework::history{$qualifierrest};
                   6955:                 }
1.335     albertel 6956: 	    } else {
1.359     albertel 6957: 		my %restored;
1.620     albertel 6958: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6959: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6960: 		} else {
                   6961: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6962: 		}
1.335     albertel 6963: 		return $restored{$qualifierrest};
                   6964: 	    }
1.48      www      6965: # ----------------------------------------------------------------- user.access
                   6966:         } elsif ($space eq 'access') {
1.218     albertel 6967: 	    # FIXME - not supporting calls for a specific user
1.48      www      6968:             return &allowed($qualifier,$rest);
                   6969: # ------------------------------------------ user.preferences, user.environment
                   6970:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6971: 	    if (($uname eq $env{'user.name'}) &&
                   6972: 		($udom eq $env{'user.domain'})) {
                   6973: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6974: 	    } else {
1.359     albertel 6975: 		my %returnhash;
                   6976: 		if (!$publicuser) {
                   6977: 		    %returnhash=&userenvironment($udom,$uname,
                   6978: 						 $qualifierrest);
                   6979: 		}
1.218     albertel 6980: 		return $returnhash{$qualifierrest};
                   6981: 	    }
1.48      www      6982: # ----------------------------------------------------------------- user.course
                   6983:         } elsif ($space eq 'course') {
1.218     albertel 6984: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6985:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6986: # ------------------------------------------------------------------- user.role
                   6987:         } elsif ($space eq 'role') {
1.218     albertel 6988: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6989:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6990:             if ($qualifier eq 'value') {
                   6991: 		return $role;
                   6992:             } elsif ($qualifier eq 'extent') {
                   6993:                 return $where;
                   6994:             }
                   6995: # ----------------------------------------------------------------- user.domain
                   6996:         } elsif ($space eq 'domain') {
1.218     albertel 6997:             return $udom;
1.48      www      6998: # ------------------------------------------------------------------- user.name
                   6999:         } elsif ($space eq 'name') {
1.218     albertel 7000:             return $uname;
1.48      www      7001: # ---------------------------------------------------- Any other user namespace
1.29      www      7002:         } else {
1.359     albertel 7003: 	    my %reply;
                   7004: 	    if (!$publicuser) {
                   7005: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7006: 	    }
                   7007: 	    return $reply{$qualifierrest};
1.48      www      7008:         }
1.236     www      7009:     } elsif ($realm eq 'query') {
                   7010: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7011:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7012: 						[$spacequalifierrest]);
1.620     albertel 7013: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7014:    } elsif ($realm eq 'request') {
1.48      www      7015: # ------------------------------------------------------------- request.browser
                   7016:         if ($space eq 'browser') {
1.430     www      7017: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7018: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7019: 		    return 1;
                   7020: 		} else {
                   7021: 		    return 0;
                   7022: 		}
                   7023: 	    } else {
1.620     albertel 7024: 		return $env{'browser.'.$qualifier};
1.430     www      7025: 	    }
1.57      www      7026: # ------------------------------------------------------------ request.filename
                   7027:         } else {
1.620     albertel 7028:             return $env{'request.'.$spacequalifierrest};
1.29      www      7029:         }
1.28      www      7030:     } elsif ($realm eq 'course') {
1.48      www      7031: # ---------------------------------------------------------- course.description
1.620     albertel 7032:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7033:     } elsif ($realm eq 'resource') {
1.165     www      7034: 
1.620     albertel 7035: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7036: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7037: 	}
1.693     albertel 7038: 
                   7039: 	if ($space eq 'title') {
                   7040: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7041: 	    return &gettitle($symbparm);
                   7042: 	}
                   7043: 	
                   7044: 	if ($space eq 'map') {
                   7045: 	    my ($map) = &decode_symb($symbparm);
                   7046: 	    return &symbread($map);
                   7047: 	}
1.905     albertel 7048: 	if ($space eq 'filename') {
                   7049: 	    if ($symbparm) {
                   7050: 		return &clutter((&decode_symb($symbparm))[2]);
                   7051: 	    }
                   7052: 	    return &hreflocation('',$env{'request.filename'});
                   7053: 	}
1.693     albertel 7054: 
                   7055: 	my ($section, $group, @groups);
1.593     albertel 7056: 	my ($courselevelm,$courselevel);
1.539     albertel 7057: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7058: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7059: 
1.218     albertel 7060: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7061: 
1.60      www      7062: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7063: 	    my $symbp=$symbparm;
1.735     albertel 7064: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7065: 
                   7066: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7067: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7068: 
1.620     albertel 7069: 	    if (($env{'user.name'} eq $uname) &&
                   7070: 		($env{'user.domain'} eq $udom)) {
                   7071: 		$section=$env{'request.course.sec'};
1.733     raeburn  7072:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7073:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7074: 	    } else {
1.539     albertel 7075: 		if (! defined($usection)) {
1.551     albertel 7076: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7077: 		} else {
                   7078: 		    $section = $usection;
                   7079: 		}
1.733     raeburn  7080:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7081: 	    }
                   7082: 
                   7083: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7084: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7085: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7086: 
1.593     albertel 7087: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7088: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7089: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7090: 
1.60      www      7091: # ----------------------------------------------------------- first, check user
1.624     albertel 7092: 
                   7093: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7094: 				       ([$courselevelr,'resource'],
                   7095: 					[$courselevelm,'map'     ],
                   7096: 					[$courselevel, 'course'  ]));
1.931     albertel 7097: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7098: 
1.594     albertel 7099: # ------------------------------------------------ second, check some of course
1.684     raeburn  7100:             my $coursereply;
1.691     raeburn  7101:             if (@groups > 0) {
                   7102:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7103:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7104:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7105:             }
1.96      www      7106: 
1.684     raeburn  7107: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7108: 				  $env{'course.'.$courseid.'.domain'},
                   7109: 				  'course',
                   7110: 				  ([$seclevelr,   'resource'],
                   7111: 				   [$seclevelm,   'map'     ],
                   7112: 				   [$seclevel,    'course'  ],
                   7113: 				   [$courselevelr,'resource']));
                   7114: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7115: 
1.60      www      7116: # ------------------------------------------------------ third, check map parms
1.218     albertel 7117: 	    my %parmhash=();
                   7118: 	    my $thisparm='';
                   7119: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7120: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7121: 		    &GDBM_READER(),0640)) {
1.218     albertel 7122: 		$thisparm=$parmhash{$symbparm};
                   7123: 		untie(%parmhash);
                   7124: 	    }
1.927     albertel 7125: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7126: 	}
1.594     albertel 7127: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7128: 
1.218     albertel 7129: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7130: 	my $filename;
                   7131: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7132: 	if ($symbparm) {
1.409     www      7133: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7134: 	} else {
1.620     albertel 7135: 	    $filename=$env{'request.filename'};
1.282     albertel 7136: 	}
                   7137: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7138: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7139: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7140: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7141: 
1.927     albertel 7142: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7143: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7144: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7145: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7146: 				     $env{'course.'.$courseid.'.domain'},
                   7147: 				     'course',
1.927     albertel 7148: 				     ([$courselevelm,'map'   ],
                   7149: 				      [$courselevel, 'course']));
                   7150: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7151: 	}
1.145     www      7152: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7153: 	unless ($space eq '0') {
1.336     albertel 7154: 	    my @parts=split(/_/,$space);
                   7155: 	    my $id=pop(@parts);
                   7156: 	    my $part=join('_',@parts);
                   7157: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7158: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7159: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7160: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7161: 	}
1.395     albertel 7162: 	if ($recurse) { return undef; }
                   7163: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7164: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7165: # ---------------------------------------------------- Any other user namespace
                   7166:     } elsif ($realm eq 'environment') {
                   7167: # ----------------------------------------------------------------- environment
1.620     albertel 7168: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7169: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7170: 	} else {
1.770     albertel 7171: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7172: 		return '';
                   7173: 	    }
1.219     albertel 7174: 	    my %returnhash=&userenvironment($udom,$uname,
                   7175: 					    $spacequalifierrest);
                   7176: 	    return $returnhash{$spacequalifierrest};
                   7177: 	}
1.28      www      7178:     } elsif ($realm eq 'system') {
1.48      www      7179: # ----------------------------------------------------------------- system.time
                   7180: 	if ($space eq 'time') {
                   7181: 	    return time;
                   7182:         }
1.696     albertel 7183:     } elsif ($realm eq 'server') {
                   7184: # ----------------------------------------------------------------- system.time
                   7185: 	if ($space eq 'name') {
                   7186: 	    return $ENV{'SERVER_NAME'};
                   7187:         }
1.28      www      7188:     }
1.48      www      7189:     return '';
1.61      www      7190: }
                   7191: 
1.927     albertel 7192: sub get_reply {
                   7193:     my ($reply_value) = @_;
1.940     raeburn  7194:     if (ref($reply_value) eq 'ARRAY') {
                   7195:         if (wantarray) {
                   7196: 	    return @$reply_value;
                   7197:         }
                   7198:         return $reply_value->[0];
                   7199:     } else {
                   7200:         return $reply_value;
1.927     albertel 7201:     }
                   7202: }
                   7203: 
1.691     raeburn  7204: sub check_group_parms {
                   7205:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7206:     my @groupitems = ();
                   7207:     my $resultitem;
1.927     albertel 7208:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7209:     foreach my $group (@{$groups}) {
                   7210:         foreach my $level (@levels) {
1.927     albertel 7211:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7212:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7213:         }
                   7214:     }
                   7215:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7216:                             $env{'course.'.$courseid.'.domain'},
                   7217:                                      'course',@groupitems);
                   7218:     return $coursereply;
                   7219: }
                   7220: 
                   7221: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7222:     my ($courseid,@groups) = @_;
                   7223:     @groups = sort(@groups);
1.691     raeburn  7224:     return @groups;
                   7225: }
                   7226: 
1.395     albertel 7227: sub packages_tab_default {
                   7228:     my ($uri,$varname)=@_;
                   7229:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7230: 
                   7231:     my (@extension,@specifics,$do_default);
                   7232:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7233: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7234: 	if ($pack_type eq 'default') {
                   7235: 	    $do_default=1;
                   7236: 	} elsif ($pack_type eq 'extension') {
                   7237: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7238: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7239: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7240: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7241: 	}
                   7242:     }
                   7243:     # first look for a package that matches the requested part id
                   7244:     foreach my $package (@specifics) {
                   7245: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7246: 	next if ($pack_part ne $part);
                   7247: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7248: 	    return $packagetab{"$pack_type&$name&default"};
                   7249: 	}
                   7250:     }
                   7251:     # look for any possible matching non extension_ package
                   7252:     foreach my $package (@specifics) {
                   7253: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7254: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7255: 	    return $packagetab{"$pack_type&$name&default"};
                   7256: 	}
1.585     albertel 7257: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7258: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7259: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7260: 	}
                   7261:     }
1.738     albertel 7262:     # look for any posible extension_ match
                   7263:     foreach my $package (@extension) {
                   7264: 	my ($package,$pack_type)=@{$package};
                   7265: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7266: 	    return $packagetab{"$pack_type&$name&default"};
                   7267: 	}
                   7268: 	if (defined($packagetab{$package."&$name&default"})) {
                   7269: 	    return $packagetab{$package."&$name&default"};
                   7270: 	}
                   7271:     }
                   7272:     # look for a global default setting
                   7273:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7274: 	return $packagetab{"default&$name&default"};
                   7275:     }
1.395     albertel 7276:     return undef;
                   7277: }
                   7278: 
1.334     albertel 7279: sub add_prefix_and_part {
                   7280:     my ($prefix,$part)=@_;
                   7281:     my $keyroot;
                   7282:     if (defined($prefix) && $prefix !~ /^__/) {
                   7283: 	# prefix that has a part already
                   7284: 	$keyroot=$prefix;
                   7285:     } elsif (defined($prefix)) {
                   7286: 	# prefix that is missing a part
                   7287: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7288:     } else {
                   7289: 	# no prefix at all
                   7290: 	if (defined($part)) { $keyroot='_'.$part; }
                   7291:     }
                   7292:     return $keyroot;
                   7293: }
                   7294: 
1.71      www      7295: # ---------------------------------------------------------------- Get metadata
                   7296: 
1.599     albertel 7297: my %metaentry;
1.71      www      7298: sub metadata {
1.176     www      7299:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7300:     $uri=&declutter($uri);
1.288     albertel 7301:     # if it is a non metadata possible uri return quickly
1.529     albertel 7302:     if (($uri eq '') || 
                   7303: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7304: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7305:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7306: 	return undef;
                   7307:     }
                   7308:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7309: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7310: 	return undef;
1.288     albertel 7311:     }
1.73      www      7312:     my $filename=$uri;
                   7313:     $uri=~s/\.meta$//;
1.172     www      7314: #
                   7315: # Is the metadata already cached?
1.177     www      7316: # Look at timestamp of caching
1.172     www      7317: # Everything is cached by the main uri, libraries are never directly cached
                   7318: #
1.428     albertel 7319:     if (!defined($liburi)) {
1.599     albertel 7320: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7321: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7322:     }
                   7323:     {
1.172     www      7324: #
                   7325: # Is this a recursive call for a library?
                   7326: #
1.599     albertel 7327: #	if (! exists($metacache{$uri})) {
                   7328: #	    $metacache{$uri}={};
                   7329: #	}
1.924     albertel 7330: 	my $cachetime = 60*60;
1.171     www      7331:         if ($liburi) {
                   7332: 	    $liburi=&declutter($liburi);
                   7333:             $filename=$liburi;
1.401     bowersj2 7334:         } else {
1.599     albertel 7335: 	    &devalidate_cache_new('meta',$uri);
                   7336: 	    undef(%metaentry);
1.401     bowersj2 7337: 	}
1.140     www      7338:         my %metathesekeys=();
1.73      www      7339:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7340: 	my $metastring;
1.924     albertel 7341: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7342: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7343: 	    $metastring = 
1.929     albertel 7344: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7345: 					  ('grade_target' => 'meta'));
                   7346: 	    $cachetime = 1; # only want this cached in the child not long term
                   7347: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7348: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7349: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7350: 	    $metastring=&getfile($file);
1.489     albertel 7351: 	}
1.208     albertel 7352:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7353:         my $token;
1.140     www      7354:         undef %metathesekeys;
1.71      www      7355:         while ($token=$parser->get_token) {
1.339     albertel 7356: 	    if ($token->[0] eq 'S') {
                   7357: 		if (defined($token->[2]->{'package'})) {
1.172     www      7358: #
                   7359: # This is a package - get package info
                   7360: #
1.339     albertel 7361: 		    my $package=$token->[2]->{'package'};
                   7362: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7363: 		    if (defined($token->[2]->{'id'})) { 
                   7364: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7365: 		    }
1.599     albertel 7366: 		    if ($metaentry{':packages'}) {
                   7367: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7368: 		    } else {
1.599     albertel 7369: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7370: 		    }
1.736     albertel 7371: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7372: 			my $part=$keyroot;
                   7373: 			$part=~s/^\_//;
1.736     albertel 7374: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7375: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7376: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7377: 			    # ignore package.tab specified default values
                   7378:                             # here &package_tab_default() will fetch those
                   7379: 			    if ($subp eq 'default') { next; }
1.736     albertel 7380: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7381: 			    my $unikey;
                   7382: 			    if ($pack =~ /_0$/) {
                   7383: 				$unikey='parameter_0_'.$name;
                   7384: 				$part=0;
                   7385: 			    } else {
                   7386: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7387: 			    }
1.339     albertel 7388: 			    if ($subp eq 'display') {
                   7389: 				$value.=' [Part: '.$part.']';
                   7390: 			    }
1.599     albertel 7391: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7392: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7393: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7394: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7395: 			    }
1.599     albertel 7396: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7397: 				$metaentry{':'.$unikey}=
                   7398: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7399: 			    }
1.339     albertel 7400: 			}
                   7401: 		    }
                   7402: 		} else {
1.172     www      7403: #
                   7404: # This is not a package - some other kind of start tag
1.339     albertel 7405: #
                   7406: 		    my $entry=$token->[1];
                   7407: 		    my $unikey;
                   7408: 		    if ($entry eq 'import') {
                   7409: 			$unikey='';
                   7410: 		    } else {
                   7411: 			$unikey=$entry;
                   7412: 		    }
                   7413: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7414: 
                   7415: 		    if (defined($token->[2]->{'id'})) { 
                   7416: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7417: 		    }
1.175     www      7418: 
1.339     albertel 7419: 		    if ($entry eq 'import') {
1.175     www      7420: #
                   7421: # Importing a library here
1.339     albertel 7422: #
                   7423: 			if ($depthcount<20) {
                   7424: 			    my $location=$parser->get_text('/import');
                   7425: 			    my $dir=$filename;
                   7426: 			    $dir=~s|[^/]*$||;
                   7427: 			    $location=&filelocation($dir,$location);
1.736     albertel 7428: 			    my $metadata = 
                   7429: 				&metadata($uri,'keys', $location,$unikey,
                   7430: 					  $depthcount+1);
                   7431: 			    foreach my $meta (split(',',$metadata)) {
                   7432: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7433: 				$metathesekeys{$meta}=1;
1.339     albertel 7434: 			    }
                   7435: 			}
                   7436: 		    } else { 
                   7437: 			
                   7438: 			if (defined($token->[2]->{'name'})) { 
                   7439: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7440: 			}
                   7441: 			$metathesekeys{$unikey}=1;
1.736     albertel 7442: 			foreach my $param (@{$token->[3]}) {
                   7443: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7444: 				$token->[2]->{$param};
1.339     albertel 7445: 			}
                   7446: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7447: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7448: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7449: 		 # only ws inside the tag, and not in default, so use default
                   7450: 		 # as value
1.599     albertel 7451: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7452: 			} elsif ( $internaltext =~ /\S/ ) {
                   7453: 		  # something interesting inside the tag
                   7454: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7455: 			} else {
1.908     albertel 7456: 		  # no interesting values, don't set a default
1.339     albertel 7457: 			}
1.172     www      7458: # end of not-a-package not-a-library import
1.339     albertel 7459: 		    }
1.172     www      7460: # end of not-a-package start tag
1.339     albertel 7461: 		}
1.172     www      7462: # the next is the end of "start tag"
1.339     albertel 7463: 	    }
                   7464: 	}
1.483     albertel 7465: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7466: 	$extension = lc($extension);
                   7467: 	if ($extension eq 'htm') { $extension='html'; }
                   7468: 
1.737     albertel 7469: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7470: 	    #no specific packages #how's our extension
                   7471: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7472: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7473: 					 \%metathesekeys);
                   7474: 	}
1.883     albertel 7475: 
                   7476: 	if (!exists($metaentry{':packages'})
                   7477: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7478: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7479: 		#no specific packages well let's get default then
                   7480: 		if ($key!~/^default&/) { next; }
1.488     albertel 7481: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7482: 					     \%metathesekeys);
                   7483: 	    }
                   7484: 	}
1.338     www      7485: # are there custom rights to evaluate
1.599     albertel 7486: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7487: 
1.338     www      7488:     #
                   7489:     # Importing a rights file here
1.339     albertel 7490:     #
                   7491: 	    unless ($depthcount) {
1.599     albertel 7492: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7493: 		my $dir=$filename;
                   7494: 		$dir=~s|[^/]*$||;
                   7495: 		$location=&filelocation($dir,$location);
1.736     albertel 7496: 		my $rights_metadata =
                   7497: 		    &metadata($uri,'keys',$location,'_rights',
                   7498: 			      $depthcount+1);
                   7499: 		foreach my $rights (split(',',$rights_metadata)) {
                   7500: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7501: 		    $metathesekeys{$rights}=1;
1.339     albertel 7502: 		}
                   7503: 	    }
                   7504: 	}
1.737     albertel 7505: 	# uniqifiy package listing
                   7506: 	my %seen;
                   7507: 	my @uniq_packages =
                   7508: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7509: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7510: 
                   7511: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7512: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7513: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7514: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7515: # this is the end of "was not already recently cached
1.71      www      7516:     }
1.599     albertel 7517:     return $metaentry{':'.$what};
1.261     albertel 7518: }
                   7519: 
1.488     albertel 7520: sub metadata_create_package_def {
1.483     albertel 7521:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7522:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7523:     if ($subp eq 'default') { next; }
                   7524:     
1.599     albertel 7525:     if (defined($metaentry{':packages'})) {
                   7526: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7527:     } else {
1.599     albertel 7528: 	$metaentry{':packages'}=$package;
1.483     albertel 7529:     }
                   7530:     my $value=$packagetab{$key};
                   7531:     my $unikey;
                   7532:     $unikey='parameter_0_'.$name;
1.599     albertel 7533:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7534:     $$metathesekeys{$unikey}=1;
1.599     albertel 7535:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7536: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7537:     }
1.599     albertel 7538:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7539: 	$metaentry{':'.$unikey}=
                   7540: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7541:     }
                   7542: }
                   7543: 
1.261     albertel 7544: sub metadata_generate_part0 {
                   7545:     my ($metadata,$metacache,$uri) = @_;
                   7546:     my %allnames;
1.737     albertel 7547:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7548: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7549: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7550: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7551: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7552: 	    $allnames{$name}=$part;
                   7553: 	  }
                   7554: 	}
                   7555:     }
                   7556:     foreach my $name (keys(%allnames)) {
                   7557:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7558:       my $key=":parameter_0_$name";
1.261     albertel 7559:       $$metacache{"$key.part"}='0';
                   7560:       $$metacache{"$key.name"}=$name;
1.428     albertel 7561:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7562: 					   $allnames{$name}.'_'.$name.
                   7563: 					   '.type'};
1.428     albertel 7564:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7565: 			     '.display'};
1.644     www      7566:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7567:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7568:       $$metacache{"$key.display"}=$olddis;
                   7569:     }
1.71      www      7570: }
                   7571: 
1.764     albertel 7572: # ------------------------------------------------------ Devalidate title cache
                   7573: 
                   7574: sub devalidate_title_cache {
                   7575:     my ($url)=@_;
                   7576:     if (!$env{'request.course.id'}) { return; }
                   7577:     my $symb=&symbread($url);
                   7578:     if (!$symb) { return; }
                   7579:     my $key=$env{'request.course.id'}."\0".$symb;
                   7580:     &devalidate_cache_new('title',$key);
                   7581: }
                   7582: 
1.301     www      7583: # ------------------------------------------------- Get the title of a resource
                   7584: 
                   7585: sub gettitle {
                   7586:     my $urlsymb=shift;
                   7587:     my $symb=&symbread($urlsymb);
1.534     albertel 7588:     if ($symb) {
1.620     albertel 7589: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7590: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7591: 	if (defined($cached)) { 
                   7592: 	    return $result;
                   7593: 	}
1.534     albertel 7594: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7595: 	my $title='';
1.907     albertel 7596: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7597: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7598: 	} else {
                   7599: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7600: 		    &GDBM_READER(),0640)) {
                   7601: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7602: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7603: 		untie(%bighash);
                   7604: 	    }
1.534     albertel 7605: 	}
                   7606: 	$title=~s/\&colon\;/\:/gs;
                   7607: 	if ($title) {
1.599     albertel 7608: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7609: 	}
                   7610: 	$urlsymb=$url;
                   7611:     }
                   7612:     my $title=&metadata($urlsymb,'title');
                   7613:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7614:     return $title;
1.301     www      7615: }
1.613     albertel 7616: 
1.614     albertel 7617: sub get_slot {
                   7618:     my ($which,$cnum,$cdom)=@_;
                   7619:     if (!$cnum || !$cdom) {
1.790     albertel 7620: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7621: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7622: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7623:     }
1.703     albertel 7624:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7625:     my %slotinfo;
                   7626:     if (exists($remembered{$key})) {
                   7627: 	$slotinfo{$which} = $remembered{$key};
                   7628:     } else {
                   7629: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7630: 	&Apache::lonhomework::showhash(%slotinfo);
                   7631: 	my ($tmp)=keys(%slotinfo);
                   7632: 	if ($tmp=~/^error:/) { return (); }
                   7633: 	$remembered{$key} = $slotinfo{$which};
                   7634:     }
1.616     albertel 7635:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7636: 	return %{$slotinfo{$which}};
                   7637:     }
                   7638:     return $slotinfo{$which};
1.614     albertel 7639: }
1.31      www      7640: # ------------------------------------------------- Update symbolic store links
                   7641: 
                   7642: sub symblist {
                   7643:     my ($mapname,%newhash)=@_;
1.438     www      7644:     $mapname=&deversion(&declutter($mapname));
1.31      www      7645:     my %hash;
1.620     albertel 7646:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7647:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7648:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7649: 	    foreach my $url (keys %newhash) {
                   7650: 		next if ($url eq 'last_known'
                   7651: 			 && $env{'form.no_update_last_known'});
                   7652: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7653: 						    $newhash{$url}->[1],
                   7654: 						    $newhash{$url}->[0]);
1.191     harris41 7655:             }
1.31      www      7656:             if (untie(%hash)) {
                   7657: 		return 'ok';
                   7658:             }
                   7659:         }
                   7660:     }
                   7661:     return 'error';
1.212     www      7662: }
                   7663: 
                   7664: # --------------------------------------------------------------- Verify a symb
                   7665: 
                   7666: sub symbverify {
1.510     www      7667:     my ($symb,$thisurl)=@_;
                   7668:     my $thisfn=$thisurl;
1.439     www      7669:     $thisfn=&declutter($thisfn);
1.215     www      7670: # direct jump to resource in page or to a sequence - will construct own symbs
                   7671:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7672: # check URL part
1.409     www      7673:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7674: 
1.431     www      7675:     unless ($url eq $thisfn) { return 0; }
1.213     www      7676: 
1.216     www      7677:     $symb=&symbclean($symb);
1.510     www      7678:     $thisurl=&deversion($thisurl);
1.439     www      7679:     $thisfn=&deversion($thisfn);
1.213     www      7680: 
                   7681:     my %bighash;
                   7682:     my $okay=0;
1.431     www      7683: 
1.620     albertel 7684:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7685:                             &GDBM_READER(),0640)) {
1.510     www      7686:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7687:         unless ($ids) { 
1.510     www      7688:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7689:         }
                   7690:         if ($ids) {
                   7691: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7692: 	    foreach my $id (split(/\,/,$ids)) {
                   7693: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7694:                if (
                   7695:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7696:    eq $symb) { 
1.620     albertel 7697: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7698: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7699: 		       $okay=1; 
                   7700: 		   }
                   7701: 	       }
1.216     www      7702: 	   }
                   7703:         }
1.213     www      7704: 	untie(%bighash);
                   7705:     }
                   7706:     return $okay;
1.31      www      7707: }
                   7708: 
1.210     www      7709: # --------------------------------------------------------------- Clean-up symb
                   7710: 
                   7711: sub symbclean {
                   7712:     my $symb=shift;
1.568     albertel 7713:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7714: # remove version from map
                   7715:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7716: 
1.210     www      7717: # remove version from URL
                   7718:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7719: 
1.507     www      7720: # remove wrapper
                   7721: 
1.510     www      7722:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7723:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7724:     return $symb;
1.409     www      7725: }
                   7726: 
                   7727: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7728: 
                   7729: sub encode_symb {
                   7730:     my ($map,$resid,$url)=@_;
                   7731:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7732: }
1.409     www      7733: 
                   7734: sub decode_symb {
1.568     albertel 7735:     my $symb=shift;
                   7736:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7737:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7738:     return (&fixversion($map),$resid,&fixversion($url));
                   7739: }
                   7740: 
                   7741: sub fixversion {
                   7742:     my $fn=shift;
1.609     banghart 7743:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7744:     my %bighash;
                   7745:     my $uri=&clutter($fn);
1.620     albertel 7746:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7747: # is this cached?
1.599     albertel 7748:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7749:     if (defined($cached)) { return $result; }
                   7750: # unfortunately not cached, or expired
1.620     albertel 7751:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7752: 	    &GDBM_READER(),0640)) {
                   7753:  	if ($bighash{'version_'.$uri}) {
                   7754:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7755:  	    unless (($version eq 'mostrecent') || 
                   7756: 		    ($version==&getversion($uri))) {
1.440     www      7757:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7758:  	    }
                   7759:  	}
                   7760:  	untie %bighash;
1.413     www      7761:     }
1.599     albertel 7762:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7763: }
                   7764: 
                   7765: sub deversion {
                   7766:     my $url=shift;
                   7767:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7768:     return $url;
1.210     www      7769: }
                   7770: 
1.31      www      7771: # ------------------------------------------------------ Return symb list entry
                   7772: 
                   7773: sub symbread {
1.249     www      7774:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7775:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7776:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7777: # no filename provided? try from environment
1.44      www      7778:     unless ($thisfn) {
1.620     albertel 7779:         if ($env{'request.symb'}) {
                   7780: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7781: 	}
1.620     albertel 7782: 	$thisfn=$env{'request.filename'};
1.44      www      7783:     }
1.569     albertel 7784:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7785: # is that filename actually a symb? Verify, clean, and return
                   7786:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7787: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7788: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7789: 	}
1.242     www      7790:     }
1.44      www      7791:     $thisfn=declutter($thisfn);
1.31      www      7792:     my %hash;
1.37      www      7793:     my %bighash;
                   7794:     my $syval='';
1.620     albertel 7795:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7796:         my $targetfn = $thisfn;
1.609     banghart 7797:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7798:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7799:         }
1.687     albertel 7800: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7801: 	    $targetfn=$1;
                   7802: 	}
1.620     albertel 7803:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7804:                       &GDBM_READER(),0640)) {
1.481     raeburn  7805: 	    $syval=$hash{$targetfn};
1.37      www      7806:             untie(%hash);
                   7807:         }
                   7808: # ---------------------------------------------------------- There was an entry
                   7809:         if ($syval) {
1.601     albertel 7810: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7811: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7812: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7813: 		    #return $env{$cache_str}='';
1.601     albertel 7814: 		#}    
                   7815: 		#$syval.=$1;
                   7816: 	    #}
1.37      www      7817:         } else {
                   7818: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7819:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7820:                             &GDBM_READER(),0640)) {
1.37      www      7821: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7822:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7823:               unless ($ids) { 
                   7824:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7825:               }
                   7826:               unless ($ids) {
                   7827: # alias?
                   7828: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7829:               }
1.37      www      7830:               if ($ids) {
                   7831: # ------------------------------------------------------------------- Has ID(s)
                   7832:                  my @possibilities=split(/\,/,$ids);
1.39      www      7833:                  if ($#possibilities==0) {
                   7834: # ----------------------------------------------- There is only one possibility
1.37      www      7835: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7836: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7837: 						    $resid,$thisfn);
1.249     www      7838:                  } elsif (!$donotrecurse) {
1.39      www      7839: # ------------------------------------------ There is more than one possibility
                   7840:                      my $realpossible=0;
1.800     albertel 7841:                      foreach my $id (@possibilities) {
                   7842: 			 my $file=$bighash{'src_'.$id};
1.39      www      7843:                          if (&allowed('bre',$file)) {
1.800     albertel 7844:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7845:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7846: 				$realpossible++;
1.626     albertel 7847:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7848: 						    $resid,$thisfn);
1.39      www      7849:                             }
                   7850: 			 }
1.191     harris41 7851:                      }
1.39      www      7852: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7853:                  } else {
                   7854:                      $syval='';
1.37      www      7855:                  }
                   7856: 	      }
                   7857:               untie(%bighash)
1.481     raeburn  7858:            }
1.31      www      7859:         }
1.62      www      7860:         if ($syval) {
1.620     albertel 7861: 	    return $env{$cache_str}=$syval;
1.62      www      7862:         }
1.31      www      7863:     }
1.949     raeburn  7864:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7865:     return $env{$cache_str}='';
1.31      www      7866: }
                   7867: 
                   7868: # ---------------------------------------------------------- Return random seed
                   7869: 
1.32      www      7870: sub numval {
                   7871:     my $txt=shift;
                   7872:     $txt=~tr/A-J/0-9/;
                   7873:     $txt=~tr/a-j/0-9/;
                   7874:     $txt=~tr/K-T/0-9/;
                   7875:     $txt=~tr/k-t/0-9/;
                   7876:     $txt=~tr/U-Z/0-5/;
                   7877:     $txt=~tr/u-z/0-5/;
                   7878:     $txt=~s/\D//g;
1.564     albertel 7879:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7880:     return int($txt);
1.368     albertel 7881: }
                   7882: 
1.484     albertel 7883: sub numval2 {
                   7884:     my $txt=shift;
                   7885:     $txt=~tr/A-J/0-9/;
                   7886:     $txt=~tr/a-j/0-9/;
                   7887:     $txt=~tr/K-T/0-9/;
                   7888:     $txt=~tr/k-t/0-9/;
                   7889:     $txt=~tr/U-Z/0-5/;
                   7890:     $txt=~tr/u-z/0-5/;
                   7891:     $txt=~s/\D//g;
                   7892:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7893:     my $total;
                   7894:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7895:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7896:     return int($total);
                   7897: }
                   7898: 
1.575     albertel 7899: sub numval3 {
                   7900:     use integer;
                   7901:     my $txt=shift;
                   7902:     $txt=~tr/A-J/0-9/;
                   7903:     $txt=~tr/a-j/0-9/;
                   7904:     $txt=~tr/K-T/0-9/;
                   7905:     $txt=~tr/k-t/0-9/;
                   7906:     $txt=~tr/U-Z/0-5/;
                   7907:     $txt=~tr/u-z/0-5/;
                   7908:     $txt=~s/\D//g;
                   7909:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7910:     my $total;
                   7911:     foreach my $val (@txts) { $total+=$val; }
                   7912:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7913:     return $total;
                   7914: }
                   7915: 
1.675     albertel 7916: sub digest {
                   7917:     my ($data)=@_;
                   7918:     my $digest=&Digest::MD5::md5($data);
                   7919:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7920:     my ($e,$f);
                   7921:     {
                   7922:         use integer;
                   7923:         $e=($a+$b);
                   7924:         $f=($c+$d);
                   7925:         if ($_64bit) {
                   7926:             $e=(($e<<32)>>32);
                   7927:             $f=(($f<<32)>>32);
                   7928:         }
                   7929:     }
                   7930:     if (wantarray) {
                   7931: 	return ($e,$f);
                   7932:     } else {
                   7933: 	my $g;
                   7934: 	{
                   7935: 	    use integer;
                   7936: 	    $g=($e+$f);
                   7937: 	    if ($_64bit) {
                   7938: 		$g=(($g<<32)>>32);
                   7939: 	    }
                   7940: 	}
                   7941: 	return $g;
                   7942:     }
                   7943: }
                   7944: 
1.368     albertel 7945: sub latest_rnd_algorithm_id {
1.675     albertel 7946:     return '64bit5';
1.366     albertel 7947: }
1.32      www      7948: 
1.503     albertel 7949: sub get_rand_alg {
                   7950:     my ($courseid)=@_;
1.790     albertel 7951:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7952:     if ($courseid) {
1.620     albertel 7953: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7954:     }
                   7955:     return &latest_rnd_algorithm_id();
                   7956: }
                   7957: 
1.562     albertel 7958: sub validCODE {
                   7959:     my ($CODE)=@_;
                   7960:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7961:     return 0;
                   7962: }
                   7963: 
1.491     albertel 7964: sub getCODE {
1.620     albertel 7965:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7966:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7967: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7968: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7969: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7970:     }
                   7971:     return undef;
                   7972: }
                   7973: 
1.31      www      7974: sub rndseed {
1.155     albertel 7975:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7976:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7977:     if (!defined($symb)) {
1.366     albertel 7978: 	unless ($symb=$wsymb) { return time; }
                   7979:     }
                   7980:     if (!$courseid) { $courseid=$wcourseid; }
                   7981:     if (!$domain) { $domain=$wdomain; }
                   7982:     if (!$username) { $username=$wusername }
1.503     albertel 7983:     my $which=&get_rand_alg();
1.803     albertel 7984: 
1.491     albertel 7985:     if (defined(&getCODE())) {
1.675     albertel 7986: 	if ($which eq '64bit5') {
                   7987: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7988: 	} elsif ($which eq '64bit4') {
1.575     albertel 7989: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7990: 	} else {
                   7991: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7992: 	}
1.675     albertel 7993:     } elsif ($which eq '64bit5') {
                   7994: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7995:     } elsif ($which eq '64bit4') {
                   7996: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7997:     } elsif ($which eq '64bit3') {
                   7998: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7999:     } elsif ($which eq '64bit2') {
                   8000: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8001:     } elsif ($which eq '64bit') {
                   8002: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8003:     }
                   8004:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8005: }
                   8006: 
                   8007: sub rndseed_32bit {
                   8008:     my ($symb,$courseid,$domain,$username)=@_;
                   8009:     {
                   8010: 	use integer;
                   8011: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8012: 	my $symbseed=numval($symb) << 22;
                   8013: 	my $namechck=unpack("%32C*",$username) << 17;
                   8014: 	my $nameseed=numval($username) << 12;
                   8015: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8016: 	my $courseseed=unpack("%32C*",$courseid);
                   8017: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8019: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8020: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8021: 	return $num;
                   8022:     }
                   8023: }
                   8024: 
                   8025: sub rndseed_64bit {
                   8026:     my ($symb,$courseid,$domain,$username)=@_;
                   8027:     {
                   8028: 	use integer;
                   8029: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8030: 	my $symbseed=numval($symb) << 10;
                   8031: 	my $namechck=unpack("%32S*",$username);
                   8032: 	
                   8033: 	my $nameseed=numval($username) << 21;
                   8034: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8035: 	my $courseseed=unpack("%32S*",$courseid);
                   8036: 	
                   8037: 	my $num1=$symbchck+$symbseed+$namechck;
                   8038: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8039: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8040: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8041: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8042: 	return "$num1,$num2";
1.155     albertel 8043:     }
1.366     albertel 8044: }
                   8045: 
1.443     albertel 8046: sub rndseed_64bit2 {
                   8047:     my ($symb,$courseid,$domain,$username)=@_;
                   8048:     {
                   8049: 	use integer;
                   8050: 	# strings need to be an even # of cahracters long, it it is odd the
                   8051:         # last characters gets thrown away
                   8052: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8053: 	my $symbseed=numval($symb) << 10;
                   8054: 	my $namechck=unpack("%32S*",$username.' ');
                   8055: 	
                   8056: 	my $nameseed=numval($username) << 21;
1.501     albertel 8057: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8058: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8059: 	
                   8060: 	my $num1=$symbchck+$symbseed+$namechck;
                   8061: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8062: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8063: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8064: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8065: 	return "$num1,$num2";
                   8066:     }
                   8067: }
                   8068: 
                   8069: sub rndseed_64bit3 {
                   8070:     my ($symb,$courseid,$domain,$username)=@_;
                   8071:     {
                   8072: 	use integer;
                   8073: 	# strings need to be an even # of cahracters long, it it is odd the
                   8074:         # last characters gets thrown away
                   8075: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8076: 	my $symbseed=numval2($symb) << 10;
                   8077: 	my $namechck=unpack("%32S*",$username.' ');
                   8078: 	
                   8079: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8080: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8081: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8082: 	
                   8083: 	my $num1=$symbchck+$symbseed+$namechck;
                   8084: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8085: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8086: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8087: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8088: 	
1.503     albertel 8089: 	return "$num1:$num2";
1.443     albertel 8090:     }
                   8091: }
                   8092: 
1.575     albertel 8093: sub rndseed_64bit4 {
                   8094:     my ($symb,$courseid,$domain,$username)=@_;
                   8095:     {
                   8096: 	use integer;
                   8097: 	# strings need to be an even # of cahracters long, it it is odd the
                   8098:         # last characters gets thrown away
                   8099: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8100: 	my $symbseed=numval3($symb) << 10;
                   8101: 	my $namechck=unpack("%32S*",$username.' ');
                   8102: 	
                   8103: 	my $nameseed=numval3($username) << 21;
                   8104: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8105: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8106: 	
                   8107: 	my $num1=$symbchck+$symbseed+$namechck;
                   8108: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8109: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8110: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8111: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8112: 	
                   8113: 	return "$num1:$num2";
                   8114:     }
                   8115: }
                   8116: 
1.675     albertel 8117: sub rndseed_64bit5 {
                   8118:     my ($symb,$courseid,$domain,$username)=@_;
                   8119:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8120:     return "$num1:$num2";
                   8121: }
                   8122: 
1.366     albertel 8123: sub rndseed_CODE_64bit {
                   8124:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8125:     {
1.366     albertel 8126: 	use integer;
1.443     albertel 8127: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8128: 	my $symbseed=numval2($symb);
1.491     albertel 8129: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8130: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8131: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8132: 	my $num1=$symbseed+$CODEchck;
                   8133: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8134: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8135: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8136: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8137: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8138: 	return "$num1:$num2";
1.366     albertel 8139:     }
                   8140: }
                   8141: 
1.575     albertel 8142: sub rndseed_CODE_64bit4 {
                   8143:     my ($symb,$courseid,$domain,$username)=@_;
                   8144:     {
                   8145: 	use integer;
                   8146: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8147: 	my $symbseed=numval3($symb);
                   8148: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8149: 	my $CODEseed=numval3(&getCODE());
                   8150: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8151: 	my $num1=$symbseed+$CODEchck;
                   8152: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8153: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8154: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8155: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8156: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8157: 	return "$num1:$num2";
                   8158:     }
                   8159: }
                   8160: 
1.675     albertel 8161: sub rndseed_CODE_64bit5 {
                   8162:     my ($symb,$courseid,$domain,$username)=@_;
                   8163:     my $code = &getCODE();
                   8164:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8165:     return "$num1:$num2";
                   8166: }
                   8167: 
1.366     albertel 8168: sub setup_random_from_rndseed {
                   8169:     my ($rndseed)=@_;
1.503     albertel 8170:     if ($rndseed =~/([,:])/) {
                   8171: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8172: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8173:     } else {
                   8174: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8175:     }
1.36      albertel 8176: }
                   8177: 
1.474     albertel 8178: sub latest_receipt_algorithm_id {
1.835     albertel 8179:     return 'receipt3';
1.474     albertel 8180: }
                   8181: 
1.480     www      8182: sub recunique {
                   8183:     my $fucourseid=shift;
                   8184:     my $unique;
1.835     albertel 8185:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8186: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8187: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8188:     } else {
                   8189: 	$unique=$perlvar{'lonReceipt'};
                   8190:     }
                   8191:     return unpack("%32C*",$unique);
                   8192: }
                   8193: 
                   8194: sub recprefix {
                   8195:     my $fucourseid=shift;
                   8196:     my $prefix;
1.835     albertel 8197:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8198: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8199: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8200:     } else {
                   8201: 	$prefix=$perlvar{'lonHostID'};
                   8202:     }
                   8203:     return unpack("%32C*",$prefix);
                   8204: }
                   8205: 
1.76      www      8206: sub ireceipt {
1.474     albertel 8207:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8208: 
                   8209:     my $return =&recprefix($fucourseid).'-';
                   8210: 
                   8211:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8212: 	$env{'request.state'} eq 'construct') {
                   8213: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8214: 	return $return;
                   8215:     }
                   8216: 
1.76      www      8217:     my $cuname=unpack("%32C*",$funame);
                   8218:     my $cudom=unpack("%32C*",$fudom);
                   8219:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8220:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8221:     my $cunique=&recunique($fucourseid);
1.474     albertel 8222:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8223:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8224: 
1.790     albertel 8225: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8226: 			       
                   8227: 	$return.= ($cunique%$cuname+
                   8228: 		   $cunique%$cudom+
                   8229: 		   $cusymb%$cuname+
                   8230: 		   $cusymb%$cudom+
                   8231: 		   $cucourseid%$cuname+
                   8232: 		   $cucourseid%$cudom+
                   8233: 		   $cpart%$cuname+
                   8234: 		   $cpart%$cudom);
                   8235:     } else {
                   8236: 	$return.= ($cunique%$cuname+
                   8237: 		   $cunique%$cudom+
                   8238: 		   $cusymb%$cuname+
                   8239: 		   $cusymb%$cudom+
                   8240: 		   $cucourseid%$cuname+
                   8241: 		   $cucourseid%$cudom);
                   8242:     }
                   8243:     return $return;
1.76      www      8244: }
                   8245: 
                   8246: sub receipt {
1.474     albertel 8247:     my ($part)=@_;
1.790     albertel 8248:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8249:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8250: }
1.260     ng       8251: 
1.790     albertel 8252: sub whichuser {
                   8253:     my ($passedsymb)=@_;
                   8254:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8255:     if (defined($env{'form.grade_symb'})) {
                   8256: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8257: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8258: 	if (!$allowed &&
                   8259: 	    exists($env{'request.course.sec'}) &&
                   8260: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8261: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8262: 			      '/'.$env{'request.course.sec'});
                   8263: 	}
                   8264: 	if ($allowed) {
                   8265: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8266: 	    $courseid=$tmp_courseid;
                   8267: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8268: 	    ($name)=&get_env_multiple('form.grade_username');
                   8269: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8270: 	}
                   8271:     }
                   8272:     if (!$passedsymb) {
                   8273: 	$symb=&symbread();
                   8274:     } else {
                   8275: 	$symb=$passedsymb;
                   8276:     }
                   8277:     $courseid=$env{'request.course.id'};
                   8278:     $domain=$env{'user.domain'};
                   8279:     $name=$env{'user.name'};
                   8280:     if ($name eq 'public' && $domain eq 'public') {
                   8281: 	if (!defined($env{'form.username'})) {
                   8282: 	    $env{'form.username'}.=time.rand(10000000);
                   8283: 	}
                   8284: 	$name.=$env{'form.username'};
                   8285:     }
                   8286:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8287: 
                   8288: }
                   8289: 
1.36      albertel 8290: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8291: # returns either the contents of the file or 
                   8292: # -1 if the file doesn't exist
1.481     raeburn  8293: #
                   8294: # if the target is a file that was uploaded via DOCS, 
                   8295: # a check will be made to see if a current copy exists on the local server,
                   8296: # if it does this will be served, otherwise a copy will be retrieved from
                   8297: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8298: # the local server.   
1.472     albertel 8299: 
1.36      albertel 8300: sub getfile {
1.538     albertel 8301:     my ($file) = @_;
1.609     banghart 8302:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8303:     &repcopy($file);
                   8304:     return &readfile($file);
                   8305: }
                   8306: 
                   8307: sub repcopy_userfile {
                   8308:     my ($file)=@_;
1.609     banghart 8309:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8310:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8311:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8312: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8313:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8314:     if (-e "$file") {
1.828     www      8315: # we already have a local copy, check it out
1.538     albertel 8316: 	my @fileinfo = stat($file);
1.828     www      8317: 	my $rtncode;
                   8318: 	my $info;
1.538     albertel 8319: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8320: 	if ($lwpresp ne 'ok') {
1.828     www      8321: # there is no such file anymore, even though we had a local copy
1.482     albertel 8322: 	    if ($rtncode eq '404') {
1.538     albertel 8323: 		unlink($file);
1.482     albertel 8324: 	    }
                   8325: 	    return -1;
                   8326: 	}
                   8327: 	if ($info < $fileinfo[9]) {
1.828     www      8328: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8329: 	    return 'ok';
1.828     www      8330: 	} else {
                   8331: # the file is outdated, get rid of it
                   8332: 	    unlink($file);
1.482     albertel 8333: 	}
1.828     www      8334:     }
                   8335: # one way or the other, at this point, we don't have the file
                   8336: # construct the correct path for the file
                   8337:     my @parts = ($cdom,$cnum); 
                   8338:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8339: 	push @parts, split(/\//,$1);
                   8340:     }
                   8341:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8342:     foreach my $part (@parts) {
                   8343: 	$path .= '/'.$part;
                   8344: 	if (!-e $path) {
                   8345: 	    mkdir($path,0770);
1.482     albertel 8346: 	}
                   8347:     }
1.828     www      8348: # now the path exists for sure
                   8349: # get a user agent
                   8350:     my $ua=new LWP::UserAgent;
                   8351:     my $transferfile=$file.'.in.transfer';
                   8352: # FIXME: this should flock
                   8353:     if (-e $transferfile) { return 'ok'; }
                   8354:     my $request;
                   8355:     $uri=~s/^\///;
1.980     raeburn  8356:     my $homeserver = &homeserver($cnum,$cdom);
                   8357:     my $protocol = $protocol{$homeserver};
                   8358:     $protocol = 'http' if ($protocol ne 'https');
                   8359:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8360:     my $response=$ua->request($request,$transferfile);
                   8361: # did it work?
                   8362:     if ($response->is_error()) {
                   8363: 	unlink($transferfile);
                   8364: 	&logthis("Userfile repcopy failed for $uri");
                   8365: 	return -1;
                   8366:     }
                   8367: # worked, rename the transfer file
                   8368:     rename($transferfile,$file);
1.607     raeburn  8369:     return 'ok';
1.481     raeburn  8370: }
                   8371: 
1.517     albertel 8372: sub tokenwrapper {
                   8373:     my $uri=shift;
1.980     raeburn  8374:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8375:     $uri=~s|^/||;
1.620     albertel 8376:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8377:     my $token=$1;
1.552     albertel 8378:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8379:     if ($udom && $uname && $file) {
                   8380: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8381:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8382:         my $homeserver = &homeserver($uname,$udom);
                   8383:         my $protocol = $protocol{$homeserver};
                   8384:         $protocol = 'http' if ($protocol ne 'https');
                   8385:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8386:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8387:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8388:     } else {
                   8389:         return '/adm/notfound.html';
                   8390:     }
                   8391: }
                   8392: 
1.828     www      8393: # call with reqtype HEAD: get last modification time
                   8394: # call with reqtype GET: get the file contents
                   8395: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8396: #
1.481     raeburn  8397: sub getuploaded {
                   8398:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8399:     $uri=~s/^\///;
1.980     raeburn  8400:     my $homeserver = &homeserver($cnum,$cdom);
                   8401:     my $protocol = $protocol{$homeserver};
                   8402:     $protocol = 'http' if ($protocol ne 'https');
                   8403:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8404:     my $ua=new LWP::UserAgent;
                   8405:     my $request=new HTTP::Request($reqtype,$uri);
                   8406:     my $response=$ua->request($request);
                   8407:     $$rtncode = $response->code;
1.482     albertel 8408:     if (! $response->is_success()) {
                   8409: 	return 'failed';
                   8410:     }      
                   8411:     if ($reqtype eq 'HEAD') {
1.486     www      8412: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8413:     } elsif ($reqtype eq 'GET') {
                   8414: 	$$info = $response->content;
1.472     albertel 8415:     }
1.482     albertel 8416:     return 'ok';
1.36      albertel 8417: }
                   8418: 
1.481     raeburn  8419: sub readfile {
                   8420:     my $file = shift;
                   8421:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8422:     my $fh;
                   8423:     open($fh,"<$file");
                   8424:     my $a='';
1.800     albertel 8425:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8426:     return $a;
                   8427: }
                   8428: 
1.36      albertel 8429: sub filelocation {
1.590     banghart 8430:     my ($dir,$file) = @_;
                   8431:     my $location;
                   8432:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8433: 
                   8434:     if ($file =~ m-^/adm/-) {
                   8435: 	$file=~s-^/adm/wrapper/-/-;
                   8436: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8437:     }
1.882     albertel 8438: 
1.590     banghart 8439:     if ($file=~m:^/~:) { # is a contruction space reference
                   8440:         $location = $file;
                   8441:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8442:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8443: 	# is a correct contruction space reference
                   8444:         $location = $file;
1.956     raeburn  8445:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8446:         $location = $file;
1.609     banghart 8447:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8448:         my ($udom,$uname,$filename)=
1.811     albertel 8449:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8450:         my $home=&homeserver($uname,$udom);
                   8451:         my $is_me=0;
                   8452:         my @ids=&current_machine_ids();
                   8453:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8454:         if ($is_me) {
1.955     raeburn  8455:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8456:         } else {
                   8457:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8458:   	      $udom.'/'.$uname.'/'.$filename;
                   8459:         }
1.882     albertel 8460:     } elsif ($file =~ m-^/adm/-) {
                   8461: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8462:     } else {
                   8463:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8464:         $file=~s:^/res/:/:;
                   8465:         if ( !( $file =~ m:^/:) ) {
                   8466:             $location = $dir. '/'.$file;
                   8467:         } else {
                   8468:             $location = '/home/httpd/html/res'.$file;
                   8469:         }
1.59      albertel 8470:     }
1.590     banghart 8471:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8472:     while ($location=~m{/\.\./}) {
                   8473: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8474: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8475: 	} else {
                   8476: 	    $location=~ s{/\.\./}{/}g;
                   8477: 	}
                   8478:     } #remove dir/..
1.590     banghart 8479:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8480:     return $location;
1.46      www      8481: }
1.36      albertel 8482: 
1.46      www      8483: sub hreflocation {
                   8484:     my ($dir,$file)=@_;
1.980     raeburn  8485:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8486: 	$file=filelocation($dir,$file);
1.700     albertel 8487:     } elsif ($file=~m-^/adm/-) {
                   8488: 	$file=~s-^/adm/wrapper/-/-;
                   8489: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8490:     }
                   8491:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8492: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8493:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8494: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8495:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8496: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8497: 	    -/uploaded/$1/$2/-x;
1.46      www      8498:     }
1.913     albertel 8499:     if ($file=~ m{^/userfiles/}) {
                   8500: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8501:     }
1.462     albertel 8502:     return $file;
1.465     albertel 8503: }
                   8504: 
                   8505: sub current_machine_domains {
1.853     albertel 8506:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8507: }
                   8508: 
                   8509: sub machine_domains {
                   8510:     my ($hostname) = @_;
1.465     albertel 8511:     my @domains;
1.838     albertel 8512:     my %hostname = &all_hostnames();
1.465     albertel 8513:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8514: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8515: 	if ($hostname eq $name) {
1.844     albertel 8516: 	    push(@domains,&host_domain($id));
1.465     albertel 8517: 	}
                   8518:     }
                   8519:     return @domains;
                   8520: }
                   8521: 
                   8522: sub current_machine_ids {
1.853     albertel 8523:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8524: }
                   8525: 
                   8526: sub machine_ids {
                   8527:     my ($hostname) = @_;
                   8528:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8529:     my @ids;
1.888     albertel 8530:     my %name_to_host = &all_names();
1.889     albertel 8531:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8532: 	return @{ $name_to_host{$hostname} };
                   8533:     }
                   8534:     return;
1.31      www      8535: }
                   8536: 
1.824     raeburn  8537: sub additional_machine_domains {
                   8538:     my @domains;
                   8539:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8540:     while( my $line = <$fh>) {
                   8541:         $line =~ s/\s//g;
                   8542:         push(@domains,$line);
                   8543:     }
                   8544:     return @domains;
                   8545: }
                   8546: 
                   8547: sub default_login_domain {
                   8548:     my $domain = $perlvar{'lonDefDomain'};
                   8549:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8550:     foreach my $posdom (&current_machine_domains(),
                   8551:                         &additional_machine_domains()) {
                   8552:         if (lc($posdom) eq lc($testdomain)) {
                   8553:             $domain=$posdom;
                   8554:             last;
                   8555:         }
                   8556:     }
                   8557:     return $domain;
                   8558: }
                   8559: 
1.31      www      8560: # ------------------------------------------------------------- Declutters URLs
                   8561: 
                   8562: sub declutter {
                   8563:     my $thisfn=shift;
1.569     albertel 8564:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8565:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8566:     $thisfn=~s/^\///;
1.697     albertel 8567:     $thisfn=~s|^adm/wrapper/||;
                   8568:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8569:     $thisfn=~s/^res\///;
1.235     www      8570:     $thisfn=~s/\?.+$//;
1.268     www      8571:     return $thisfn;
                   8572: }
                   8573: 
                   8574: # ------------------------------------------------------------- Clutter up URLs
                   8575: 
                   8576: sub clutter {
                   8577:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8578:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8579: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8580:        $thisfn='/res'.$thisfn; 
                   8581:     }
1.694     albertel 8582:     if ($thisfn !~m|/adm|) {
1.695     albertel 8583: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8584: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8585: 	} else {
                   8586: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8587: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8588: 	    if ($embstyle eq 'ssi'
                   8589: 		|| ($embstyle eq 'hdn')
                   8590: 		|| ($embstyle eq 'rat')
                   8591: 		|| ($embstyle eq 'prv')
                   8592: 		|| ($embstyle eq 'ign')) {
                   8593: 		#do nothing with these
                   8594: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8595: 		|| ($embstyle eq 'emb')
                   8596: 		|| ($embstyle eq 'wrp')) {
                   8597: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8598: 	    } elsif ($embstyle eq 'unk'
                   8599: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8600: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8601: 	    } else {
1.718     www      8602: #		&logthis("Got a blank emb style");
1.695     albertel 8603: 	    }
1.694     albertel 8604: 	}
                   8605:     }
1.31      www      8606:     return $thisfn;
1.12      www      8607: }
                   8608: 
1.787     albertel 8609: sub clutter_with_no_wrapper {
                   8610:     my $uri = &clutter(shift);
                   8611:     if ($uri =~ m-^/adm/-) {
                   8612: 	$uri =~ s-^/adm/wrapper/-/-;
                   8613: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8614:     }
                   8615:     return $uri;
                   8616: }
                   8617: 
1.557     albertel 8618: sub freeze_escape {
                   8619:     my ($value)=@_;
                   8620:     if (ref($value)) {
                   8621: 	$value=&nfreeze($value);
                   8622: 	return '__FROZEN__'.&escape($value);
                   8623:     }
                   8624:     return &escape($value);
                   8625: }
                   8626: 
1.11      www      8627: 
1.557     albertel 8628: sub thaw_unescape {
                   8629:     my ($value)=@_;
                   8630:     if ($value =~ /^__FROZEN__/) {
                   8631: 	substr($value,0,10,undef);
                   8632: 	$value=&unescape($value);
                   8633: 	return &thaw($value);
                   8634:     }
                   8635:     return &unescape($value);
                   8636: }
                   8637: 
1.436     albertel 8638: sub correct_line_ends {
                   8639:     my ($result)=@_;
                   8640:     $$result =~s/\r\n/\n/mg;
                   8641:     $$result =~s/\r/\n/mg;
1.415     albertel 8642: }
1.1       albertel 8643: # ================================================================ Main Program
                   8644: 
1.184     www      8645: sub goodbye {
1.204     albertel 8646:    &logthis("Starting Shut down");
1.443     albertel 8647: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8648:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8649: #converted
1.599     albertel 8650: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8651:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8652: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8653: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8654: #1.1 only
1.870     albertel 8655: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8656: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8657: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8658: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8659:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8660:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8661:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8662:    &flushcourselogs();
                   8663:    &logthis("Shutting down");
                   8664: }
                   8665: 
1.852     albertel 8666: sub get_dns {
1.869     albertel 8667:     my ($url,$func,$ignore_cache) = @_;
                   8668:     if (!$ignore_cache) {
                   8669: 	my ($content,$cached)=
                   8670: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8671: 	if ($cached) {
                   8672: 	    &$func($content);
                   8673: 	    return;
                   8674: 	}
                   8675:     }
                   8676: 
                   8677:     my %alldns;
1.852     albertel 8678:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8679:     foreach my $dns (<$config>) {
                   8680: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8681:         my $line = $1;
                   8682:         my ($host,$protocol) = split(/:/,$line);
                   8683:         if ($protocol ne 'https') {
                   8684:             $protocol = 'http';
                   8685:         }
                   8686: 	$alldns{$host} = $protocol;
1.869     albertel 8687:     }
                   8688:     while (%alldns) {
                   8689: 	my ($dns) = keys(%alldns);
1.852     albertel 8690: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8691: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8692: 	my $response=$ua->request($request);
1.979     raeburn  8693:         delete($alldns{$dns});
1.852     albertel 8694: 	next if ($response->is_error());
                   8695: 	my @content = split("\n",$response->content);
1.869     albertel 8696: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8697: 	&$func(\@content);
1.869     albertel 8698: 	return;
1.852     albertel 8699:     }
                   8700:     close($config);
1.871     albertel 8701:     my $which = (split('/',$url))[3];
                   8702:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8703:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8704:     my @content = <$config>;
                   8705:     &$func(\@content);
                   8706:     return;
1.852     albertel 8707: }
1.327     albertel 8708: # ------------------------------------------------------------ Read domain file
                   8709: {
1.852     albertel 8710:     my $loaded;
1.846     albertel 8711:     my %domain;
                   8712: 
1.852     albertel 8713:     sub parse_domain_tab {
                   8714: 	my ($lines) = @_;
                   8715: 	foreach my $line (@$lines) {
                   8716: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8717: 
1.846     albertel 8718: 	    chomp($line);
1.852     albertel 8719: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8720: 	    my %this_domain;
                   8721: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8722: 			       'lang_def', 'city', 'longi', 'lati',
                   8723: 			       'primary') {
                   8724: 		$this_domain{$field} = shift(@elements);
                   8725: 	    }
                   8726: 	    $domain{$name} = \%this_domain;
1.852     albertel 8727: 	}
                   8728:     }
1.864     albertel 8729: 
                   8730:     sub reset_domain_info {
                   8731: 	undef($loaded);
                   8732: 	undef(%domain);
                   8733:     }
                   8734: 
1.852     albertel 8735:     sub load_domain_tab {
1.869     albertel 8736: 	my ($ignore_cache) = @_;
                   8737: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8738: 	my $fh;
                   8739: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8740: 	    my @lines = <$fh>;
                   8741: 	    &parse_domain_tab(\@lines);
1.448     albertel 8742: 	}
1.852     albertel 8743: 	close($fh);
                   8744: 	$loaded = 1;
1.327     albertel 8745:     }
1.846     albertel 8746: 
                   8747:     sub domain {
1.852     albertel 8748: 	&load_domain_tab() if (!$loaded);
                   8749: 
1.846     albertel 8750: 	my ($name,$what) = @_;
                   8751: 	return if ( !exists($domain{$name}) );
                   8752: 
                   8753: 	if (!$what) {
                   8754: 	    return $domain{$name}{'description'};
                   8755: 	}
                   8756: 	return $domain{$name}{$what};
                   8757:     }
1.974     raeburn  8758: 
                   8759:     sub domain_info {
                   8760:         &load_domain_tab() if (!$loaded);
                   8761:         return %domain;
                   8762:     }
                   8763: 
1.327     albertel 8764: }
                   8765: 
                   8766: 
1.1       albertel 8767: # ------------------------------------------------------------- Read hosts file
                   8768: {
1.838     albertel 8769:     my %hostname;
1.844     albertel 8770:     my %hostdom;
1.845     albertel 8771:     my %libserv;
1.852     albertel 8772:     my $loaded;
1.888     albertel 8773:     my %name_to_host;
1.852     albertel 8774: 
                   8775:     sub parse_hosts_tab {
                   8776: 	my ($file) = @_;
                   8777: 	foreach my $configline (@$file) {
                   8778: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8779: 	    next if ($configline =~ /^\^/);
                   8780: 	    chomp($configline);
1.968     raeburn  8781: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8782: 	    $name=~s/\s//g;
                   8783: 	    if ($id && $domain && $role && $name) {
                   8784: 		$hostname{$id}=$name;
1.888     albertel 8785: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8786: 		$hostdom{$id}=$domain;
                   8787: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8788:                 if (defined($protocol)) {
                   8789:                     if ($protocol eq 'https') {
                   8790:                         $protocol{$id} = $protocol;
                   8791:                     } else {
                   8792:                         $protocol{$id} = 'http'; 
                   8793:                     }
1.968     raeburn  8794:                 } else {
1.969     raeburn  8795:                     $protocol{$id} = 'http';
1.968     raeburn  8796:                 }
1.852     albertel 8797: 	    }
                   8798: 	}
                   8799:     }
1.864     albertel 8800:     
                   8801:     sub reset_hosts_info {
1.897     albertel 8802: 	&purge_remembered();
1.864     albertel 8803: 	&reset_domain_info();
                   8804: 	&reset_hosts_ip_info();
1.892     albertel 8805: 	undef(%name_to_host);
1.864     albertel 8806: 	undef(%hostname);
                   8807: 	undef(%hostdom);
                   8808: 	undef(%libserv);
                   8809: 	undef($loaded);
                   8810:     }
1.1       albertel 8811: 
1.852     albertel 8812:     sub load_hosts_tab {
1.869     albertel 8813: 	my ($ignore_cache) = @_;
                   8814: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8815: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8816: 	my @config = <$config>;
                   8817: 	&parse_hosts_tab(\@config);
                   8818: 	close($config);
                   8819: 	$loaded=1;
1.1       albertel 8820:     }
1.852     albertel 8821: 
1.838     albertel 8822:     sub hostname {
1.852     albertel 8823: 	&load_hosts_tab() if (!$loaded);
                   8824: 
1.838     albertel 8825: 	my ($lonid) = @_;
                   8826: 	return $hostname{$lonid};
                   8827:     }
1.845     albertel 8828: 
1.838     albertel 8829:     sub all_hostnames {
1.852     albertel 8830: 	&load_hosts_tab() if (!$loaded);
                   8831: 
1.838     albertel 8832: 	return %hostname;
                   8833:     }
1.845     albertel 8834: 
1.888     albertel 8835:     sub all_names {
                   8836: 	&load_hosts_tab() if (!$loaded);
                   8837: 
                   8838: 	return %name_to_host;
                   8839:     }
                   8840: 
1.974     raeburn  8841:     sub all_host_domain {
                   8842:         &load_hosts_tab() if (!$loaded);
                   8843:         return %hostdom;
                   8844:     }
                   8845: 
1.845     albertel 8846:     sub is_library {
1.852     albertel 8847: 	&load_hosts_tab() if (!$loaded);
                   8848: 
1.845     albertel 8849: 	return exists($libserv{$_[0]});
                   8850:     }
                   8851: 
                   8852:     sub all_library {
1.852     albertel 8853: 	&load_hosts_tab() if (!$loaded);
                   8854: 
1.845     albertel 8855: 	return %libserv;
                   8856:     }
                   8857: 
1.841     albertel 8858:     sub get_servers {
1.852     albertel 8859: 	&load_hosts_tab() if (!$loaded);
                   8860: 
1.841     albertel 8861: 	my ($domain,$type) = @_;
                   8862: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8863: 	                                          : %hostname;
                   8864: 	my %result;
1.842     albertel 8865: 	if (ref($domain) eq 'ARRAY') {
                   8866: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8867: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8868: 		    $result{$host} = $hostname;
                   8869: 		}
                   8870: 	    }
                   8871: 	} else {
                   8872: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8873: 		if ($hostdom{$host} eq $domain) {
                   8874: 		    $result{$host} = $hostname;
                   8875: 		}
1.841     albertel 8876: 	    }
                   8877: 	}
                   8878: 	return %result;
                   8879:     }
1.845     albertel 8880: 
1.844     albertel 8881:     sub host_domain {
1.852     albertel 8882: 	&load_hosts_tab() if (!$loaded);
                   8883: 
1.844     albertel 8884: 	my ($lonid) = @_;
                   8885: 	return $hostdom{$lonid};
                   8886:     }
                   8887: 
1.841     albertel 8888:     sub all_domains {
1.852     albertel 8889: 	&load_hosts_tab() if (!$loaded);
                   8890: 
1.841     albertel 8891: 	my %seen;
                   8892: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8893: 	return @uniq;
                   8894:     }
1.1       albertel 8895: }
                   8896: 
1.847     albertel 8897: { 
                   8898:     my %iphost;
1.856     albertel 8899:     my %name_to_ip;
                   8900:     my %lonid_to_ip;
1.869     albertel 8901: 
1.847     albertel 8902:     sub get_hosts_from_ip {
                   8903: 	my ($ip) = @_;
                   8904: 	my %iphosts = &get_iphost();
                   8905: 	if (ref($iphosts{$ip})) {
                   8906: 	    return @{$iphosts{$ip}};
                   8907: 	}
                   8908: 	return;
1.839     albertel 8909:     }
1.864     albertel 8910:     
                   8911:     sub reset_hosts_ip_info {
                   8912: 	undef(%iphost);
                   8913: 	undef(%name_to_ip);
                   8914: 	undef(%lonid_to_ip);
                   8915:     }
1.856     albertel 8916: 
                   8917:     sub get_host_ip {
                   8918: 	my ($lonid) = @_;
                   8919: 	if (exists($lonid_to_ip{$lonid})) {
                   8920: 	    return $lonid_to_ip{$lonid};
                   8921: 	}
                   8922: 	my $name=&hostname($lonid);
                   8923:    	my $ip = gethostbyname($name);
                   8924: 	return if (!$ip || length($ip) ne 4);
                   8925: 	$ip=inet_ntoa($ip);
                   8926: 	$name_to_ip{$name}   = $ip;
                   8927: 	$lonid_to_ip{$lonid} = $ip;
                   8928: 	return $ip;
                   8929:     }
1.847     albertel 8930:     
                   8931:     sub get_iphost {
1.869     albertel 8932: 	my ($ignore_cache) = @_;
1.894     albertel 8933: 
1.869     albertel 8934: 	if (!$ignore_cache) {
                   8935: 	    if (%iphost) {
                   8936: 		return %iphost;
                   8937: 	    }
                   8938: 	    my ($ip_info,$cached)=
                   8939: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8940: 	    if ($cached) {
                   8941: 		%iphost      = %{$ip_info->[0]};
                   8942: 		%name_to_ip  = %{$ip_info->[1]};
                   8943: 		%lonid_to_ip = %{$ip_info->[2]};
                   8944: 		return %iphost;
                   8945: 	    }
                   8946: 	}
1.894     albertel 8947: 
                   8948: 	# get yesterday's info for fallback
                   8949: 	my %old_name_to_ip;
                   8950: 	my ($ip_info,$cached)=
                   8951: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8952: 	if ($cached) {
                   8953: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8954: 	}
                   8955: 
1.888     albertel 8956: 	my %name_to_host = &all_names();
                   8957: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8958: 	    my $ip;
                   8959: 	    if (!exists($name_to_ip{$name})) {
                   8960: 		$ip = gethostbyname($name);
                   8961: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8962: 		    if (defined($old_name_to_ip{$name})) {
                   8963: 			$ip = $old_name_to_ip{$name};
                   8964: 			&logthis("Can't find $name defaulting to old $ip");
                   8965: 		    } else {
                   8966: 			&logthis("Name $name no IP found");
                   8967: 			next;
                   8968: 		    }
                   8969: 		} else {
                   8970: 		    $ip=inet_ntoa($ip);
1.847     albertel 8971: 		}
                   8972: 		$name_to_ip{$name} = $ip;
                   8973: 	    } else {
                   8974: 		$ip = $name_to_ip{$name};
1.653     albertel 8975: 	    }
1.888     albertel 8976: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8977: 		$lonid_to_ip{$id} = $ip;
                   8978: 	    }
                   8979: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8980: 	}
1.869     albertel 8981: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8982: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8983: 				      48*60*60);
1.869     albertel 8984: 
1.847     albertel 8985: 	return %iphost;
1.598     albertel 8986:     }
                   8987: }
                   8988: 
1.862     albertel 8989: BEGIN {
                   8990: 
                   8991: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8992:     unless ($readit) {
                   8993: {
                   8994:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8995:     %perlvar = (%perlvar,%{$configvars});
                   8996: }
                   8997: 
                   8998: 
1.1       albertel 8999: # ------------------------------------------------------ Read spare server file
                   9000: {
1.448     albertel 9001:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9002: 
                   9003:     while (my $configline=<$config>) {
                   9004:        chomp($configline);
1.284     matthew  9005:        if ($configline) {
1.784     albertel 9006: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9007: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9008: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9009:        }
                   9010:     }
1.448     albertel 9011:     close($config);
1.1       albertel 9012: }
1.11      www      9013: # ------------------------------------------------------------ Read permissions
                   9014: {
1.448     albertel 9015:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9016: 
                   9017:     while (my $configline=<$config>) {
1.448     albertel 9018: 	chomp($configline);
                   9019: 	if ($configline) {
                   9020: 	    my ($role,$perm)=split(/ /,$configline);
                   9021: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9022: 	}
1.11      www      9023:     }
1.448     albertel 9024:     close($config);
1.11      www      9025: }
                   9026: 
                   9027: # -------------------------------------------- Read plain texts for permissions
                   9028: {
1.448     albertel 9029:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9030: 
                   9031:     while (my $configline=<$config>) {
1.448     albertel 9032: 	chomp($configline);
                   9033: 	if ($configline) {
1.742     raeburn  9034: 	    my ($short,@plain)=split(/:/,$configline);
                   9035:             %{$prp{$short}} = ();
                   9036: 	    if (@plain > 0) {
                   9037:                 $prp{$short}{'std'} = $plain[0];
                   9038:                 for (my $i=1; $i<@plain; $i++) {
                   9039:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9040:                 }
                   9041:             }
1.448     albertel 9042: 	}
1.135     www      9043:     }
1.448     albertel 9044:     close($config);
1.135     www      9045: }
                   9046: 
                   9047: # ---------------------------------------------------------- Read package table
                   9048: {
1.448     albertel 9049:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9050: 
                   9051:     while (my $configline=<$config>) {
1.483     albertel 9052: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9053: 	chomp($configline);
                   9054: 	my ($short,$plain)=split(/:/,$configline);
                   9055: 	my ($pack,$name)=split(/\&/,$short);
                   9056: 	if ($plain ne '') {
                   9057: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9058: 	    $packagetab{$short}=$plain; 
                   9059: 	}
1.11      www      9060:     }
1.448     albertel 9061:     close($config);
1.329     matthew  9062: }
                   9063: 
                   9064: # ------------- set up temporary directory
                   9065: {
                   9066:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9067: 
1.11      www      9068: }
                   9069: 
1.794     albertel 9070: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9071: 				'compress_threshold'=> 20_000,
                   9072:  			        });
1.185     www      9073: 
1.281     www      9074: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9075: $dumpcount=0;
1.958     www      9076: $locknum=0;
1.22      www      9077: 
1.163     harris41 9078: &logtouch();
1.672     albertel 9079: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9080: $readit=1;
1.564     albertel 9081:     {
                   9082: 	use integer;
                   9083: 	my $test=(2**32)+1;
1.568     albertel 9084: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9085: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9086:     }
1.195     www      9087: }
1.1       albertel 9088: }
1.179     www      9089: 
1.1       albertel 9090: 1;
1.191     harris41 9091: __END__
                   9092: 
1.243     albertel 9093: =pod
                   9094: 
1.191     harris41 9095: =head1 NAME
                   9096: 
1.243     albertel 9097: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9098: 
                   9099: =head1 SYNOPSIS
                   9100: 
1.243     albertel 9101: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9102: 
                   9103:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9104: 
1.243     albertel 9105: Common parameters:
                   9106: 
                   9107: =over 4
                   9108: 
                   9109: =item *
                   9110: 
                   9111: $uname : an internal username (if $cname expecting a course Id specifically)
                   9112: 
                   9113: =item *
                   9114: 
                   9115: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9116: 
                   9117: =item *
                   9118: 
                   9119: $symb : a resource instance identifier
                   9120: 
                   9121: =item *
                   9122: 
                   9123: $namespace : the name of a .db file that contains the data needed or
                   9124: being set.
                   9125: 
                   9126: =back
                   9127: 
1.394     bowersj2 9128: =head1 OVERVIEW
1.191     harris41 9129: 
1.394     bowersj2 9130: lonnet provides subroutines which interact with the
                   9131: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9132: about classes, users, and resources.
1.243     albertel 9133: 
                   9134: For many of these objects you can also use this to store data about
                   9135: them or modify them in various ways.
1.191     harris41 9136: 
1.394     bowersj2 9137: =head2 Symbs
1.191     harris41 9138: 
1.394     bowersj2 9139: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9140: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9141: map, the resource number of the resource in the map, and the URL of
                   9142: the resource itself. The latter is somewhat redundant, but might help
                   9143: if maps change.
                   9144: 
                   9145: An example is
                   9146: 
                   9147:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9148: 
                   9149: The respective map entry is
                   9150: 
                   9151:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9152:   title="Problem 2">
                   9153:  </resource>
                   9154: 
                   9155: Symbs are used by the random number generator, as well as to store and
                   9156: restore data specific to a certain instance of for example a problem.
                   9157: 
                   9158: =head2 Storing And Retrieving Data
                   9159: 
                   9160: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9161: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9162: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9163: is is the non-critical message twin of cstore. These functions are for
                   9164: handlers to store a perl hash to a user's permanent data space in an
                   9165: easy manner, and to retrieve it again on another call. It is expected
                   9166: that a handler would use this once at the beginning to retrieve data,
                   9167: and then again once at the end to send only the new data back.
                   9168: 
                   9169: The data is stored in the user's data directory on the user's
                   9170: homeserver under the ID of the course.
                   9171: 
                   9172: The hash that is returned by restore will have all of the previous
                   9173: value for all of the elements of the hash.
                   9174: 
                   9175: Example:
                   9176: 
                   9177:  #creating a hash
                   9178:  my %hash;
                   9179:  $hash{'foo'}='bar';
                   9180: 
                   9181:  #storing it
                   9182:  &Apache::lonnet::cstore(\%hash);
                   9183: 
                   9184:  #changing a value
                   9185:  $hash{'foo'}='notbar';
                   9186: 
                   9187:  #adding a new value
                   9188:  $hash{'bar'}='foo';
                   9189:  &Apache::lonnet::cstore(\%hash);
                   9190: 
                   9191:  #retrieving the hash
                   9192:  my %history=&Apache::lonnet::restore();
                   9193: 
                   9194:  #print the hash
                   9195:  foreach my $key (sort(keys(%history))) {
                   9196:    print("\%history{$key} = $history{$key}");
                   9197:  }
                   9198: 
                   9199: Will print out:
1.191     harris41 9200: 
1.394     bowersj2 9201:  %history{1:foo} = bar
                   9202:  %history{1:keys} = foo:timestamp
                   9203:  %history{1:timestamp} = 990455579
                   9204:  %history{2:bar} = foo
                   9205:  %history{2:foo} = notbar
                   9206:  %history{2:keys} = foo:bar:timestamp
                   9207:  %history{2:timestamp} = 990455580
                   9208:  %history{bar} = foo
                   9209:  %history{foo} = notbar
                   9210:  %history{timestamp} = 990455580
                   9211:  %history{version} = 2
                   9212: 
                   9213: Note that the special hash entries C<keys>, C<version> and
                   9214: C<timestamp> were added to the hash. C<version> will be equal to the
                   9215: total number of versions of the data that have been stored. The
                   9216: C<timestamp> attribute will be the UNIX time the hash was
                   9217: stored. C<keys> is available in every historical section to list which
                   9218: keys were added or changed at a specific historical revision of a
                   9219: hash.
                   9220: 
                   9221: B<Warning>: do not store the hash that restore returns directly. This
                   9222: will cause a mess since it will restore the historical keys as if the
                   9223: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9224: 
1.394     bowersj2 9225: Calling convention:
1.191     harris41 9226: 
1.394     bowersj2 9227:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9228:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9229: 
1.394     bowersj2 9230: For more detailed information, see lonnet specific documentation.
1.191     harris41 9231: 
1.394     bowersj2 9232: =head1 RETURN MESSAGES
1.191     harris41 9233: 
1.394     bowersj2 9234: =over 4
1.191     harris41 9235: 
1.394     bowersj2 9236: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9237: 
1.394     bowersj2 9238: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9239: when the connection is brought back up
1.191     harris41 9240: 
1.394     bowersj2 9241: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9242: for later delivery
1.191     harris41 9243: 
1.967     bisitz   9244: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9245: 
1.394     bowersj2 9246: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9247: that was requested
1.191     harris41 9248: 
1.243     albertel 9249: =back
1.191     harris41 9250: 
1.243     albertel 9251: =head1 PUBLIC SUBROUTINES
1.191     harris41 9252: 
1.243     albertel 9253: =head2 Session Environment Functions
1.191     harris41 9254: 
1.243     albertel 9255: =over 4
1.191     harris41 9256: 
1.394     bowersj2 9257: =item * 
                   9258: X<appenv()>
1.949     raeburn  9259: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9260: the user envirnoment file, and will be restored for each access this
1.620     albertel 9261: user makes during this session, also modifies the %env for the current
1.949     raeburn  9262: process. Optional rolesarrayref - if defined contains a reference to an array
                   9263: of roles which are exempt from the restriction on modifying user.role entries 
                   9264: in the user's environment.db and in %env.    
1.191     harris41 9265: 
                   9266: =item *
1.394     bowersj2 9267: X<delenv()>
                   9268: B<delenv($regexp)>: removes all items from the session
                   9269: environment file that matches the regular expression in $regexp. The
1.620     albertel 9270: values are also delted from the current processes %env.
1.191     harris41 9271: 
1.795     albertel 9272: =item * get_env_multiple($name) 
                   9273: 
                   9274: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9275: values may be defined and end up as an array ref.
                   9276: 
                   9277: returns an array of values
                   9278: 
1.243     albertel 9279: =back
                   9280: 
                   9281: =head2 User Information
1.191     harris41 9282: 
1.243     albertel 9283: =over 4
1.191     harris41 9284: 
                   9285: =item *
1.394     bowersj2 9286: X<queryauthenticate()>
                   9287: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9288: authentication scheme
                   9289: 
                   9290: =item *
1.394     bowersj2 9291: X<authenticate()>
                   9292: B<authenticate($uname,$upass,$udom)>: try to
                   9293: authenticate user from domain's lib servers (first use the current
                   9294: one). C<$upass> should be the users password.
1.191     harris41 9295: 
                   9296: =item *
1.394     bowersj2 9297: X<homeserver()>
                   9298: B<homeserver($uname,$udom)>: find the server which has
                   9299: the user's directory and files (there must be only one), this caches
                   9300: the answer, and also caches if there is a borken connection.
1.191     harris41 9301: 
                   9302: =item *
1.394     bowersj2 9303: X<idget()>
                   9304: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9305: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9306: username, and only 1 username per ID in a specific domain) (returns
                   9307: hash: id=>name,id=>name)
1.191     harris41 9308: 
                   9309: =item *
1.394     bowersj2 9310: X<idrget()>
                   9311: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9312: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9313: 
                   9314: =item *
1.394     bowersj2 9315: X<idput()>
                   9316: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9317: 
                   9318: =item *
1.394     bowersj2 9319: X<rolesinit()>
                   9320: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9321: 
                   9322: =item *
1.551     albertel 9323: X<getsection()>
                   9324: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9325: course $cname, return section name/number or '' for "not in course"
                   9326: and '-1' for "no section"
                   9327: 
                   9328: =item *
1.394     bowersj2 9329: X<userenvironment()>
                   9330: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9331: passed in @what from the requested user's environment, returns a hash
                   9332: 
1.858     raeburn  9333: =item * 
                   9334: X<userlog_query()>
1.859     albertel 9335: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9336: activity.log file. %filters defines filters applied when parsing the
                   9337: log file. These can be start or end timestamps, or the type of action
                   9338: - log to look for Login or Logout events, check for Checkin or
                   9339: Checkout, role for role selection. The response is in the form
                   9340: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9341: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9342: 
1.243     albertel 9343: =back
                   9344: 
                   9345: =head2 User Roles
                   9346: 
                   9347: =over 4
                   9348: 
                   9349: =item *
                   9350: 
1.810     raeburn  9351: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9352:  F: full access
                   9353:  U,I,K: authentication modes (cxx only)
                   9354:  '': forbidden
                   9355:  1: user needs to choose course
                   9356:  2: browse allowed
1.766     albertel 9357:  A: passphrase authentication needed
1.243     albertel 9358: 
                   9359: =item *
                   9360: 
                   9361: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9362: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9363: and course level
                   9364: 
                   9365: =item *
                   9366: 
                   9367: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9368: explanation of a user role term
                   9369: 
1.832     raeburn  9370: =item *
                   9371: 
1.935     raeburn  9372: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9373: All arguments are optional. Returns a hash of a roles, either for
                   9374: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9375: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9376: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9377: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9378: For each key, value is set to colon-separated start and end times for
                   9379: the role.  If no username and domain are specified, will default to
1.934     raeburn  9380: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9381: of role statuses (active, future or previous), roles 
                   9382: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9383: to restrict the list of roles reported. If no array ref is 
                   9384: provided for types, will default to return only active roles.
1.834     albertel 9385: 
1.243     albertel 9386: =back
                   9387: 
                   9388: =head2 User Modification
                   9389: 
                   9390: =over 4
                   9391: 
                   9392: =item *
                   9393: 
1.957     raeburn  9394: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9395: user for the level given by URL.  Optional start and end dates (leave empty
                   9396: string or zero for "no date")
1.191     harris41 9397: 
                   9398: =item *
                   9399: 
1.243     albertel 9400: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9401: change a users, password, possible return values are: ok,
                   9402: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9403: refused
1.191     harris41 9404: 
                   9405: =item *
                   9406: 
1.243     albertel 9407: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9408: 
                   9409: =item *
                   9410: 
1.963     raeburn  9411: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9412:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9413: modify user
1.191     harris41 9414: 
                   9415: =item *
                   9416: 
1.286     matthew  9417: modifystudent
                   9418: 
1.957     raeburn  9419: modify a student's enrollment and identification information.
1.286     matthew  9420: The course id is resolved based on the current users environment.  
                   9421: This means the envoking user must be a course coordinator or otherwise
                   9422: associated with a course.
                   9423: 
1.297     matthew  9424: This call is essentially a wrapper for lonnet::modifyuser and
                   9425: lonnet::modify_student_enrollment
1.286     matthew  9426: 
                   9427: Inputs: 
                   9428: 
                   9429: =over 4
                   9430: 
1.957     raeburn  9431: =item B<$udom> Student's loncapa domain
1.286     matthew  9432: 
1.957     raeburn  9433: =item B<$uname> Student's loncapa login name
1.286     matthew  9434: 
1.964     bisitz   9435: =item B<$uid> Student/Employee ID
1.286     matthew  9436: 
1.957     raeburn  9437: =item B<$umode> Student's authentication mode
1.286     matthew  9438: 
1.957     raeburn  9439: =item B<$upass> Student's password
1.286     matthew  9440: 
1.957     raeburn  9441: =item B<$first> Student's first name
1.286     matthew  9442: 
1.957     raeburn  9443: =item B<$middle> Student's middle name
1.286     matthew  9444: 
1.957     raeburn  9445: =item B<$last> Student's last name
1.286     matthew  9446: 
1.957     raeburn  9447: =item B<$gene> Student's generation
1.286     matthew  9448: 
1.957     raeburn  9449: =item B<$usec> Student's section in course
1.286     matthew  9450: 
                   9451: =item B<$end> Unix time of the roles expiration
                   9452: 
                   9453: =item B<$start> Unix time of the roles start date
                   9454: 
                   9455: =item B<$forceid> If defined, allow $uid to be changed
                   9456: 
                   9457: =item B<$desiredhome> server to use as home server for student
                   9458: 
1.957     raeburn  9459: =item B<$email> Student's permanent e-mail address
                   9460: 
                   9461: =item B<$type> Type of enrollment (auto or manual)
                   9462: 
1.963     raeburn  9463: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9464: 
                   9465: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9466: 
1.963     raeburn  9467: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9468: 
1.963     raeburn  9469: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9470: 
1.963     raeburn  9471: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9472: 
1.286     matthew  9473: =back
1.297     matthew  9474: 
                   9475: =item *
                   9476: 
                   9477: modify_student_enrollment
                   9478: 
                   9479: Change a students enrollment status in a class.  The environment variable
                   9480: 'role.request.course' must be defined for this function to proceed.
                   9481: 
                   9482: Inputs:
                   9483: 
                   9484: =over 4
                   9485: 
                   9486: =item $udom, students domain
                   9487: 
                   9488: =item $uname, students name
                   9489: 
                   9490: =item $uid, students user id
                   9491: 
                   9492: =item $first, students first name
                   9493: 
                   9494: =item $middle
                   9495: 
                   9496: =item $last
                   9497: 
                   9498: =item $gene
                   9499: 
                   9500: =item $usec
                   9501: 
                   9502: =item $end
                   9503: 
                   9504: =item $start
                   9505: 
1.957     raeburn  9506: =item $type
                   9507: 
                   9508: =item $locktype
                   9509: 
                   9510: =item $cid
                   9511: 
                   9512: =item $selfenroll
                   9513: 
                   9514: =item $context
                   9515: 
1.297     matthew  9516: =back
                   9517: 
1.191     harris41 9518: 
                   9519: =item *
                   9520: 
1.243     albertel 9521: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9522: custom role; give a custom role to a user for the level given by URL.  Specify
                   9523: name and domain of role author, and role name
1.191     harris41 9524: 
                   9525: =item *
                   9526: 
1.243     albertel 9527: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9528: 
                   9529: =item *
                   9530: 
1.243     albertel 9531: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9532: 
                   9533: =back
                   9534: 
                   9535: =head2 Course Infomation
                   9536: 
                   9537: =over 4
1.191     harris41 9538: 
                   9539: =item *
                   9540: 
1.631     albertel 9541: coursedescription($courseid) : returns a hash of information about the
                   9542: specified course id, including all environment settings for the
                   9543: course, the description of the course will be in the hash under the
                   9544: key 'description'
1.191     harris41 9545: 
                   9546: =item *
                   9547: 
1.624     albertel 9548: resdata($name,$domain,$type,@which) : request for current parameter
                   9549: setting for a specific $type, where $type is either 'course' or 'user',
                   9550: @what should be a list of parameters to ask about. This routine caches
                   9551: answers for 5 minutes.
1.243     albertel 9552: 
1.877     foxr     9553: =item *
                   9554: 
                   9555: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9556: data base, returning a hash that is keyed by the resource name and has
                   9557: values that are the resource value.  I believe that the timestamps and
                   9558: versions are also returned.
                   9559: 
                   9560: 
1.243     albertel 9561: =back
                   9562: 
                   9563: =head2 Course Modification
                   9564: 
                   9565: =over 4
1.191     harris41 9566: 
                   9567: =item *
                   9568: 
1.243     albertel 9569: writecoursepref($courseid,%prefs) : write preferences (environment
                   9570: database) for a course
1.191     harris41 9571: 
                   9572: =item *
                   9573: 
1.243     albertel 9574: createcourse($udom,$description,$url) : make/modify course
                   9575: 
                   9576: =back
                   9577: 
                   9578: =head2 Resource Subroutines
                   9579: 
                   9580: =over 4
1.191     harris41 9581: 
                   9582: =item *
                   9583: 
1.243     albertel 9584: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9585: 
                   9586: =item *
                   9587: 
1.243     albertel 9588: repcopy($filename) : subscribes to the requested file, and attempts to
                   9589: replicate from the owning library server, Might return
1.607     raeburn  9590: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9591: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9592: resource. Expects the local filesystem pathname
                   9593: (/home/httpd/html/res/....)
                   9594: 
                   9595: =back
                   9596: 
                   9597: =head2 Resource Information
                   9598: 
                   9599: =over 4
1.191     harris41 9600: 
                   9601: =item *
                   9602: 
1.243     albertel 9603: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9604: a vairety of different possible values, $varname should be a request
                   9605: string, and the other parameters can be used to specify who and what
                   9606: one is asking about.
                   9607: 
                   9608: Possible values for $varname are environment.lastname (or other item
                   9609: from the envirnment hash), user.name (or someother aspect about the
                   9610: user), resource.0.maxtries (or some other part and parameter of a
                   9611: resource)
1.204     albertel 9612: 
                   9613: =item *
                   9614: 
1.243     albertel 9615: directcondval($number) : get current value of a condition; reads from a state
                   9616: string
1.204     albertel 9617: 
                   9618: =item *
                   9619: 
1.243     albertel 9620: condval($condidx) : value of condition index based on state
1.204     albertel 9621: 
                   9622: =item *
                   9623: 
1.243     albertel 9624: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9625: resource's metadata, $what should be either a specific key, or either
                   9626: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9627: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9628: 
                   9629: this function automatically caches all requests
1.191     harris41 9630: 
                   9631: =item *
                   9632: 
1.243     albertel 9633: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9634: network of library servers; returns file handle of where SQL and regex results
                   9635: will be stored for query
1.191     harris41 9636: 
                   9637: =item *
                   9638: 
1.243     albertel 9639: symbread($filename) : return symbolic list entry (filename argument optional);
                   9640: returns the data handle
1.191     harris41 9641: 
                   9642: =item *
                   9643: 
1.243     albertel 9644: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9645: a possible symb for the URL in $thisfn, and if is an encryypted
                   9646: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9647: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9648: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9649: 
1.191     harris41 9650: 
                   9651: =item *
                   9652: 
1.243     albertel 9653: symbclean($symb) : removes versions numbers from a symb, returns the
                   9654: cleaned symb
1.191     harris41 9655: 
                   9656: =item *
                   9657: 
1.243     albertel 9658: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9659: course map, user must be in a course for it to work.
1.191     harris41 9660: 
                   9661: =item *
                   9662: 
1.243     albertel 9663: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9664: 
                   9665: =item *
                   9666: 
1.243     albertel 9667: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9668: a random seed, all arguments are optional, if they aren't sent it uses the
                   9669: environment to derive them. Note: if symb isn't sent and it can't get one
                   9670: from &symbread it will use the current time as its return value
1.191     harris41 9671: 
                   9672: =item *
                   9673: 
1.243     albertel 9674: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9675: unfakeable, receipt
1.191     harris41 9676: 
                   9677: =item *
                   9678: 
1.620     albertel 9679: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9680: 
                   9681: =item *
                   9682: 
1.243     albertel 9683: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9684: 
                   9685: =item *
                   9686: 
1.243     albertel 9687: 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 9688: 
                   9689: =item *
                   9690: 
1.243     albertel 9691: 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 9692: 
                   9693: =item *
                   9694: 
1.243     albertel 9695: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9696: 
                   9697: =item *
                   9698: 
1.243     albertel 9699: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9700: forcing spreadsheet to reevaluate the resource scores next time.
                   9701: 
                   9702: =back
                   9703: 
                   9704: =head2 Storing/Retreiving Data
                   9705: 
                   9706: =over 4
1.191     harris41 9707: 
                   9708: =item *
                   9709: 
1.243     albertel 9710: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9711: for this url; hashref needs to be given and should be a \%hashname; the
                   9712: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9713: be derived from the env
1.191     harris41 9714: 
                   9715: =item *
                   9716: 
1.243     albertel 9717: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9718: uses critical subroutine
1.191     harris41 9719: 
                   9720: =item *
                   9721: 
1.243     albertel 9722: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9723: all args are optional
1.191     harris41 9724: 
                   9725: =item *
                   9726: 
1.717     albertel 9727: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9728: dumps the complete (or key matching regexp) namespace into a hash
                   9729: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9730: normally &store()ed into
                   9731: 
                   9732: $range should be either an integer '100' (give me the first 100
                   9733:                                            matching records)
                   9734:               or be  two integers sperated by a - with no spaces
                   9735:                  '30-50' (give me the 30th through the 50th matching
                   9736:                           records)
                   9737: 
                   9738: 
                   9739: =item *
                   9740: 
                   9741: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9742: replaces a &store() version of data with a replacement set of data
                   9743: for a particular resource in a namespace passed in the $storehash hash 
                   9744: reference
                   9745: 
                   9746: =item *
                   9747: 
1.243     albertel 9748: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9749: works very similar to store/cstore, but all data is stored in a
                   9750: temporary location and can be reset using tmpreset, $storehash should
                   9751: be a hash reference, returns nothing on success
1.191     harris41 9752: 
                   9753: =item *
                   9754: 
1.243     albertel 9755: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9756: similar to restore, but all data is stored in a temporary location and
                   9757: can be reset using tmpreset. Returns a hash of values on success,
                   9758: error string otherwise.
1.191     harris41 9759: 
                   9760: =item *
                   9761: 
1.243     albertel 9762: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9763: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9764: 
                   9765: =item *
                   9766: 
1.243     albertel 9767: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9768: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9769: 
                   9770: =item *
                   9771: 
1.243     albertel 9772: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9773: namesp ($udom and $uname are optional)
1.191     harris41 9774: 
                   9775: =item *
                   9776: 
1.702     albertel 9777: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9778: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9779: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9780: 
1.702     albertel 9781: $range should be either an integer '100' (give me the first 100
                   9782:                                            matching records)
                   9783:               or be  two integers sperated by a - with no spaces
                   9784:                  '30-50' (give me the 30th through the 50th matching
                   9785:                           records)
1.449     matthew  9786: =item *
                   9787: 
                   9788: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9789: $store can be a scalar, an array reference, or if the amount to be 
                   9790: incremented is > 1, a hash reference.
                   9791: 
                   9792: ($udom and $uname are optional)
1.191     harris41 9793: 
                   9794: =item *
                   9795: 
1.243     albertel 9796: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9797: ($udom and $uname are optional)
1.191     harris41 9798: 
                   9799: =item *
                   9800: 
1.243     albertel 9801: cput($namespace,$storehash,$udom,$uname) : critical put
                   9802: ($udom and $uname are optional)
1.191     harris41 9803: 
                   9804: =item *
                   9805: 
1.748     albertel 9806: newput($namespace,$storehash,$udom,$uname) :
                   9807: 
                   9808: Attempts to store the items in the $storehash, but only if they don't
                   9809: currently exist, if this succeeds you can be certain that you have 
                   9810: successfully created a new key value pair in the $namespace db.
                   9811: 
                   9812: 
                   9813: Args:
                   9814:  $namespace: name of database to store values to
                   9815:  $storehash: hashref to store to the db
                   9816:  $udom: (optional) domain of user containing the db
                   9817:  $uname: (optional) name of user caontaining the db
                   9818: 
                   9819: Returns:
                   9820:  'ok' -> succeeded in storing all keys of $storehash
                   9821:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9822:                         least <key> already existed in the db (other
                   9823:                         requested keys may also already exist)
1.967     bisitz   9824:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9825:  'con_lost' -> unable to contact request server
                   9826:  'refused' -> action was not allowed by remote machine
                   9827: 
                   9828: 
                   9829: =item *
                   9830: 
1.243     albertel 9831: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9832: reference filled in from namesp (encrypts the return communication)
                   9833: ($udom and $uname are optional)
1.191     harris41 9834: 
                   9835: =item *
                   9836: 
1.243     albertel 9837: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9838: critical subroutine
                   9839: 
1.806     raeburn  9840: =item *
                   9841: 
1.860     raeburn  9842: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9843: array reference filled in from namespace found in domain level on either
                   9844: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9845: 
                   9846: =item *
                   9847: 
1.860     raeburn  9848: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9849: domain level either on specified domain server ($uhome) or primary domain 
                   9850: server ($udom and $uhome are optional)
1.806     raeburn  9851: 
1.943     raeburn  9852: =item * 
                   9853: 
                   9854: get_domain_defaults($target_domain) : returns hash with defaults for
                   9855: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9856: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9857: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9858: Values are retrieved from cache (if current), or from domain's configuration.db
                   9859: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9860: or lonTabs/domain.tab. 
                   9861: 
                   9862: %domdefaults = &get_auth_defaults($target_domain);
                   9863: 
1.243     albertel 9864: =back
                   9865: 
                   9866: =head2 Network Status Functions
                   9867: 
                   9868: =over 4
1.191     harris41 9869: 
                   9870: =item *
                   9871: 
                   9872: dirlist($uri) : return directory list based on URI
                   9873: 
                   9874: =item *
                   9875: 
1.243     albertel 9876: spareserver() : find server with least workload from spare.tab
                   9877: 
                   9878: =back
                   9879: 
                   9880: =head2 Apache Request
                   9881: 
                   9882: =over 4
1.191     harris41 9883: 
                   9884: =item *
                   9885: 
1.243     albertel 9886: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9887: localhost, posts hash
                   9888: 
                   9889: =back
                   9890: 
                   9891: =head2 Data to String to Data
                   9892: 
                   9893: =over 4
1.191     harris41 9894: 
                   9895: =item *
                   9896: 
1.243     albertel 9897: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9898: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9899: 
                   9900: =item *
                   9901: 
1.243     albertel 9902: hashref2str($hashref) : convert a hashref into a string complete with
                   9903: escaping and '=' and '&' separators, supports elements that are
                   9904: arrayrefs and hashrefs
1.191     harris41 9905: 
                   9906: =item *
                   9907: 
1.243     albertel 9908: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9909: with escaping and '&' separators, supports elements that are arrayrefs
                   9910: and hashrefs
1.191     harris41 9911: 
                   9912: =item *
                   9913: 
1.243     albertel 9914: str2hash($string) : convert string to hash using unescaping and
                   9915: splitting on '=' and '&', supports elements that are arrayrefs and
                   9916: hashrefs
1.191     harris41 9917: 
                   9918: =item *
                   9919: 
1.243     albertel 9920: str2array($string) : convert string to hash using unescaping and
                   9921: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9922: 
                   9923: =back
                   9924: 
                   9925: =head2 Logging Routines
                   9926: 
                   9927: =over 4
                   9928: 
                   9929: These routines allow one to make log messages in the lonnet.log and
                   9930: lonnet.perm logfiles.
1.191     harris41 9931: 
                   9932: =item *
                   9933: 
1.243     albertel 9934: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9935: 
                   9936: =item *
                   9937: 
1.243     albertel 9938: logthis() : append message to the normal lonnet.log file, it gets
                   9939: preiodically rolled over and deleted.
1.191     harris41 9940: 
                   9941: =item *
                   9942: 
1.243     albertel 9943: logperm() : append a permanent message to lonnet.perm.log, this log
                   9944: file never gets deleted by any automated portion of the system, only
                   9945: messages of critical importance should go in here.
                   9946: 
                   9947: =back
                   9948: 
                   9949: =head2 General File Helper Routines
                   9950: 
                   9951: =over 4
1.191     harris41 9952: 
                   9953: =item *
                   9954: 
1.481     raeburn  9955: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9956: (a) files in /uploaded
                   9957:   (i) If a local copy of the file exists - 
                   9958:       compares modification date of local copy with last-modified date for 
                   9959:       definitive version stored on home server for course. If local copy is 
                   9960:       stale, requests a new version from the home server and stores it. 
                   9961:       If the original has been removed from the home server, then local copy 
                   9962:       is unlinked.
                   9963:   (ii) If local copy does not exist -
                   9964:       requests the file from the home server and stores it. 
                   9965:   
                   9966:   If $caller is 'uploadrep':  
                   9967:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9968:     for request for files originally uploaded via DOCS. 
                   9969:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9970:   
                   9971:   Otherwise:
                   9972:      This indicates a call from the content generation phase of the request.
                   9973:      -  returns the entire contents of the file or -1.
                   9974:      
                   9975: (b) files in /res
                   9976:    - returns the entire contents of a file or -1; 
                   9977:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9978: 
1.712     albertel 9979: 
                   9980: =item *
                   9981: 
                   9982: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9983:                   reference
                   9984: 
                   9985: returns either a stat() list of data about the file or an empty list
                   9986: if the file doesn't exist or couldn't find out about it (connection
                   9987: problems or user unknown)
                   9988: 
1.191     harris41 9989: =item *
                   9990: 
1.243     albertel 9991: filelocation($dir,$file) : returns file system location of a file
                   9992: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9993: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9994: and a file of ../bob will become /a/bob)
1.191     harris41 9995: 
                   9996: =item *
                   9997: 
                   9998: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9999: filelocation except for hrefs
                   10000: 
                   10001: =item *
                   10002: 
                   10003: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10004: 
1.243     albertel 10005: =back
                   10006: 
1.608     albertel 10007: =head2 Usererfile file routines (/uploaded*)
                   10008: 
                   10009: =over 4
                   10010: 
                   10011: =item *
                   10012: 
                   10013: userfileupload(): main rotine for putting a file in a user or course's
                   10014:                   filespace, arguments are,
                   10015: 
1.620     albertel 10016:  formname - required - this is the name of the element in $env where the
1.608     albertel 10017:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10018:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10019:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10020:  coursedoc - if true, store the file in the course of the active role
                   10021:              of the current user
                   10022:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10023:          if undefined, it will be placed in "unknown"
                   10024: 
                   10025:  (This routine calls clean_filename() to remove any dangerous
                   10026:  characters from the filename, and then calls finuserfileupload() to
                   10027:  complete the transaction)
                   10028: 
                   10029:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10030:  and /adm/notfound.html if unsuccessful
                   10031: 
                   10032: =item *
                   10033: 
                   10034: clean_filename(): routine for cleaing a filename up for storage in
                   10035:                  userfile space, argument is:
                   10036: 
                   10037:  filename - proposed filename
                   10038: 
                   10039: returns: the new clean filename
                   10040: 
                   10041: =item *
                   10042: 
                   10043: finishuserfileupload(): routine that creaes and sends the file to
                   10044: userspace, probably shouldn't be called directly
                   10045: 
                   10046:   docuname: username or courseid of destination for the file
                   10047:   docudom: domain of user/course of destination for the file
                   10048:   formname: same as for userfileupload()
                   10049:   fname: filename (inculding subdirectories) for the file
                   10050: 
                   10051:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10052:  and /adm/notfound.html if unsuccessful
                   10053: 
                   10054: =item *
                   10055: 
                   10056: renameuserfile(): renames an existing userfile to a new name
                   10057: 
                   10058:   Args:
                   10059:    docuname: username or courseid of destination for the file
                   10060:    docudom: domain of user/course of destination for the file
                   10061:    old: current file name (including any subdirs under userfiles)
                   10062:    new: desired file name (including any subdirs under userfiles)
                   10063: 
                   10064: =item *
                   10065: 
                   10066: mkdiruserfile(): creates a directory is a userfiles dir
                   10067: 
                   10068:   Args:
                   10069:    docuname: username or courseid of destination for the file
                   10070:    docudom: domain of user/course of destination for the file
                   10071:    dir: dir to create (including any subdirs under userfiles)
                   10072: 
                   10073: =item *
                   10074: 
                   10075: removeuserfile(): removes a file that exists in userfiles
                   10076: 
                   10077:   Args:
                   10078:    docuname: username or courseid of destination for the file
                   10079:    docudom: domain of user/course of destination for the file
                   10080:    fname: filname to delete (including any subdirs under userfiles)
                   10081: 
                   10082: =item *
                   10083: 
                   10084: removeuploadedurl(): convience function for removeuserfile()
                   10085: 
                   10086:   Args:
                   10087:    url:  a full /uploaded/... url to delete
                   10088: 
1.747     albertel 10089: =item * 
                   10090: 
                   10091: get_portfile_permissions():
                   10092:   Args:
                   10093:     domain: domain of user or course contain the portfolio files
                   10094:     user: name of user or num of course contain the portfolio files
                   10095:   Returns:
                   10096:     hashref of a dump of the proper file_permissions.db
                   10097:    
                   10098: 
                   10099: =item * 
                   10100: 
                   10101: get_access_controls():
                   10102: 
                   10103: Args:
                   10104:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10105:   group: (optional) the group you want the files associated with
                   10106:   file: (optional) the file you want access info on
                   10107: 
                   10108: Returns:
1.749     raeburn  10109:     a hash (keys are file names) of hashes containing
                   10110:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10111:         values are XML containing access control settings (see below) 
1.747     albertel 10112: 
                   10113: Internal notes:
                   10114: 
1.749     raeburn  10115:  access controls are stored in file_permissions.db as key=value pairs.
                   10116:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10117:         where scope -> public,guest,course,group,domains or users.
                   10118:               end -> UNIX time for end of access (0 -> no end date)
                   10119:               start -> UNIX time for start of access
                   10120: 
                   10121:     value -> XML description of access control
                   10122:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10123:             <start></start>
                   10124:             <end></end>
                   10125: 
                   10126:             <password></password>  for scope type = guest
                   10127: 
                   10128:             <domain></domain>     for scope type = course or group
                   10129:             <number></number>
                   10130:             <roles id="">
                   10131:              <role></role>
                   10132:              <access></access>
                   10133:              <section></section>
                   10134:              <group></group>
                   10135:             </roles>
                   10136: 
                   10137:             <dom></dom>         for scope type = domains
                   10138: 
                   10139:             <users>             for scope type = users
                   10140:              <user>
                   10141:               <uname></uname>
                   10142:               <udom></udom>
                   10143:              </user>
                   10144:             </users>
                   10145:            </scope> 
                   10146:               
                   10147:  Access data is also aggregated for each file in an additional key=value pair:
                   10148:  key -> path to file/file_name\0accesscontrol 
                   10149:  value -> reference to hash
                   10150:           hash contains key = value pairs
                   10151:           where key = uniqueID:scope_end_start
                   10152:                 value = UNIX time record was last updated
                   10153: 
                   10154:           Used to improve speed of look-ups of access controls for each file.  
                   10155:  
                   10156:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10157: 
                   10158: modify_access_controls():
                   10159: 
                   10160: Modifies access controls for a portfolio file
                   10161: Args
                   10162: 1. file name
                   10163: 2. reference to hash of required changes,
                   10164: 3. domain
                   10165: 4. username
                   10166:   where domain,username are the domain of the portfolio owner 
                   10167:   (either a user or a course) 
                   10168: 
                   10169: Returns:
                   10170: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10171: 2. result of deletions ('ok' or 'error', with error message).
                   10172: 3. reference to hash of any new or updated access controls.
                   10173: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10174:    key = integer (inbound ID)
                   10175:    value = uniqueID  
1.747     albertel 10176: 
1.608     albertel 10177: =back
                   10178: 
1.243     albertel 10179: =head2 HTTP Helper Routines
                   10180: 
                   10181: =over 4
                   10182: 
1.191     harris41 10183: =item *
                   10184: 
                   10185: escape() : unpack non-word characters into CGI-compatible hex codes
                   10186: 
                   10187: =item *
                   10188: 
                   10189: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10190: 
1.243     albertel 10191: =back
                   10192: 
                   10193: =head1 PRIVATE SUBROUTINES
                   10194: 
                   10195: =head2 Underlying communication routines (Shouldn't call)
                   10196: 
                   10197: =over 4
                   10198: 
                   10199: =item *
                   10200: 
                   10201: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10202: 
                   10203: =item *
                   10204: 
                   10205: reply() : uses subreply to send a message to remote machine, logs all failures
                   10206: 
                   10207: =item *
                   10208: 
                   10209: critical() : passes a critical message to another server; if cannot
                   10210: get through then place message in connection buffer directory and
                   10211: returns con_delayed, if incapable of saving message, returns
                   10212: con_failed
                   10213: 
                   10214: =item *
                   10215: 
                   10216: reconlonc() : tries to reconnect lonc client processes.
                   10217: 
                   10218: =back
                   10219: 
                   10220: =head2 Resource Access Logging
                   10221: 
                   10222: =over 4
                   10223: 
                   10224: =item *
                   10225: 
                   10226: flushcourselogs() : flush (save) buffer logs and access logs
                   10227: 
                   10228: =item *
                   10229: 
                   10230: courselog($what) : save message for course in hash
                   10231: 
                   10232: =item *
                   10233: 
                   10234: courseacclog($what) : save message for course using &courselog().  Perform
                   10235: special processing for specific resource types (problems, exams, quizzes, etc).
                   10236: 
1.191     harris41 10237: =item *
                   10238: 
                   10239: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10240: as a PerlChildExitHandler
1.243     albertel 10241: 
                   10242: =back
                   10243: 
                   10244: =head2 Other
                   10245: 
                   10246: =over 4
                   10247: 
                   10248: =item *
                   10249: 
                   10250: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10251: 
                   10252: =back
                   10253: 
                   10254: =cut
1.877     foxr     10255: 

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