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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.991   ! raeburn     4: # $Id: lonnet.pm,v 1.990 2009/03/09 05:25:44 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.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    79:             $_64bit %env %protocol);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.807     albertel   95: use LONCAPA qw(:DEFAULT :match);
1.740     www        96: use LONCAPA::Configuration;
1.676     albertel   97: 
1.195     www        98: my $readit;
1.550     foxr       99: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  100: 
1.977     amueller  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  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 {
1.987     raeburn   529:     my ($delthis,$regexp) = @_;
1.56      www       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.987     raeburn   542: 	    if ($regexp) {
                    543:                 if ($key=~/^$delthis/) {
                    544:                     delete($env{$key});
                    545:                     delete($disk_env{$key});
                    546:                 } 
                    547:             } else {
                    548:                 if ($key=~/^\Q$delthis\E/) {
                    549: 		    delete($env{$key});
                    550: 		    delete($disk_env{$key});
                    551: 	        }
                    552:             }
1.448     albertel  553: 	}
1.783     albertel  554: 	untie(%disk_env);
1.5       www       555:     }
                    556:     return 'ok';
1.369     albertel  557: }
                    558: 
1.790     albertel  559: sub get_env_multiple {
                    560:     my ($name) = @_;
                    561:     my @values;
                    562:     if (defined($env{$name})) {
                    563:         # exists is it an array
                    564:         if (ref($env{$name})) {
                    565:             @values=@{ $env{$name} };
                    566:         } else {
                    567:             $values[0]=$env{$name};
                    568:         }
                    569:     }
                    570:     return(@values);
                    571: }
                    572: 
1.958     www       573: # ------------------------------------------------------------------- Locking
                    574: 
                    575: sub set_lock {
                    576:     my ($text)=@_;
                    577:     $locknum++;
                    578:     my $id=$$.'-'.$locknum;
                    579:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    580:              'session.lock.'.$id => $text});
                    581:     return $id;
                    582: }
                    583: 
                    584: sub get_locks {
                    585:     my $num=0;
                    586:     my %texts=();
                    587:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    588:        if ($lock=~/\w/) {
                    589:           $num++;
                    590:           $texts{$lock}=$env{'session.lock.'.$lock};
                    591:        }
                    592:    }
                    593:    return ($num,%texts);
                    594: }
                    595: 
                    596: sub remove_lock {
                    597:     my ($id)=@_;
                    598:     my $newlocks='';
                    599:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    600:        if (($lock=~/\w/) && ($lock ne $id)) {
                    601:           $newlocks.=','.$lock;
                    602:        }
                    603:     }
                    604:     &appenv({'session.locks' => $newlocks});
                    605:     &delenv('session.lock.'.$id);
                    606: }
                    607: 
                    608: sub remove_all_locks {
                    609:     my $activelocks=$env{'session.locks'};
                    610:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    611:        if ($lock=~/\w/) {
                    612:           &remove_lock($lock);
                    613:        }
                    614:     }
                    615: }
                    616: 
                    617: 
1.369     albertel  618: # ------------------------------------------ Find out current server userload
                    619: sub userload {
                    620:     my $numusers=0;
                    621:     {
                    622: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    623: 	my $filename;
                    624: 	my $curtime=time;
                    625: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  626: 	    next if ($filename eq '.' || $filename eq '..');
                    627: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  628: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  629: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  630: 	}
                    631: 	closedir(LONIDS);
                    632:     }
                    633:     my $userloadpercent=0;
                    634:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    635:     if ($maxuserload) {
1.371     albertel  636: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  637:     }
1.372     albertel  638:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  639:     return $userloadpercent;
1.283     www       640: }
                    641: 
                    642: # ------------------------------------------ Fight off request when overloaded
                    643: 
                    644: sub overloaderror {
                    645:     my ($r,$checkserver)=@_;
                    646:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    647:     my $loadavg;
                    648:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  649:        open(my $loadfile,'/proc/loadavg');
1.283     www       650:        $loadavg=<$loadfile>;
                    651:        $loadavg =~ s/\s.*//g;
1.285     matthew   652:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  653:        close($loadfile);
1.283     www       654:     } else {
                    655:        $loadavg=&reply('load',$checkserver);
                    656:     }
1.285     matthew   657:     my $overload=$loadavg-100;
1.283     www       658:     if ($overload>0) {
1.285     matthew   659: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       660:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       661:         return 413;
1.283     www       662:     }    
                    663:     return '';
1.5       www       664: }
1.1       albertel  665: 
                    666: # ------------------------------ Find server with least workload from spare.tab
1.11      www       667: 
1.1       albertel  668: sub spareserver {
1.670     albertel  669:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  670:     my $spare_server;
1.370     albertel  671:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  672:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    673:                                                      :  $userloadpercent;
                    674:     
                    675:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    676: 	($spare_server, $lowest_load) =
                    677: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    678:     }
                    679: 
                    680:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    681: 
                    682:     if (!$found_server) {
                    683: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    684: 	    ($spare_server, $lowest_load) =
                    685: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    686: 	}
                    687:     }
                    688: 
                    689:     if (!$want_server_name) {
1.968     raeburn   690:         my $protocol = 'http';
                    691:         if ($protocol{$spare_server} eq 'https') {
                    692:             $protocol = $protocol{$spare_server};
                    693:         }
                    694: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  695:     }
                    696:     return $spare_server;
                    697: }
                    698: 
                    699: sub compare_server_load {
                    700:     my ($try_server, $spare_server, $lowest_load) = @_;
                    701: 
                    702:     my $loadans     = &reply('load',    $try_server);
                    703:     my $userloadans = &reply('userload',$try_server);
                    704: 
                    705:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    706: 	next; #didn't get a number from the server
                    707:     }
                    708: 
                    709:     my $load;
                    710:     if ($loadans =~ /\d/) {
                    711: 	if ($userloadans =~ /\d/) {
                    712: 	    #both are numbers, pick the bigger one
                    713: 	    $load = ($loadans > $userloadans) ? $loadans 
                    714: 		                              : $userloadans;
1.411     albertel  715: 	} else {
1.784     albertel  716: 	    $load = $loadans;
1.411     albertel  717: 	}
1.784     albertel  718:     } else {
                    719: 	$load = $userloadans;
                    720:     }
                    721: 
                    722:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    723: 	$spare_server = $try_server;
                    724: 	$lowest_load  = $load;
1.370     albertel  725:     }
1.784     albertel  726:     return ($spare_server,$lowest_load);
1.202     matthew   727: }
1.914     albertel  728: 
                    729: # --------------------------- ask offload servers if user already has a session
                    730: sub find_existing_session {
                    731:     my ($udom,$uname) = @_;
                    732:     foreach my $try_server (@{ $spareid{'primary'} },
                    733: 			    @{ $spareid{'default'} }) {
                    734: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    735:     }
                    736:     return;
                    737: }
                    738: 
                    739: # -------------------------------- ask if server already has a session for user
                    740: sub has_user_session {
                    741:     my ($lonid,$udom,$uname) = @_;
                    742:     my $result = &reply(join(':','userhassession',
                    743: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    744:     return 1 if ($result eq 'ok');
                    745: 
                    746:     return 0;
                    747: }
                    748: 
1.202     matthew   749: # --------------------------------------------- Try to change a user's password
                    750: 
                    751: sub changepass {
1.799     raeburn   752:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   753:     $currentpass = &escape($currentpass);
                    754:     $newpass     = &escape($newpass);
1.799     raeburn   755:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   756: 		       $server);
                    757:     if (! $answer) {
                    758: 	&logthis("No reply on password change request to $server ".
                    759: 		 "by $uname in domain $udom.");
                    760:     } elsif ($answer =~ "^ok") {
                    761:         &logthis("$uname in $udom successfully changed their password ".
                    762: 		 "on $server.");
                    763:     } elsif ($answer =~ "^pwchange_failure") {
                    764: 	&logthis("$uname in $udom was unable to change their password ".
                    765: 		 "on $server.  The action was blocked by either lcpasswd ".
                    766: 		 "or pwchange");
                    767:     } elsif ($answer =~ "^non_authorized") {
                    768:         &logthis("$uname in $udom did not get their password correct when ".
                    769: 		 "attempting to change it on $server.");
                    770:     } elsif ($answer =~ "^auth_mode_error") {
                    771:         &logthis("$uname in $udom attempted to change their password despite ".
                    772: 		 "not being locally or internally authenticated on $server.");
                    773:     } elsif ($answer =~ "^unknown_user") {
                    774:         &logthis("$uname in $udom attempted to change their password ".
                    775: 		 "on $server but were unable to because $server is not ".
                    776: 		 "their home server.");
                    777:     } elsif ($answer =~ "^refused") {
                    778: 	&logthis("$server refused to change $uname in $udom password because ".
                    779: 		 "it was sent an unencrypted request to change the password.");
                    780:     }
                    781:     return $answer;
1.1       albertel  782: }
                    783: 
1.169     harris41  784: # ----------------------- Try to determine user's current authentication scheme
                    785: 
                    786: sub queryauthenticate {
                    787:     my ($uname,$udom)=@_;
1.456     albertel  788:     my $uhome=&homeserver($uname,$udom);
                    789:     if (!$uhome) {
                    790: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    791: 	return 'no_host';
                    792:     }
                    793:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    794:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    795: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  796:     }
1.456     albertel  797:     return $answer;
1.169     harris41  798: }
                    799: 
1.1       albertel  800: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       801: 
1.1       albertel  802: sub authenticate {
1.952     raeburn   803:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  804:     $upass=&escape($upass);
                    805:     $uname= &LONCAPA::clean_username($uname);
1.836     www       806:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   807:     my $newhome;
1.836     www       808:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    809: # Maybe the machine was offline and only re-appeared again recently?
                    810:         &reconlonc();
                    811: # One more
1.952     raeburn   812: 	$uhome=&homeserver($uname,$udom,1);
                    813:         if (($uhome eq 'no_host') && $checkdefauth) {
                    814:             if (defined(&domain($udom,'primary'))) {
                    815:                 $newhome=&domain($udom,'primary');
                    816:             }
                    817:             if ($newhome ne '') {
                    818:                 $uhome = $newhome;
                    819:             }
                    820:         }
1.836     www       821: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    822: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   823: 	    return 'no_host';
                    824:         }
1.1       albertel  825:     }
1.952     raeburn   826:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  827:     if ($answer eq 'authorized') {
1.952     raeburn   828:         if ($newhome) {
                    829:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    830:             return 'no_account_on_host'; 
                    831:         } else {
                    832:             &logthis("User $uname at $udom authorized by $uhome");
                    833:             return $uhome;
                    834:         }
1.471     albertel  835:     }
                    836:     if ($answer eq 'non_authorized') {
                    837: 	&logthis("User $uname at $udom rejected by $uhome");
                    838: 	return 'no_host'; 
1.9       www       839:     }
1.471     albertel  840:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  841:     return 'no_host';
                    842: }
                    843: 
                    844: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       845: 
1.599     albertel  846: my %homecache;
1.1       albertel  847: sub homeserver {
1.230     stredwic  848:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  849:     my $index="$uname:$udom";
1.426     albertel  850: 
1.599     albertel  851:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  852: 
                    853:     my %servers = &get_servers($udom,'library');
                    854:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  855:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  856: 		 exists($badServerCache{$tryserver}));
1.841     albertel  857: 
                    858: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    859: 	if ($answer eq 'found') {
                    860: 	    delete($badServerCache{$tryserver}); 
                    861: 	    return $homecache{$index}=$tryserver;
                    862: 	} elsif ($answer eq 'no_host') {
                    863: 	    $badServerCache{$tryserver}=1;
                    864: 	}
1.1       albertel  865:     }    
                    866:     return 'no_host';
1.70      www       867: }
                    868: 
                    869: # ------------------------------------- Find the usernames behind a list of IDs
                    870: 
                    871: sub idget {
                    872:     my ($udom,@ids)=@_;
                    873:     my %returnhash=();
                    874:     
1.841     albertel  875:     my %servers = &get_servers($udom,'library');
                    876:     foreach my $tryserver (keys(%servers)) {
                    877: 	my $idlist=join('&',@ids);
                    878: 	$idlist=~tr/A-Z/a-z/; 
                    879: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    880: 	my @answer=();
                    881: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    882: 	    @answer=split(/\&/,$reply);
                    883: 	}                    ;
                    884: 	my $i;
                    885: 	for ($i=0;$i<=$#ids;$i++) {
                    886: 	    if ($answer[$i]) {
                    887: 		$returnhash{$ids[$i]}=$answer[$i];
                    888: 	    } 
                    889: 	}
                    890:     } 
1.70      www       891:     return %returnhash;
                    892: }
                    893: 
                    894: # ------------------------------------- Find the IDs behind a list of usernames
                    895: 
                    896: sub idrget {
                    897:     my ($udom,@unames)=@_;
                    898:     my %returnhash=();
1.800     albertel  899:     foreach my $uname (@unames) {
                    900:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  901:     }
1.70      www       902:     return %returnhash;
                    903: }
                    904: 
                    905: # ------------------------------- Store away a list of names and associated IDs
                    906: 
                    907: sub idput {
                    908:     my ($udom,%ids)=@_;
                    909:     my %servers=();
1.800     albertel  910:     foreach my $uname (keys(%ids)) {
                    911: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    912:         my $uhom=&homeserver($uname,$udom);
1.70      www       913:         if ($uhom ne 'no_host') {
1.800     albertel  914:             my $id=&escape($ids{$uname});
1.70      www       915:             $id=~tr/A-Z/a-z/;
1.800     albertel  916:             my $esc_unam=&escape($uname);
1.70      www       917: 	    if ($servers{$uhom}) {
1.800     albertel  918: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       919:             } else {
1.800     albertel  920:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       921:             }
                    922:         }
1.191     harris41  923:     }
1.800     albertel  924:     foreach my $server (keys(%servers)) {
                    925:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  926:     }
1.344     www       927: }
                    928: 
1.806     raeburn   929: # ------------------------------------------- get items from domain db files   
                    930: 
                    931: sub get_dom {
1.860     raeburn   932:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   933:     my $items='';
                    934:     foreach my $item (@$storearr) {
                    935:         $items.=&escape($item).'&';
                    936:     }
                    937:     $items=~s/\&$//;
1.860     raeburn   938:     if (!$udom) {
                    939:         $udom=$env{'user.domain'};
                    940:         if (defined(&domain($udom,'primary'))) {
                    941:             $uhome=&domain($udom,'primary');
                    942:         } else {
1.874     albertel  943:             undef($uhome);
1.860     raeburn   944:         }
                    945:     } else {
                    946:         if (!$uhome) {
                    947:             if (defined(&domain($udom,'primary'))) {
                    948:                 $uhome=&domain($udom,'primary');
                    949:             }
                    950:         }
                    951:     }
                    952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   953:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   954:         my %returnhash;
1.875     albertel  955:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   956:             return %returnhash;
                    957:         }
1.806     raeburn   958:         my @pairs=split(/\&/,$rep);
                    959:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    960:             return @pairs;
                    961:         }
                    962:         my $i=0;
                    963:         foreach my $item (@$storearr) {
                    964:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    965:             $i++;
                    966:         }
                    967:         return %returnhash;
                    968:     } else {
1.880     banghart  969:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   970:     }
                    971: }
                    972: 
                    973: # -------------------------------------------- put items in domain db files 
                    974: 
                    975: sub put_dom {
1.860     raeburn   976:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    977:     if (!$udom) {
                    978:         $udom=$env{'user.domain'};
                    979:         if (defined(&domain($udom,'primary'))) {
                    980:             $uhome=&domain($udom,'primary');
                    981:         } else {
1.874     albertel  982:             undef($uhome);
1.860     raeburn   983:         }
                    984:     } else {
                    985:         if (!$uhome) {
                    986:             if (defined(&domain($udom,'primary'))) {
                    987:                 $uhome=&domain($udom,'primary');
                    988:             }
                    989:         }
                    990:     } 
                    991:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   992:         my $items='';
                    993:         foreach my $item (keys(%$storehash)) {
                    994:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    995:         }
                    996:         $items=~s/\&$//;
                    997:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    998:     } else {
1.860     raeburn   999:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1000:     }
                   1001: }
                   1002: 
1.837     raeburn  1003: sub retrieve_inst_usertypes {
                   1004:     my ($udom) = @_;
                   1005:     my (%returnhash,@order);
1.989     raeburn  1006:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1007:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1008:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1009:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1010:         @order = @{$domdefs{'inststatusorder'}};
                   1011:     } else {
                   1012:         if (defined(&domain($udom,'primary'))) {
                   1013:             my $uhome=&domain($udom,'primary');
                   1014:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1015:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1016:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1017:                 return (\%returnhash,\@order);
                   1018:             }
                   1019:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1020:             my @pairs=split(/\&/,$hashitems);
                   1021:             foreach my $item (@pairs) {
                   1022:                 my ($key,$value)=split(/=/,$item,2);
                   1023:                 $key = &unescape($key);
                   1024:                 next if ($key =~ /^error: 2 /);
                   1025:                 $returnhash{$key}=&thaw_unescape($value);
                   1026:             }
                   1027:             my @esc_order = split(/\&/,$orderitems);
                   1028:             foreach my $item (@esc_order) {
                   1029:                 push(@order,&unescape($item));
                   1030:             }
                   1031:         } else {
                   1032:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1033:         }
                   1034:     }
                   1035:     return (\%returnhash,\@order);
                   1036: }
                   1037: 
1.868     raeburn  1038: sub is_domainimage {
                   1039:     my ($url) = @_;
                   1040:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1041:         if (&domain($1) ne '') {
                   1042:             return '1';
                   1043:         }
                   1044:     }
                   1045:     return;
                   1046: }
                   1047: 
1.899     raeburn  1048: sub inst_directory_query {
                   1049:     my ($srch) = @_;
                   1050:     my $udom = $srch->{'srchdomain'};
                   1051:     my %results;
                   1052:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1053:     my $outcome;
1.899     raeburn  1054:     if ($homeserver ne '') {
1.904     albertel 1055: 	my $queryid=&reply("querysend:instdirsearch:".
                   1056: 			   &escape($srch->{'srchby'}).':'.
                   1057: 			   &escape($srch->{'srchterm'}).':'.
                   1058: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1059: 	my $host=&hostname($homeserver);
                   1060: 	if ($queryid !~/^\Q$host\E\_/) {
                   1061: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1062: 	    return;
                   1063: 	}
                   1064: 	my $response = &get_query_reply($queryid);
                   1065: 	my $maxtries = 5;
                   1066: 	my $tries = 1;
                   1067: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1068: 	    $response = &get_query_reply($queryid);
                   1069: 	    $tries ++;
                   1070: 	}
                   1071: 
                   1072:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1073:             if ($response eq 'unavailable') {
                   1074:                 $outcome = $response;
                   1075:             } else {
                   1076:                 $outcome = 'ok';
                   1077:                 my @matches = split(/\n/,$response);
                   1078:                 foreach my $match (@matches) {
                   1079:                     my ($key,$value) = split(/=/,$match);
                   1080:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1081:                 }
1.899     raeburn  1082:             }
                   1083:         }
                   1084:     }
1.909     raeburn  1085:     return ($outcome,%results);
1.899     raeburn  1086: }
                   1087: 
                   1088: sub usersearch {
                   1089:     my ($srch) = @_;
                   1090:     my $dom = $srch->{'srchdomain'};
                   1091:     my %results;
                   1092:     my %libserv = &all_library();
                   1093:     my $query = 'usersearch';
                   1094:     foreach my $tryserver (keys(%libserv)) {
                   1095:         if (&host_domain($tryserver) eq $dom) {
                   1096:             my $host=&hostname($tryserver);
                   1097:             my $queryid=
1.911     raeburn  1098:                 &reply("querysend:".&escape($query).':'.
                   1099:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1100:                        &escape($srch->{'srchtype'}).':'.
                   1101:                        &escape($srch->{'srchterm'}),$tryserver);
                   1102:             if ($queryid !~/^\Q$host\E\_/) {
                   1103:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1104:                 next;
1.899     raeburn  1105:             }
                   1106:             my $reply = &get_query_reply($queryid);
                   1107:             my $maxtries = 1;
                   1108:             my $tries = 1;
                   1109:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1110:                 $reply = &get_query_reply($queryid);
                   1111:                 $tries ++;
                   1112:             }
                   1113:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1114:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1115:             } else {
1.911     raeburn  1116:                 my @matches;
                   1117:                 if ($reply =~ /\n/) {
                   1118:                     @matches = split(/\n/,$reply);
                   1119:                 } else {
                   1120:                     @matches = split(/\&/,$reply);
                   1121:                 }
1.899     raeburn  1122:                 foreach my $match (@matches) {
                   1123:                     my ($uname,$udom,%userhash);
1.911     raeburn  1124:                     foreach my $entry (split(/:/,$match)) {
                   1125:                         my ($key,$value) =
                   1126:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1127:                         $userhash{$key} = $value;
                   1128:                         if ($key eq 'username') {
                   1129:                             $uname = $value;
                   1130:                         } elsif ($key eq 'domain') {
                   1131:                             $udom = $value;
1.911     raeburn  1132:                         }
1.899     raeburn  1133:                     }
                   1134:                     $results{$uname.':'.$udom} = \%userhash;
                   1135:                 }
                   1136:             }
                   1137:         }
                   1138:     }
                   1139:     return %results;
                   1140: }
                   1141: 
1.912     raeburn  1142: sub get_instuser {
                   1143:     my ($udom,$uname,$id) = @_;
                   1144:     my $homeserver = &domain($udom,'primary');
                   1145:     my ($outcome,%results);
                   1146:     if ($homeserver ne '') {
                   1147:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1148:                            &escape($id).':'.&escape($udom),$homeserver);
                   1149:         my $host=&hostname($homeserver);
                   1150:         if ($queryid !~/^\Q$host\E\_/) {
                   1151:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1152:             return;
                   1153:         }
                   1154:         my $response = &get_query_reply($queryid);
                   1155:         my $maxtries = 5;
                   1156:         my $tries = 1;
                   1157:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1158:             $response = &get_query_reply($queryid);
                   1159:             $tries ++;
                   1160:         }
                   1161:         if (!&error($response) && $response ne 'refused') {
                   1162:             if ($response eq 'unavailable') {
                   1163:                 $outcome = $response;
                   1164:             } else {
                   1165:                 $outcome = 'ok';
                   1166:                 my @matches = split(/\n/,$response);
                   1167:                 foreach my $match (@matches) {
                   1168:                     my ($key,$value) = split(/=/,$match);
                   1169:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1170:                 }
                   1171:             }
                   1172:         }
                   1173:     }
                   1174:     my %userinfo;
                   1175:     if (ref($results{$uname}) eq 'HASH') {
                   1176:         %userinfo = %{$results{$uname}};
                   1177:     } 
                   1178:     return ($outcome,%userinfo);
                   1179: }
                   1180: 
                   1181: sub inst_rulecheck {
1.923     raeburn  1182:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1183:     my %returnhash;
                   1184:     if ($udom ne '') {
                   1185:         if (ref($rules) eq 'ARRAY') {
                   1186:             @{$rules} = map {&escape($_);} (@{$rules});
                   1187:             my $rulestr = join(':',@{$rules});
                   1188:             my $homeserver=&domain($udom,'primary');
                   1189:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1190:                 my $response;
                   1191:                 if ($item eq 'username') {                
                   1192:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1193:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1194:                                               $homeserver));
1.923     raeburn  1195:                 } elsif ($item eq 'id') {
                   1196:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1197:                                               ':'.&escape($id).':'.$rulestr,
                   1198:                                               $homeserver));
1.945     raeburn  1199:                 } elsif ($item eq 'selfcreate') {
                   1200:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1201:                                                &escape($udom).':'.&escape($uname).
                   1202:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1203:                 }
1.912     raeburn  1204:                 if ($response ne 'refused') {
                   1205:                     my @pairs=split(/\&/,$response);
                   1206:                     foreach my $item (@pairs) {
                   1207:                         my ($key,$value)=split(/=/,$item,2);
                   1208:                         $key = &unescape($key);
                   1209:                         next if ($key =~ /^error: 2 /);
                   1210:                         $returnhash{$key}=&thaw_unescape($value);
                   1211:                     }
                   1212:                 }
                   1213:             }
                   1214:         }
                   1215:     }
                   1216:     return %returnhash;
                   1217: }
                   1218: 
                   1219: sub inst_userrules {
1.923     raeburn  1220:     my ($udom,$check) = @_;
1.912     raeburn  1221:     my (%ruleshash,@ruleorder);
                   1222:     if ($udom ne '') {
                   1223:         my $homeserver=&domain($udom,'primary');
                   1224:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1225:             my $response;
                   1226:             if ($check eq 'id') {
                   1227:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1228:                                  $homeserver);
1.943     raeburn  1229:             } elsif ($check eq 'email') {
                   1230:                 $response=&reply('instemailrules:'.&escape($udom),
                   1231:                                  $homeserver);
1.923     raeburn  1232:             } else {
                   1233:                 $response=&reply('instuserrules:'.&escape($udom),
                   1234:                                  $homeserver);
                   1235:             }
1.912     raeburn  1236:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1237:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1238:                 ($response ne 'no_such_host')) {
                   1239:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1240:                 my @pairs=split(/\&/,$hashitems);
                   1241:                 foreach my $item (@pairs) {
                   1242:                     my ($key,$value)=split(/=/,$item,2);
                   1243:                     $key = &unescape($key);
                   1244:                     next if ($key =~ /^error: 2 /);
                   1245:                     $ruleshash{$key}=&thaw_unescape($value);
                   1246:                 }
                   1247:                 my @esc_order = split(/\&/,$orderitems);
                   1248:                 foreach my $item (@esc_order) {
                   1249:                     push(@ruleorder,&unescape($item));
                   1250:                 }
                   1251:             }
                   1252:         }
                   1253:     }
                   1254:     return (\%ruleshash,\@ruleorder);
                   1255: }
                   1256: 
1.976     raeburn  1257: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1258: 
                   1259: sub get_domain_defaults {
                   1260:     my ($domain) = @_;
                   1261:     my $cachetime = 60*60*24;
                   1262:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1263:     if (defined($cached)) {
                   1264:         if (ref($result) eq 'HASH') {
                   1265:             return %{$result};
                   1266:         }
                   1267:     }
                   1268:     my %domdefaults;
                   1269:     my %domconfig =
1.989     raeburn  1270:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1271:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1272:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1273:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1274:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1275:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1276:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1277:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1278:     } else {
                   1279:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1280:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1281:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1282:     }
1.976     raeburn  1283:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1284:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1285:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1286:         } else {
                   1287:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1288:         } 
                   1289:         my @usertools = ('aboutme','blog','portfolio');
                   1290:         foreach my $item (@usertools) {
                   1291:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1292:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1293:             }
                   1294:         }
                   1295:     }
1.985     raeburn  1296:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
                   1297:         foreach my $item ('official','unofficial') {
                   1298:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1299:         }
                   1300:     }
1.989     raeburn  1301:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1302:         foreach my $item ('inststatustypes','inststatusorder') {
                   1303:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1304:         }
                   1305:     }
1.943     raeburn  1306:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1307:                                   $cachetime);
                   1308:     return %domdefaults;
                   1309: }
                   1310: 
1.344     www      1311: # --------------------------------------------------- Assign a key to a student
                   1312: 
                   1313: sub assign_access_key {
1.364     www      1314: #
                   1315: # a valid key looks like uname:udom#comments
                   1316: # comments are being appended
                   1317: #
1.498     www      1318:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1319:     $kdom=
1.620     albertel 1320:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1321:     $knum=
1.620     albertel 1322:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1323:     $cdom=
1.620     albertel 1324:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1325:     $cnum=
1.620     albertel 1326:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1327:     $udom=$env{'user.name'} unless (defined($udom));
                   1328:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1329:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1330:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1331:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1332:                                                   # assigned to this person
                   1333:                                                   # - this should not happen,
1.345     www      1334:                                                   # unless something went wrong
                   1335:                                                   # the first time around
                   1336: # ready to assign
1.364     www      1337:         $logentry=$1.'; '.$logentry;
1.496     www      1338:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1339:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1340: # key now belongs to user
1.346     www      1341: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1342:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1343:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1344:                 return 'ok';
                   1345:             } else {
                   1346:                 return 
                   1347:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1348: 	    }
                   1349:         } else {
                   1350:             return 'error: Could not assign key, try again later.';
                   1351:         }
1.364     www      1352:     } elsif (!$existing{$ckey}) {
1.345     www      1353: # the key does not exist
                   1354: 	return 'error: The key does not exist';
                   1355:     } else {
                   1356: # the key is somebody else's
                   1357: 	return 'error: The key is already in use';
                   1358:     }
1.344     www      1359: }
                   1360: 
1.364     www      1361: # ------------------------------------------ put an additional comment on a key
                   1362: 
                   1363: sub comment_access_key {
                   1364: #
                   1365: # a valid key looks like uname:udom#comments
                   1366: # comments are being appended
                   1367: #
                   1368:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1369:     $cdom=
1.620     albertel 1370:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1371:     $cnum=
1.620     albertel 1372:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1373:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1374:     if ($existing{$ckey}) {
                   1375:         $existing{$ckey}.='; '.$logentry;
                   1376: # ready to assign
1.367     www      1377:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1378:                                                  $cdom,$cnum) eq 'ok') {
                   1379: 	    return 'ok';
                   1380:         } else {
                   1381: 	    return 'error: Count not store comment.';
                   1382:         }
                   1383:     } else {
                   1384: # the key does not exist
                   1385: 	return 'error: The key does not exist';
                   1386:     }
                   1387: }
                   1388: 
1.344     www      1389: # ------------------------------------------------------ Generate a set of keys
                   1390: 
                   1391: sub generate_access_keys {
1.364     www      1392:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1393:     $cdom=
1.620     albertel 1394:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1395:     $cnum=
1.620     albertel 1396:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1397:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1398:     unless (($cdom) && ($cnum)) { return 0; }
                   1399:     if ($number>10000) { return 0; }
                   1400:     sleep(2); # make sure don't get same seed twice
                   1401:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1402:     my $total=0;
                   1403:     for (my $i=1;$i<=$number;$i++) {
                   1404:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1405:                   sprintf("%lx",int(100000*rand)).'-'.
                   1406:                   sprintf("%lx",int(100000*rand));
                   1407:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1408:        $newkey=~s/0/h/g; # and also 0 and O
                   1409:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1410:        if ($existing{$newkey}) {
                   1411:            $i--;
                   1412:        } else {
1.364     www      1413: 	  if (&put('accesskeys',
                   1414:               { $newkey => '# generated '.localtime().
1.620     albertel 1415:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1416:                            '; '.$logentry },
                   1417: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1418:               $total++;
                   1419: 	  }
                   1420:        }
                   1421:     }
1.620     albertel 1422:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1423:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1424:     return $total;
                   1425: }
                   1426: 
                   1427: # ------------------------------------------------------- Validate an accesskey
                   1428: 
                   1429: sub validate_access_key {
                   1430:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1431:     $cdom=
1.620     albertel 1432:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1433:     $cnum=
1.620     albertel 1434:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1435:     $udom=$env{'user.domain'} unless (defined($udom));
                   1436:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1437:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1438:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1439: }
                   1440: 
                   1441: # ------------------------------------- Find the section of student in a course
1.652     albertel 1442: sub devalidate_getsection_cache {
                   1443:     my ($udom,$unam,$courseid)=@_;
                   1444:     my $hashid="$udom:$unam:$courseid";
                   1445:     &devalidate_cache_new('getsection',$hashid);
                   1446: }
1.298     matthew  1447: 
1.815     albertel 1448: sub courseid_to_courseurl {
                   1449:     my ($courseid) = @_;
                   1450:     #already url style courseid
                   1451:     return $courseid if ($courseid =~ m{^/});
                   1452: 
                   1453:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1454: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1455: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1456: 	return "/$cdom/$cnum";
                   1457:     }
                   1458: 
                   1459:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1460:     if (exists($courseinfo{'num'})) {
                   1461: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1462:     }
                   1463: 
                   1464:     return undef;
                   1465: }
                   1466: 
1.298     matthew  1467: sub getsection {
                   1468:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1469:     my $cachetime=1800;
1.551     albertel 1470: 
                   1471:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1472:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1473:     if (defined($cached)) { return $result; }
                   1474: 
1.298     matthew  1475:     my %Pending; 
                   1476:     my %Expired;
                   1477:     #
                   1478:     # Each role can either have not started yet (pending), be active, 
                   1479:     #    or have expired.
                   1480:     #
                   1481:     # If there is an active role, we are done.
                   1482:     #
                   1483:     # If there is more than one role which has not started yet, 
                   1484:     #     choose the one which will start sooner
                   1485:     # If there is one role which has not started yet, return it.
                   1486:     #
                   1487:     # If there is more than one expired role, choose the one which ended last.
                   1488:     # If there is a role which has expired, return it.
                   1489:     #
1.815     albertel 1490:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1491:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1492:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1493:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1494:         my $section=$1;
                   1495:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1496:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1497:         my $now=time;
1.548     albertel 1498:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1499:             $Expired{$end}=$section;
                   1500:             next;
                   1501:         }
1.548     albertel 1502:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1503:             $Pending{$start}=$section;
                   1504:             next;
                   1505:         }
1.599     albertel 1506:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1507:     }
                   1508:     #
                   1509:     # Presumedly there will be few matching roles from the above
                   1510:     # loop and the sorting time will be negligible.
                   1511:     if (scalar(keys(%Pending))) {
                   1512:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1513:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1514:     } 
                   1515:     if (scalar(keys(%Expired))) {
                   1516:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1517:         my $time = pop(@sorted);
1.599     albertel 1518:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1519:     }
1.599     albertel 1520:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1521: }
1.70      www      1522: 
1.599     albertel 1523: sub save_cache {
                   1524:     &purge_remembered();
1.722     albertel 1525:     #&Apache::loncommon::validate_page();
1.620     albertel 1526:     undef(%env);
1.780     albertel 1527:     undef($env_loaded);
1.599     albertel 1528: }
1.452     albertel 1529: 
1.599     albertel 1530: my $to_remember=-1;
                   1531: my %remembered;
                   1532: my %accessed;
                   1533: my $kicks=0;
                   1534: my $hits=0;
1.849     albertel 1535: sub make_key {
                   1536:     my ($name,$id) = @_;
1.872     albertel 1537:     if (length($id) > 65 
                   1538: 	&& length(&escape($id)) > 200) {
                   1539: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1540:     }
1.849     albertel 1541:     return &escape($name.':'.$id);
                   1542: }
                   1543: 
1.599     albertel 1544: sub devalidate_cache_new {
                   1545:     my ($name,$id,$debug) = @_;
                   1546:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1547:     $id=&make_key($name,$id);
1.599     albertel 1548:     $memcache->delete($id);
                   1549:     delete($remembered{$id});
                   1550:     delete($accessed{$id});
                   1551: }
                   1552: 
                   1553: sub is_cached_new {
                   1554:     my ($name,$id,$debug) = @_;
1.849     albertel 1555:     $id=&make_key($name,$id);
1.599     albertel 1556:     if (exists($remembered{$id})) {
                   1557: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1558: 	$accessed{$id}=[&gettimeofday()];
                   1559: 	$hits++;
                   1560: 	return ($remembered{$id},1);
                   1561:     }
                   1562:     my $value = $memcache->get($id);
                   1563:     if (!(defined($value))) {
                   1564: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1565: 	return (undef,undef);
1.416     albertel 1566:     }
1.599     albertel 1567:     if ($value eq '__undef__') {
                   1568: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1569: 	$value=undef;
                   1570:     }
                   1571:     &make_room($id,$value,$debug);
                   1572:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1573:     return ($value,1);
                   1574: }
                   1575: 
                   1576: sub do_cache_new {
                   1577:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1578:     $id=&make_key($name,$id);
1.599     albertel 1579:     my $setvalue=$value;
                   1580:     if (!defined($setvalue)) {
                   1581: 	$setvalue='__undef__';
                   1582:     }
1.623     albertel 1583:     if (!defined($time) ) {
                   1584: 	$time=600;
                   1585:     }
1.599     albertel 1586:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1587:     my $result = $memcache->set($id,$setvalue,$time);
                   1588:     if (! $result) {
1.872     albertel 1589: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1590: 	$memcache->disconnect_all();
1.872     albertel 1591:     }
1.600     albertel 1592:     # need to make a copy of $value
1.919     albertel 1593:     &make_room($id,$value,$debug);
1.599     albertel 1594:     return $value;
                   1595: }
                   1596: 
                   1597: sub make_room {
                   1598:     my ($id,$value,$debug)=@_;
1.919     albertel 1599: 
                   1600:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1601:                                     : $value;
1.599     albertel 1602:     if ($to_remember<0) { return; }
                   1603:     $accessed{$id}=[&gettimeofday()];
                   1604:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1605:     my $to_kick;
                   1606:     my $max_time=0;
                   1607:     foreach my $other (keys(%accessed)) {
                   1608: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1609: 	    $to_kick=$other;
                   1610: 	    $max_time=&tv_interval($accessed{$other});
                   1611: 	}
                   1612:     }
                   1613:     delete($remembered{$to_kick});
                   1614:     delete($accessed{$to_kick});
                   1615:     $kicks++;
                   1616:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1617:     return;
                   1618: }
                   1619: 
1.599     albertel 1620: sub purge_remembered {
1.604     albertel 1621:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1622:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1623:     undef(%remembered);
                   1624:     undef(%accessed);
1.428     albertel 1625: }
1.70      www      1626: # ------------------------------------- Read an entry from a user's environment
                   1627: 
                   1628: sub userenvironment {
                   1629:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1630:     my $items;
                   1631:     foreach my $item (@what) {
                   1632:         $items.=&escape($item).'&';
                   1633:     }
                   1634:     $items=~s/\&$//;
1.70      www      1635:     my %returnhash=();
                   1636:     my @answer=split(/\&/,
1.976     raeburn  1637:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1638:                       &homeserver($unam,$udom)));
                   1639:     my $i;
                   1640:     for ($i=0;$i<=$#what;$i++) {
                   1641: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1642:     }
                   1643:     return %returnhash;
1.1       albertel 1644: }
                   1645: 
1.617     albertel 1646: # ---------------------------------------------------------- Get a studentphoto
                   1647: sub studentphoto {
                   1648:     my ($udom,$unam,$ext) = @_;
                   1649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1650:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1651:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1652:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1653:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1654:             } else {
                   1655:                 my ($result,$perm_reqd)=
1.707     albertel 1656: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1657:                 if ($result eq 'ok') {
                   1658:                     if (!($perm_reqd eq 'yes')) {
                   1659:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1660:                     }
                   1661:                 }
                   1662:             }
                   1663:         }
                   1664:     } else {
                   1665:         my ($result,$perm_reqd) = 
1.707     albertel 1666: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1667:         if ($result eq 'ok') {
                   1668:             if (!($perm_reqd eq 'yes')) {
                   1669:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1670:             }
                   1671:         }
                   1672:     }
                   1673:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1674: }
                   1675: 
                   1676: sub retrievestudentphoto {
                   1677:     my ($udom,$unam,$ext,$type) = @_;
                   1678:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1679:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1680:     if ($ret eq 'ok') {
                   1681:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1682:         if ($type eq 'thumbnail') {
                   1683:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1684:         }
                   1685:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1686:         return $tokenurl;
                   1687:     } else {
                   1688:         if ($type eq 'thumbnail') {
                   1689:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1690:         } else { 
                   1691:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1692:         }
1.617     albertel 1693:     }
                   1694: }
                   1695: 
1.263     www      1696: # -------------------------------------------------------------------- New chat
                   1697: 
                   1698: sub chatsend {
1.724     raeburn  1699:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1700:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1702:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1703:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1704: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1705: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1706: }
                   1707: 
                   1708: # ------------------------------------------ Find current version of a resource
                   1709: 
                   1710: sub getversion {
                   1711:     my $fname=&clutter(shift);
                   1712:     unless ($fname=~/^\/res\//) { return -1; }
                   1713:     return &currentversion(&filelocation('',$fname));
                   1714: }
                   1715: 
                   1716: sub currentversion {
                   1717:     my $fname=shift;
1.599     albertel 1718:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1719:     if (defined($cached)) { return $result; }
1.292     www      1720:     my $author=$fname;
                   1721:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1722:     my ($udom,$uname)=split(/\//,$author);
                   1723:     my $home=homeserver($uname,$udom);
                   1724:     if ($home eq 'no_host') { 
                   1725:         return -1; 
                   1726:     }
                   1727:     my $answer=reply("currentversion:$fname",$home);
                   1728:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1729: 	return -1;
                   1730:     }
1.599     albertel 1731:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1732: }
                   1733: 
1.1       albertel 1734: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1735: 
1.1       albertel 1736: sub subscribe {
                   1737:     my $fname=shift;
1.761     raeburn  1738:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1739:     $fname=~s/[\n\r]//g;
1.1       albertel 1740:     my $author=$fname;
                   1741:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1742:     my ($udom,$uname)=split(/\//,$author);
                   1743:     my $home=homeserver($uname,$udom);
1.335     albertel 1744:     if ($home eq 'no_host') {
                   1745:         return 'not_found';
1.1       albertel 1746:     }
                   1747:     my $answer=reply("sub:$fname",$home);
1.64      www      1748:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1749: 	$answer.=' by '.$home;
                   1750:     }
1.1       albertel 1751:     return $answer;
                   1752: }
                   1753:     
1.8       www      1754: # -------------------------------------------------------------- Replicate file
                   1755: 
                   1756: sub repcopy {
                   1757:     my $filename=shift;
1.23      www      1758:     $filename=~s/\/+/\//g;
1.607     raeburn  1759:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1760:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1761:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1762: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1763: 	return &repcopy_userfile($filename);
                   1764:     }
1.532     albertel 1765:     $filename=~s/[\n\r]//g;
1.8       www      1766:     my $transname="$filename.in.transfer";
1.828     www      1767: # FIXME: this should flock
1.607     raeburn  1768:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1769:     my $remoteurl=subscribe($filename);
1.64      www      1770:     if ($remoteurl =~ /^con_lost by/) {
                   1771: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1772:            return 'unavailable';
1.8       www      1773:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1774: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1775: 	   return 'not_found';
1.64      www      1776:     } elsif ($remoteurl =~ /^rejected by/) {
                   1777: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1778:            return 'forbidden';
1.20      www      1779:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1780:            return 'ok';
1.8       www      1781:     } else {
1.290     www      1782:         my $author=$filename;
                   1783:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1784:         my ($udom,$uname)=split(/\//,$author);
                   1785:         my $home=homeserver($uname,$udom);
                   1786:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1787:            my @parts=split(/\//,$filename);
                   1788:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1789:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1790:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1791: 	       return 'bad_request';
1.8       www      1792:            }
                   1793:            my $count;
                   1794:            for ($count=5;$count<$#parts;$count++) {
                   1795:                $path.="/$parts[$count]";
                   1796:                if ((-e $path)!=1) {
                   1797: 		   mkdir($path,0777);
                   1798:                }
                   1799:            }
                   1800:            my $ua=new LWP::UserAgent;
                   1801:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1802:            my $response=$ua->request($request,$transname);
                   1803:            if ($response->is_error()) {
                   1804: 	       unlink($transname);
                   1805:                my $message=$response->status_line;
1.672     albertel 1806:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1807:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1808:                return 'unavailable';
1.8       www      1809:            } else {
1.16      www      1810: 	       if ($remoteurl!~/\.meta$/) {
                   1811:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1812:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1813:                   if ($mresponse->is_error()) {
                   1814: 		      unlink($filename.'.meta');
                   1815:                       &logthis(
1.672     albertel 1816:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1817:                   }
                   1818: 	       }
1.8       www      1819:                rename($transname,$filename);
1.607     raeburn  1820:                return 'ok';
1.8       www      1821:            }
1.290     www      1822:        }
1.8       www      1823:     }
1.330     www      1824: }
                   1825: 
                   1826: # ------------------------------------------------ Get server side include body
                   1827: sub ssi_body {
1.381     albertel 1828:     my ($filelink,%form)=@_;
1.606     matthew  1829:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1830:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1831:     }
1.953     www      1832:     my $output='';
                   1833:     my $response;
1.980     raeburn  1834:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1835:        ($output,$response)=&externalssi($filelink);
1.953     www      1836:     } else {
                   1837:        ($output,$response)=&ssi($filelink,%form);
                   1838:     }
1.778     albertel 1839:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1840:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1841:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1842:     if (wantarray) {
                   1843:         return ($output, $response);
                   1844:     } else {
                   1845:         return $output;
                   1846:     }
1.8       www      1847: }
                   1848: 
1.15      www      1849: # --------------------------------------------------------- Server Side Include
                   1850: 
1.782     albertel 1851: sub absolute_url {
                   1852:     my ($host_name) = @_;
                   1853:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1854:     if ($host_name eq '') {
                   1855: 	$host_name = $ENV{'SERVER_NAME'};
                   1856:     }
                   1857:     return $protocol.$host_name;
                   1858: }
                   1859: 
1.942     foxr     1860: #
                   1861: #   Server side include.
                   1862: # Parameters:
                   1863: #  fn     Possibly encrypted resource name/id.
                   1864: #  form   Hash that describes how the rendering should be done
                   1865: #         and other things.
1.944     foxr     1866: # Returns:
1.950     raeburn  1867: #   Scalar context: The content of the response.
                   1868: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1869: #     
1.15      www      1870: sub ssi {
                   1871: 
1.944     foxr     1872:     my ($fn,%form)=@_;
1.15      www      1873:     my $ua=new LWP::UserAgent;
1.23      www      1874:     my $request;
1.711     albertel 1875: 
                   1876:     $form{'no_update_last_known'}=1;
1.895     albertel 1877:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1878:     if (%form) {
1.782     albertel 1879:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1880:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1881:     } else {
1.782     albertel 1882:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1883:     }
                   1884: 
1.15      www      1885:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1886:     my $response=$ua->request($request);
                   1887: 
1.944     foxr     1888:     if (wantarray) {
                   1889: 	return ($response->content, $response);
                   1890:     } else {
                   1891: 	return $response->content;
1.942     foxr     1892:     }
1.324     www      1893: }
                   1894: 
                   1895: sub externalssi {
                   1896:     my ($url)=@_;
                   1897:     my $ua=new LWP::UserAgent;
                   1898:     my $request=new HTTP::Request('GET',$url);
                   1899:     my $response=$ua->request($request);
1.954     raeburn  1900:     if (wantarray) {
                   1901:         return ($response->content, $response);
                   1902:     } else {
                   1903:         return $response->content;
                   1904:     }
1.15      www      1905: }
1.254     www      1906: 
1.492     albertel 1907: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1908: 
                   1909: sub allowuploaded {
                   1910:     my ($srcurl,$url)=@_;
                   1911:     $url=&clutter(&declutter($url));
                   1912:     my $dir=$url;
                   1913:     $dir=~s/\/[^\/]+$//;
                   1914:     my %httpref=();
                   1915:     my $httpurl=&hreflocation('',$url);
                   1916:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1917:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1918: }
1.477     raeburn  1919: 
1.478     albertel 1920: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1921: # input: action, courseID, current domain, intended
1.637     raeburn  1922: #        path to file, source of file, instruction to parse file for objects,
                   1923: #        ref to hash for embedded objects,
                   1924: #        ref to hash for codebase of java objects.
                   1925: #
1.485     raeburn  1926: # output: url to file (if action was uploaddoc), 
                   1927: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1928: #
1.478     albertel 1929: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1930: # course.
1.477     raeburn  1931: #
1.478     albertel 1932: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1933: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1934: #          course's home server.
1.477     raeburn  1935: #
1.478     albertel 1936: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1937: #          be copied from $source (current location) to 
                   1938: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1939: #         and will then be copied to
                   1940: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1941: #         course's home server.
1.485     raeburn  1942: #
1.481     raeburn  1943: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1944: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1945: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1946: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1947: #         in course's home server.
1.637     raeburn  1948: #
1.477     raeburn  1949: 
                   1950: sub process_coursefile {
1.638     albertel 1951:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1952:     my $fetchresult;
1.638     albertel 1953:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1954:     if ($action eq 'propagate') {
1.638     albertel 1955:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1956: 			     $home);
1.481     raeburn  1957:     } else {
1.477     raeburn  1958:         my $fpath = '';
                   1959:         my $fname = $file;
1.478     albertel 1960:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1961:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1962:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1963:         if ($action eq 'copy') {
                   1964:             if ($source eq '') {
                   1965:                 $fetchresult = 'no source file';
                   1966:                 return $fetchresult;
                   1967:             } else {
                   1968:                 my $destination = $filepath.'/'.$fname;
                   1969:                 rename($source,$destination);
                   1970:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1971:                                  $home);
1.481     raeburn  1972:             }
                   1973:         } elsif ($action eq 'uploaddoc') {
                   1974:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1975:             print $fh $env{'form.'.$source};
1.481     raeburn  1976:             close($fh);
1.637     raeburn  1977:             if ($parser eq 'parse') {
1.961     raeburn  1978:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1979:                 unless ($parse_result eq 'ok') {
                   1980:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1981:                 }
                   1982:             }
1.477     raeburn  1983:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1984:                                  $home);
1.481     raeburn  1985:             if ($fetchresult eq 'ok') {
                   1986:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1987:             } else {
                   1988:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1989:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1990:                 return '/adm/notfound.html';
                   1991:             }
1.477     raeburn  1992:         }
                   1993:     }
1.485     raeburn  1994:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1995:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1996:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1997:     }
                   1998:     return $fetchresult;
                   1999: }
                   2000: 
1.637     raeburn  2001: sub build_filepath {
                   2002:     my ($fpath) = @_;
                   2003:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2004:     unless ($fpath eq '') {
                   2005:         my @parts=split('/',$fpath);
                   2006:         foreach my $part (@parts) {
                   2007:             $filepath.= '/'.$part;
                   2008:             if ((-e $filepath)!=1) {
                   2009:                 mkdir($filepath,0777);
                   2010:             }
                   2011:         }
                   2012:     }
                   2013:     return $filepath;
                   2014: }
                   2015: 
                   2016: sub store_edited_file {
1.638     albertel 2017:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2018:     my $file = $primary_url;
                   2019:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2020:     my $fpath = '';
                   2021:     my $fname = $file;
                   2022:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2023:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2024:     my $filepath = &build_filepath($fpath);
                   2025:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2026:     print $fh $content;
                   2027:     close($fh);
1.638     albertel 2028:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2029:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2030: 			  $home);
1.637     raeburn  2031:     if ($$fetchresult eq 'ok') {
                   2032:         return '/uploaded/'.$fpath.'/'.$fname;
                   2033:     } else {
1.638     albertel 2034:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2035: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2036:         return '/adm/notfound.html';
                   2037:     }
                   2038: }
                   2039: 
1.531     albertel 2040: sub clean_filename {
1.831     albertel 2041:     my ($fname,$args)=@_;
1.315     www      2042: # Replace Windows backslashes by forward slashes
1.257     www      2043:     $fname=~s/\\/\//g;
1.831     albertel 2044:     if (!$args->{'keep_path'}) {
                   2045:         # Get rid of everything but the actual filename
                   2046: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2047:     }
1.315     www      2048: # Replace spaces by underscores
                   2049:     $fname=~s/\s+/\_/g;
                   2050: # Replace all other weird characters by nothing
1.831     albertel 2051:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2052: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2053: # numbers
                   2054:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2055:     return $fname;
                   2056: }
1.984     neumanie 2057: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2058: sub resizeImage {
                   2059: 	my($img_url) = @_;	
                   2060: 	my $ima = Image::Magick->new;                       
                   2061:         $ima->Read($img_url);
                   2062: 	if($ima->Get('width') > 400)
                   2063: 	{
                   2064: 		my $factor = $ima->Get('width')/400;
                   2065:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2066: 	}
                   2067: 	if($ima->Get('height') > 500)
                   2068:         {
                   2069:         	my $factor = $ima->Get('height')/500;
                   2070:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2071:         } 
                   2072: 		
                   2073: 	$ima->Write($img_url);
                   2074: }
1.531     albertel 2075: 
1.977     amueller 2076: #Wrapper function for userphotoupload
                   2077: sub userphotoupload
                   2078: {
                   2079: 	my($formname,$subdir) = @_;
                   2080: 	$upload_photo_form = 1;
                   2081: 	return &userfileupload($formname,undef,$subdir);
                   2082: }
                   2083: 
1.608     albertel 2084: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2085: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2086: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2087: #        $coursedoc - if true up to the current course
                   2088: #                     if false
                   2089: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2090: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2091: #        $allfiles - reference to hash for embedded objects
                   2092: #        $codebase - reference to hash for codebase of java objects
                   2093: #        $desuname - username for permanent storage of uploaded file
                   2094: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2095: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2096: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2097: # 
1.686     albertel 2098: # output: url of file in userspace, or error: <message> 
                   2099: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2100: 
                   2101: 
1.531     albertel 2102: sub userfileupload {
1.860     raeburn  2103:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2104:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2105:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2106:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2107:     $fname=&clean_filename($fname);
1.315     www      2108: # See if there is anything left
1.257     www      2109:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2110:     chop($env{'form.'.$formname});
1.523     raeburn  2111:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2112:         my $now = time;
                   2113:         my $filepath = 'tmp/helprequests/'.$now;
                   2114:         my @parts=split(/\//,$filepath);
                   2115:         my $fullpath = $perlvar{'lonDaemons'};
                   2116:         for (my $i=0;$i<@parts;$i++) {
                   2117:             $fullpath .= '/'.$parts[$i];
                   2118:             if ((-e $fullpath)!=1) {
                   2119:                 mkdir($fullpath,0777);
                   2120:             }
                   2121:         }
                   2122:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2123:         print $fh $env{'form.'.$formname};
1.523     raeburn  2124:         close($fh);
1.741     raeburn  2125:         return $fullpath.'/'.$fname;
                   2126:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2127:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2128:                        '_'.$env{'user.domain'}.'/pending';
                   2129:         my @parts=split(/\//,$filepath);
                   2130:         my $fullpath = $perlvar{'lonDaemons'};
                   2131:         for (my $i=0;$i<@parts;$i++) {
                   2132:             $fullpath .= '/'.$parts[$i];
                   2133:             if ((-e $fullpath)!=1) {
                   2134:                 mkdir($fullpath,0777);
                   2135:             }
                   2136:         }
                   2137:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2138:         print $fh $env{'form.'.$formname};
                   2139:         close($fh);
                   2140:         return $fullpath.'/'.$fname;
1.523     raeburn  2141:     }
1.719     banghart 2142:     
1.258     www      2143: # Create the directory if not present
1.493     albertel 2144:     $fname="$subdir/$fname";
1.259     www      2145:     if ($coursedoc) {
1.638     albertel 2146: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2147: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2148:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2149:             return &finishuserfileupload($docuname,$docudom,
                   2150: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2151: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2152:         } else {
1.620     albertel 2153:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2154:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2155: 				       $fname,$formname,$parser,
                   2156: 				       $allfiles,$codebase);
1.481     raeburn  2157:         }
1.719     banghart 2158:     } elsif (defined($destuname)) {
                   2159:         my $docuname=$destuname;
                   2160:         my $docudom=$destudom;
1.860     raeburn  2161: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2162: 				     $parser,$allfiles,$codebase,
                   2163:                                      $thumbwidth,$thumbheight);
1.719     banghart 2164:         
1.259     www      2165:     } else {
1.638     albertel 2166:         my $docuname=$env{'user.name'};
                   2167:         my $docudom=$env{'user.domain'};
1.714     raeburn  2168:         if (exists($env{'form.group'})) {
                   2169:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2170:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2171:         }
1.860     raeburn  2172: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2173: 				     $parser,$allfiles,$codebase,
                   2174:                                      $thumbwidth,$thumbheight);
1.259     www      2175:     }
1.271     www      2176: }
                   2177: 
                   2178: sub finishuserfileupload {
1.860     raeburn  2179:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2180:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2181:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2182:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2183:   
1.860     raeburn  2184:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2185:     $file=$fname;
                   2186:     if ($fname=~m|/|) {
                   2187:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2188: 	$path.=$fnamepath.'/';
                   2189:     }
1.259     www      2190:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2191:     my $count;
                   2192:     for ($count=4;$count<=$#parts;$count++) {
                   2193:         $filepath.="/$parts[$count]";
                   2194:         if ((-e $filepath)!=1) {
                   2195: 	    mkdir($filepath,0777);
                   2196:         }
                   2197:     }
1.984     neumanie 2198: 
1.258     www      2199: # Save the file
                   2200:     {
1.701     albertel 2201: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2202: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2203: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2204: 	    return '/adm/notfound.html';
                   2205: 	}
                   2206: 	if (!print FH ($env{'form.'.$formname})) {
                   2207: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2208: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2209: 	    return '/adm/notfound.html';
                   2210: 	}
1.570     albertel 2211: 	close(FH);
1.977     amueller 2212: 	if($upload_photo_form==1)
                   2213: 	{
1.984     neumanie 2214: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2215: 		$upload_photo_form = 0;
                   2216: 	}
1.258     www      2217:     }
1.637     raeburn  2218:     if ($parser eq 'parse') {
1.961     raeburn  2219:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2220: 						   $codebase);
1.637     raeburn  2221:         unless ($parse_result eq 'ok') {
1.638     albertel 2222:             &logthis('Failed to parse '.$filepath.$file.
                   2223: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2224:         }
                   2225:     }
1.860     raeburn  2226:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2227:         my $input = $filepath.'/'.$file;
                   2228:         my $output = $filepath.'/'.'tn-'.$file;
                   2229:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2230:         system("convert -sample $thumbsize $input $output");
                   2231:         if (-e $filepath.'/'.'tn-'.$file) {
                   2232:             $fetchthumb  = 1; 
                   2233:         }
                   2234:     }
1.858     raeburn  2235:  
1.259     www      2236: # Notify homeserver to grep it
                   2237: #
1.984     neumanie 2238:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2239:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2240:     if ($fetchresult eq 'ok') {
1.860     raeburn  2241:         if ($fetchthumb) {
                   2242:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2243:             if ($thumbresult ne 'ok') {
                   2244:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2245:                          $docuhome.': '.$thumbresult);
                   2246:             }
                   2247:         }
1.259     www      2248: #
1.258     www      2249: # Return the URL to it
1.494     albertel 2250:         return '/uploaded/'.$path.$file;
1.263     www      2251:     } else {
1.494     albertel 2252:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2253: 		 ': '.$fetchresult);
1.263     www      2254:         return '/adm/notfound.html';
1.858     raeburn  2255:     }
1.493     albertel 2256: }
                   2257: 
1.637     raeburn  2258: sub extract_embedded_items {
1.961     raeburn  2259:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2260:     my @state = ();
                   2261:     my %javafiles = (
                   2262:                       codebase => '',
                   2263:                       code => '',
                   2264:                       archive => ''
                   2265:                     );
                   2266:     my %mediafiles = (
                   2267:                       src => '',
                   2268:                       movie => '',
                   2269:                      );
1.648     raeburn  2270:     my $p;
                   2271:     if ($content) {
                   2272:         $p = HTML::LCParser->new($content);
                   2273:     } else {
1.961     raeburn  2274:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2275:     }
1.641     albertel 2276:     while (my $t=$p->get_token()) {
1.640     albertel 2277: 	if ($t->[0] eq 'S') {
                   2278: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2279: 	    push(@state, $tagname);
1.648     raeburn  2280:             if (lc($tagname) eq 'allow') {
                   2281:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2282:             }
1.640     albertel 2283: 	    if (lc($tagname) eq 'img') {
                   2284: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2285: 	    }
1.886     albertel 2286: 	    if (lc($tagname) eq 'a') {
                   2287: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2288: 	    }
1.645     raeburn  2289:             if (lc($tagname) eq 'script') {
                   2290:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2291:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2292:                 } else {
                   2293:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2294:                 }
                   2295:             }
                   2296:             if (lc($tagname) eq 'link') {
                   2297:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2298:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2299:                 }
                   2300:             }
1.640     albertel 2301: 	    if (lc($tagname) eq 'object' ||
                   2302: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2303: 		foreach my $item (keys(%javafiles)) {
                   2304: 		    $javafiles{$item} = '';
                   2305: 		}
                   2306: 	    }
                   2307: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2308: 		my $name = lc($attr->{'name'});
                   2309: 		foreach my $item (keys(%javafiles)) {
                   2310: 		    if ($name eq $item) {
                   2311: 			$javafiles{$item} = $attr->{'value'};
                   2312: 			last;
                   2313: 		    }
                   2314: 		}
                   2315: 		foreach my $item (keys(%mediafiles)) {
                   2316: 		    if ($name eq $item) {
                   2317: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2318: 			last;
                   2319: 		    }
                   2320: 		}
                   2321: 	    }
                   2322: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2323: 		foreach my $item (keys(%javafiles)) {
                   2324: 		    if ($attr->{$item}) {
                   2325: 			$javafiles{$item} = $attr->{$item};
                   2326: 			last;
                   2327: 		    }
                   2328: 		}
                   2329: 		foreach my $item (keys(%mediafiles)) {
                   2330: 		    if ($attr->{$item}) {
                   2331: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2332: 			last;
                   2333: 		    }
                   2334: 		}
                   2335: 	    }
                   2336: 	} elsif ($t->[0] eq 'E') {
                   2337: 	    my ($tagname) = ($t->[1]);
                   2338: 	    if ($javafiles{'codebase'} ne '') {
                   2339: 		$javafiles{'codebase'} .= '/';
                   2340: 	    }  
                   2341: 	    if (lc($tagname) eq 'applet' ||
                   2342: 		lc($tagname) eq 'object' ||
                   2343: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2344: 		) {
                   2345: 		foreach my $item (keys(%javafiles)) {
                   2346: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2347: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2348: 			&add_filetype($allfiles,$file,$item);
                   2349: 		    }
                   2350: 		}
                   2351: 	    } 
                   2352: 	    pop @state;
                   2353: 	}
                   2354:     }
1.637     raeburn  2355:     return 'ok';
                   2356: }
                   2357: 
1.639     albertel 2358: sub add_filetype {
                   2359:     my ($allfiles,$file,$type)=@_;
                   2360:     if (exists($allfiles->{$file})) {
                   2361: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2362: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2363: 	}
                   2364:     } else {
                   2365: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2366:     }
                   2367: }
                   2368: 
1.493     albertel 2369: sub removeuploadedurl {
1.984     neumanie 2370:     my ($url)=@_;	
                   2371:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2372:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2373: }
                   2374: 
                   2375: sub removeuserfile {
                   2376:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2377:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2378:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2379:     if ($result eq 'ok') {	
1.798     raeburn  2380:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2381:             my $metafile = $fname.'.meta';
                   2382:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2383: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2384:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2385:             my $sqlresult = 
1.823     albertel 2386:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2387:                                         'portfolio_metadata',$group,
                   2388:                                         'delete');
1.798     raeburn  2389:         }
                   2390:     }
                   2391:     return $result;
1.257     www      2392: }
1.15      www      2393: 
1.530     albertel 2394: sub mkdiruserfile {
                   2395:     my ($docuname,$docudom,$dir)=@_;
                   2396:     my $home=&homeserver($docuname,$docudom);
                   2397:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2398: }
                   2399: 
1.531     albertel 2400: sub renameuserfile {
                   2401:     my ($docuname,$docudom,$old,$new)=@_;
                   2402:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2403:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2404:                         &escape("$old").':'.&escape("$new"),$home);
                   2405:     if ($result eq 'ok') {
                   2406:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2407:             my $oldmeta = $old.'.meta';
                   2408:             my $newmeta = $new.'.meta';
                   2409:             my $metaresult = 
                   2410:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2411: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2412:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2413:             my $sqlresult = 
1.823     albertel 2414:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2415:                                         'portfolio_metadata',$group,
                   2416:                                         'delete');
1.798     raeburn  2417:         }
                   2418:     }
                   2419:     return $result;
1.531     albertel 2420: }
                   2421: 
1.14      www      2422: # ------------------------------------------------------------------------- Log
                   2423: 
                   2424: sub log {
                   2425:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2426:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2427: }
                   2428: 
                   2429: # ------------------------------------------------------------------ Course Log
1.352     www      2430: #
                   2431: # This routine flushes several buffers of non-mission-critical nature
                   2432: #
1.157     www      2433: 
                   2434: sub flushcourselogs {
1.352     www      2435:     &logthis('Flushing log buffers');
                   2436: #
                   2437: # course logs
                   2438: # This is a log of all transactions in a course, which can be used
                   2439: # for data mining purposes
                   2440: #
                   2441: # It also collects the courseid database, which lists last transaction
                   2442: # times and course titles for all courseids
                   2443: #
                   2444:     my %courseidbuffer=();
1.921     raeburn  2445:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2446:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2447: 		          &escape($courselogs{$crsid}),
                   2448: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2449: 	    delete $courselogs{$crsid};
                   2450:         } else {
                   2451:             &logthis('Failed to flush log buffer for '.$crsid);
                   2452:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2453:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2454:                         " exceeded maximum size, deleting.</font>");
                   2455:                delete $courselogs{$crsid};
                   2456:             }
1.352     www      2457:         }
1.920     raeburn  2458:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2459:             'description' => $coursedescrbuf{$crsid},
                   2460:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2461:             'type'        => $coursetypebuf{$crsid},
                   2462:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2463:         };
1.191     harris41 2464:     }
1.352     www      2465: #
                   2466: # Write course id database (reverse lookup) to homeserver of courses 
                   2467: # Is used in pickcourse
                   2468: #
1.840     albertel 2469:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2470:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2471:                                     $courseidbuffer{$crs_home},
                   2472:                                     $crs_home,'timeonly');
1.352     www      2473:     }
                   2474: #
                   2475: # File accesses
                   2476: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2477: #
1.449     matthew  2478:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2479:         if ($entry =~ /___count$/) {
                   2480:             my ($dom,$name);
1.807     albertel 2481:             ($dom,$name,undef)=
1.811     albertel 2482: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2483:             if (! defined($dom) || $dom eq '' || 
                   2484:                 ! defined($name) || $name eq '') {
1.620     albertel 2485:                 my $cid = $env{'request.course.id'};
                   2486:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2487:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2488:             }
1.450     matthew  2489:             my $value = $accesshash{$entry};
                   2490:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2491:             my %temphash=($url => $value);
1.449     matthew  2492:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2493:             if ($result eq 'ok') {
                   2494:                 delete $accesshash{$entry};
                   2495:             } elsif ($result eq 'unknown_cmd') {
                   2496:                 # Target server has old code running on it.
1.450     matthew  2497:                 my %temphash=($entry => $value);
1.449     matthew  2498:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2499:                     delete $accesshash{$entry};
                   2500:                 }
                   2501:             }
                   2502:         } else {
1.811     albertel 2503:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2504:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2505:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2506:                 delete $accesshash{$entry};
                   2507:             }
1.185     www      2508:         }
1.191     harris41 2509:     }
1.352     www      2510: #
                   2511: # Roles
                   2512: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2513: #
1.800     albertel 2514:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2515:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2516: 	    split(/\:/,$entry);
                   2517:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2518:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2519:                 $rudom,$runame) eq 'ok') {
                   2520: 	    delete $userrolehash{$entry};
                   2521:         }
                   2522:     }
1.662     raeburn  2523: #
                   2524: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2525: #
                   2526:     my %domrolebuffer = ();
                   2527:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2528:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2529:         if ($domrolebuffer{$rudom}) {
                   2530:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2531:                       '='.&escape($domainrolehash{$entry});
                   2532:         } else {
                   2533:             $domrolebuffer{$rudom}.=&escape($entry).
                   2534:                       '='.&escape($domainrolehash{$entry});
                   2535:         }
                   2536:         delete $domainrolehash{$entry};
                   2537:     }
                   2538:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2539: 	my %servers = &get_servers($dom,'library');
                   2540: 	foreach my $tryserver (keys(%servers)) {
                   2541: 	    unless (&reply('domroleput:'.$dom.':'.
                   2542: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2543: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2544: 	    }
1.662     raeburn  2545:         }
                   2546:     }
1.186     www      2547:     $dumpcount++;
1.157     www      2548: }
                   2549: 
                   2550: sub courselog {
                   2551:     my $what=shift;
1.158     www      2552:     $what=time.':'.$what;
1.620     albertel 2553:     unless ($env{'request.course.id'}) { return ''; }
                   2554:     $coursedombuf{$env{'request.course.id'}}=
                   2555:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2556:     $coursenumbuf{$env{'request.course.id'}}=
                   2557:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2558:     $coursehombuf{$env{'request.course.id'}}=
                   2559:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2560:     $coursedescrbuf{$env{'request.course.id'}}=
                   2561:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2562:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2563:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2564:     $courseownerbuf{$env{'request.course.id'}}=
                   2565:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2566:     $coursetypebuf{$env{'request.course.id'}}=
                   2567:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2568:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2569: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2570:     } else {
1.620     albertel 2571: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2572:     }
1.620     albertel 2573:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2574: 	&flushcourselogs();
                   2575:     }
1.158     www      2576: }
                   2577: 
                   2578: sub courseacclog {
                   2579:     my $fnsymb=shift;
1.620     albertel 2580:     unless ($env{'request.course.id'}) { return ''; }
                   2581:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2582:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2583:         $what.=':POST';
1.583     matthew  2584:         # FIXME: Probably ought to escape things....
1.800     albertel 2585: 	foreach my $key (keys(%env)) {
                   2586:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2587:                 my $formitem = $1;
                   2588:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2589:                     $what.=':'.$formitem.'='.$env{$key};
                   2590:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2591:                     $what.=':'.$formitem.'='.$env{$key};
                   2592:                 }
1.158     www      2593:             }
1.191     harris41 2594:         }
1.583     matthew  2595:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2596:         # FIXME: We should not be depending on a form parameter that someone
                   2597:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2598:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2599:             $what.= ':POST';
                   2600:             # FIXME: Probably ought to escape things....
                   2601:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2602:                                  'crsdiscuss') {
1.620     albertel 2603:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2604:             }
                   2605:         }
1.158     www      2606:     }
                   2607:     &courselog($what);
1.149     www      2608: }
                   2609: 
1.185     www      2610: sub countacc {
                   2611:     my $url=&declutter(shift);
1.458     matthew  2612:     return if (! defined($url) || $url eq '');
1.620     albertel 2613:     unless ($env{'request.course.id'}) { return ''; }
                   2614:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2615:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2616:     $accesshash{$key}++;
1.185     www      2617: }
1.349     www      2618: 
1.361     www      2619: sub linklog {
                   2620:     my ($from,$to)=@_;
                   2621:     $from=&declutter($from);
                   2622:     $to=&declutter($to);
                   2623:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2624:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2625: }
                   2626:   
1.349     www      2627: sub userrolelog {
                   2628:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2629:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2630:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2631:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2632:         ($trole=~/^ta/)) {
1.350     www      2633:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2634:        $userrolehash
                   2635:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2636:                     =$tend.':'.$tstart;
1.662     raeburn  2637:     }
1.898     albertel 2638:     if (($env{'request.role'} =~ /dc\./) &&
                   2639: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2640: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2641: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2642:        $userrolehash
                   2643:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2644:                     =$tend.':'.$tstart;
                   2645:     }
1.662     raeburn  2646:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2647:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2648:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2649:         ($trole=~/^sc/)) {
                   2650:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2651:        $domainrolehash
                   2652:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2653:                     = $tend.':'.$tstart;
                   2654:     }
1.351     www      2655: }
                   2656: 
1.957     raeburn  2657: sub courserolelog {
                   2658:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2659:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2660:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2661:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2662:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2663:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2664:             my $cdom = $1;
                   2665:             my $cnum = $2;
                   2666:             my $sec = $3;
                   2667:             my $namespace = 'rolelog';
                   2668:             my %storehash = (
                   2669:                                role    => $trole,
                   2670:                                start   => $tstart,
                   2671:                                end     => $tend,
                   2672:                                selfenroll => $selfenroll,
                   2673:                                context    => $context,
                   2674:                             );
                   2675:             if ($trole eq 'gr') {
                   2676:                 $namespace = 'groupslog';
                   2677:                 $storehash{'group'} = $sec;
                   2678:             } else {
                   2679:                 $storehash{'section'} = $sec;
                   2680:             }
                   2681:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2682:         }
                   2683:     }
                   2684:     return;
                   2685: }
                   2686: 
1.351     www      2687: sub get_course_adv_roles {
1.948     raeburn  2688:     my ($cid,$codes) = @_;
1.620     albertel 2689:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2690:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2691:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2692:     my %nothide=();
1.800     albertel 2693:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2694:         if ($user !~ /:/) {
                   2695: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2696:         } else {
                   2697:             $nothide{$user}=1;
                   2698:         }
1.470     www      2699:     }
1.351     www      2700:     my %returnhash=();
                   2701:     my %dumphash=
                   2702:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2703:     my $now=time;
1.800     albertel 2704:     foreach my $entry (keys %dumphash) {
                   2705: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2706:         if (($tstart) && ($tstart<0)) { next; }
                   2707:         if (($tend) && ($tend<$now)) { next; }
                   2708:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2709:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2710: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2711: 	if ((&privileged($username,$domain)) && 
                   2712: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2713: 	if ($role eq 'cr') { next; }
1.948     raeburn  2714:         if ($codes) {
                   2715:             if ($section) { $role .= ':'.$section; }
                   2716:             if ($returnhash{$role}) {
                   2717:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2718:             } else {
                   2719:                 $returnhash{$role}=$username.':'.$domain;
                   2720:             }
1.351     www      2721:         } else {
1.988     raeburn  2722:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2723:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2724:             if ($returnhash{$key}) {
                   2725: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2726:             } else {
                   2727:                 $returnhash{$key}=$username.':'.$domain;
                   2728:             }
1.351     www      2729:         }
1.948     raeburn  2730:     }
1.400     www      2731:     return %returnhash;
                   2732: }
                   2733: 
                   2734: sub get_my_roles {
1.937     raeburn  2735:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2736:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2737:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2738:     my (%dumphash,%nothide);
1.858     raeburn  2739:     if ($context eq 'userroles') { 
                   2740:         %dumphash = &dump('roles',$udom,$uname);
                   2741:     } else {
                   2742:         %dumphash=
1.400     www      2743:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2744:         if ($hidepriv) {
                   2745:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2746:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2747:                 if ($user !~ /:/) {
                   2748:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2749:                 } else {
                   2750:                     $nothide{$user} = 1;
                   2751:                 }
                   2752:             }
                   2753:         }
1.858     raeburn  2754:     }
1.400     www      2755:     my %returnhash=();
                   2756:     my $now=time;
1.800     albertel 2757:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2758:         my ($role,$tend,$tstart);
                   2759:         if ($context eq 'userroles') {
                   2760: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2761:         } else {
                   2762:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2763:         }
1.400     www      2764:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2765:         my $status = 'active';
1.939     raeburn  2766:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2767:             $status = 'previous';
                   2768:         } 
                   2769:         if (($tstart) && ($now<$tstart)) {
                   2770:             $status = 'future';
                   2771:         }
                   2772:         if (ref($types) eq 'ARRAY') {
                   2773:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2774:                 next;
                   2775:             } 
                   2776:         } else {
                   2777:             if ($status ne 'active') {
                   2778:                 next;
                   2779:             }
                   2780:         }
1.867     raeburn  2781:         my ($rolecode,$username,$domain,$section,$area);
                   2782:         if ($context eq 'userroles') {
                   2783:             ($area,$rolecode) = split(/_/,$entry);
                   2784:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2785:         } else {
                   2786:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2787:         }
1.832     raeburn  2788:         if (ref($roledoms) eq 'ARRAY') {
                   2789:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2790:                 next;
                   2791:             }
                   2792:         }
                   2793:         if (ref($roles) eq 'ARRAY') {
                   2794:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2795:                 if ($role =~ /^cr\//) {
                   2796:                     if (!grep(/^cr$/,@{$roles})) {
                   2797:                         next;
                   2798:                     }
                   2799:                 } else {
                   2800:                     next;
                   2801:                 }
1.832     raeburn  2802:             }
1.867     raeburn  2803:         }
1.937     raeburn  2804:         if ($hidepriv) {
                   2805:             if ((&privileged($username,$domain)) &&
                   2806:                 (!$nothide{$username.':'.$domain})) { 
                   2807:                 next;
                   2808:             }
                   2809:         }
1.933     raeburn  2810:         if ($withsec) {
                   2811:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2812:                 $tstart.':'.$tend;
                   2813:         } else {
                   2814:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2815:         }
1.832     raeburn  2816:     }
1.373     www      2817:     return %returnhash;
1.399     www      2818: }
                   2819: 
                   2820: # ----------------------------------------------------- Frontpage Announcements
                   2821: #
                   2822: #
                   2823: 
                   2824: sub postannounce {
                   2825:     my ($server,$text)=@_;
1.844     albertel 2826:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2827:     unless ($text=~/\w/) { $text=''; }
                   2828:     return &reply('setannounce:'.&escape($text),$server);
                   2829: }
                   2830: 
                   2831: sub getannounce {
1.448     albertel 2832: 
                   2833:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2834: 	my $announcement='';
1.800     albertel 2835: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2836: 	close($fh);
1.399     www      2837: 	if ($announcement=~/\w/) { 
                   2838: 	    return 
                   2839:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2840:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2841: 	} else {
                   2842: 	    return '';
                   2843: 	}
                   2844:     } else {
                   2845: 	return '';
                   2846:     }
1.351     www      2847: }
1.353     www      2848: 
                   2849: # ---------------------------------------------------------- Course ID routines
                   2850: # Deal with domain's nohist_courseid.db files
                   2851: #
                   2852: 
                   2853: sub courseidput {
1.921     raeburn  2854:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2855:     my $outcome;
                   2856:     if ($caller eq 'timeonly') {
                   2857:         my $cids = '';
                   2858:         foreach my $item (keys(%$storehash)) {
                   2859:             $cids.=&escape($item).'&';
                   2860:         }
                   2861:         $cids=~s/\&$//;
                   2862:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2863:                           $coursehome);       
                   2864:     } else {
                   2865:         my $items = '';
                   2866:         foreach my $item (keys(%$storehash)) {
                   2867:             $items.= &escape($item).'='.
                   2868:                      &freeze_escape($$storehash{$item}).'&';
                   2869:         }
                   2870:         $items=~s/\&$//;
                   2871:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2872:                           $coursehome);
1.918     raeburn  2873:     }
                   2874:     if ($outcome eq 'unknown_cmd') {
                   2875:         my $what;
                   2876:         foreach my $cid (keys(%$storehash)) {
                   2877:             $what .= &escape($cid).'=';
1.921     raeburn  2878:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2879:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2880:             }
                   2881:             $what =~ s/\:$/&/;
                   2882:         }
                   2883:         $what =~ s/\&$//;  
                   2884:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2885:     } else {
                   2886:         return $outcome;
                   2887:     }
1.353     www      2888: }
                   2889: 
                   2890: sub courseiddump {
1.921     raeburn  2891:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2892:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2893:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2894:     my $as_hash = 1;
                   2895:     my %returnhash;
                   2896:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2897:     my %libserv = &all_library();
                   2898:     foreach my $tryserver (keys(%libserv)) {
                   2899:         if ( (  $hostidflag == 1 
                   2900: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2901: 	     || (!defined($hostidflag)) ) {
                   2902: 
1.918     raeburn  2903: 	    if (($domfilter eq '') ||
                   2904: 		(&host_domain($tryserver) eq $domfilter)) {
                   2905:                 my $rep = 
                   2906:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2907:                          $sincefilter.':'.&escape($descfilter).':'.
                   2908:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2909:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2910:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2911:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2912:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2913:                 my @pairs=split(/\&/,$rep);
                   2914:                 foreach my $item (@pairs) {
                   2915:                     my ($key,$value)=split(/\=/,$item,2);
                   2916:                     $key = &unescape($key);
                   2917:                     next if ($key =~ /^error: 2 /);
                   2918:                     my $result = &thaw_unescape($value);
                   2919:                     if (ref($result) eq 'HASH') {
                   2920:                         $returnhash{$key}=$result;
                   2921:                     } else {
1.921     raeburn  2922:                         my @responses = split(/:/,$value);
                   2923:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2924:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2925:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2926:                         }
                   2927:                     } 
1.353     www      2928:                 }
                   2929:             }
                   2930:         }
                   2931:     }
                   2932:     return %returnhash;
                   2933: }
                   2934: 
1.658     raeburn  2935: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2936: 
                   2937: sub dcmailput {
1.685     raeburn  2938:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2939:     my $status = &Apache::lonnet::critical(
1.740     www      2940:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2941:        &escape($message),$server);
1.662     raeburn  2942:     return $status;
                   2943: }
                   2944: 
1.658     raeburn  2945: sub dcmaildump {
                   2946:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2947:     my %returnhash=();
1.846     albertel 2948: 
                   2949:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2950:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2951:                                                          &escape($enddate).':';
                   2952: 	my @esc_senders=map { &escape($_)} @$senders;
                   2953: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2954: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2955:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2956:             if (($key) && ($value)) {
                   2957:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2958:             }
                   2959:         }
                   2960:     }
                   2961:     return %returnhash;
                   2962: }
1.662     raeburn  2963: # ---------------------------------------------------------- Domain roles
                   2964: 
                   2965: sub get_domain_roles {
                   2966:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2967:     if (undef($startdate) || $startdate eq '') {
                   2968:         $startdate = '.';
                   2969:     }
                   2970:     if (undef($enddate) || $enddate eq '') {
                   2971:         $enddate = '.';
                   2972:     }
1.922     raeburn  2973:     my $rolelist;
                   2974:     if (ref($roles) eq 'ARRAY') {
                   2975:         $rolelist = join(':',@{$roles});
                   2976:     }
1.662     raeburn  2977:     my %personnel = ();
1.841     albertel 2978: 
                   2979:     my %servers = &get_servers($dom,'library');
                   2980:     foreach my $tryserver (keys(%servers)) {
                   2981: 	%{$personnel{$tryserver}}=();
                   2982: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2983: 					    &escape($startdate).':'.
                   2984: 					    &escape($enddate).':'.
                   2985: 					    &escape($rolelist), $tryserver))) {
                   2986: 	    my ($key,$value) = split(/\=/,$line,2);
                   2987: 	    if (($key) && ($value)) {
                   2988: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2989: 	    }
                   2990: 	}
1.662     raeburn  2991:     }
                   2992:     return %personnel;
                   2993: }
1.658     raeburn  2994: 
1.149     www      2995: # ----------------------------------------------------------- Check out an item
                   2996: 
1.504     albertel 2997: sub get_first_access {
                   2998:     my ($type,$argsymb)=@_;
1.790     albertel 2999:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3000:     if ($argsymb) { $symb=$argsymb; }
                   3001:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3002:     if ($type eq 'course') {
                   3003: 	$res='course';
                   3004:     } elsif ($type eq 'map') {
1.588     albertel 3005: 	$res=&symbread($map);
                   3006:     } else {
                   3007: 	$res=$symb;
                   3008:     }
                   3009:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3010:     return $times{"$courseid\0$res"};
1.504     albertel 3011: }
                   3012: 
                   3013: sub set_first_access {
                   3014:     my ($type)=@_;
1.790     albertel 3015:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3016:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3017:     if ($type eq 'course') {
                   3018: 	$res='course';
                   3019:     } elsif ($type eq 'map') {
1.588     albertel 3020: 	$res=&symbread($map);
                   3021:     } else {
                   3022: 	$res=$symb;
                   3023:     }
                   3024:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3025:     if (!$firstaccess) {
1.588     albertel 3026: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3027:     }
                   3028:     return 'already_set';
1.504     albertel 3029: }
                   3030: 
1.149     www      3031: sub checkout {
                   3032:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3033:     my $now=time;
                   3034:     my $lonhost=$perlvar{'lonHostID'};
                   3035:     my $infostr=&escape(
1.234     www      3036:                  'CHECKOUTTOKEN&'.
1.149     www      3037:                  $tuname.'&'.
                   3038:                  $tudom.'&'.
                   3039:                  $tcrsid.'&'.
                   3040:                  $symb.'&'.
                   3041: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3042:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3043:     if ($token=~/^error\:/) { 
1.672     albertel 3044:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3045:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3046:                  "</font>");
                   3047:         return ''; 
                   3048:     }
                   3049: 
1.149     www      3050:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3051:     $token=~tr/a-z/A-Z/;
                   3052: 
1.153     www      3053:     my %infohash=('resource.0.outtoken' => $token,
                   3054:                   'resource.0.checkouttime' => $now,
                   3055:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3056: 
                   3057:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3058:        return '';
1.151     www      3059:     } else {
1.672     albertel 3060:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3061:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3062:                  "</font>");
1.149     www      3063:     }    
                   3064: 
                   3065:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3066:                          &escape('Checkout '.$infostr.' - '.
                   3067:                                                  $token)) ne 'ok') {
                   3068: 	return '';
1.151     www      3069:     } else {
1.672     albertel 3070:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3071:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3072:                  "</font>");
1.149     www      3073:     }
1.151     www      3074:     return $token;
1.149     www      3075: }
                   3076: 
                   3077: # ------------------------------------------------------------ Check in an item
                   3078: 
                   3079: sub checkin {
                   3080:     my $token=shift;
1.150     www      3081:     my $now=time;
                   3082:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3083:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3084:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3085:     $dtoken=~s/\W/\_/g;
1.234     www      3086:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3087:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3088: 
1.154     www      3089:     unless (($tuname) && ($tudom)) {
                   3090:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3091:         return '';
                   3092:     }
                   3093:     
                   3094:     unless (&allowed('mgr',$tcrsid)) {
                   3095:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3096:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3097:         return '';
                   3098:     }
                   3099: 
1.153     www      3100:     my %infohash=('resource.0.intoken' => $token,
                   3101:                   'resource.0.checkintime' => $now,
                   3102:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3103: 
                   3104:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3105:        return '';
                   3106:     }    
                   3107: 
                   3108:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3109:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3110: 	return '';
                   3111:     }
                   3112: 
                   3113:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3114: }
                   3115: 
                   3116: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3117: 
                   3118: sub expirespread {
                   3119:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3120:     my $cid=$env{'request.course.id'}; 
1.110     www      3121:     if ($cid) {
                   3122:        my $now=time;
                   3123:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3124:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3125:                             $env{'course.'.$cid.'.num'}.
1.110     www      3126: 	        	    ':nohist_expirationdates:'.
                   3127:                             &escape($key).'='.$now,
1.620     albertel 3128:                             $env{'course.'.$cid.'.home'})
1.110     www      3129:     }
                   3130:     return 'ok';
1.14      www      3131: }
                   3132: 
1.109     www      3133: # ----------------------------------------------------- Devalidate Spreadsheets
                   3134: 
                   3135: sub devalidate {
1.325     www      3136:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3137:     my $cid=$env{'request.course.id'}; 
1.109     www      3138:     if ($cid) {
1.391     matthew  3139:         # delete the stored spreadsheets for
                   3140:         # - the student level sheet of this user in course's homespace
                   3141:         # - the assessment level sheet for this resource 
                   3142:         #   for this user in user's homespace
1.553     albertel 3143: 	# - current conditional state info
1.325     www      3144: 	my $key=$uname.':'.$udom.':';
1.109     www      3145:         my $status=
1.299     matthew  3146: 	    &del('nohist_calculatedsheets',
1.391     matthew  3147: 		 [$key.'studentcalc:'],
1.620     albertel 3148: 		 $env{'course.'.$cid.'.domain'},
                   3149: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3150: 		.' '.
                   3151: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3152: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3153:         unless ($status eq 'ok ok') {
                   3154:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3155:                     $uname.' at '.$udom.' for '.
1.109     www      3156: 		    $symb.': '.$status);
1.133     albertel 3157:         }
1.553     albertel 3158: 	&delenv('user.state.'.$cid);
1.109     www      3159:     }
                   3160: }
                   3161: 
1.265     albertel 3162: sub get_scalar {
                   3163:     my ($string,$end) = @_;
                   3164:     my $value;
                   3165:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3166: 	$value = $1;
                   3167:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3168: 	$value = $1;
                   3169:     }
                   3170:     return &unescape($value);
                   3171: }
                   3172: 
                   3173: sub array2str {
                   3174:   my (@array) = @_;
                   3175:   my $result=&arrayref2str(\@array);
                   3176:   $result=~s/^__ARRAY_REF__//;
                   3177:   $result=~s/__END_ARRAY_REF__$//;
                   3178:   return $result;
                   3179: }
                   3180: 
1.204     albertel 3181: sub arrayref2str {
                   3182:   my ($arrayref) = @_;
1.265     albertel 3183:   my $result='__ARRAY_REF__';
1.204     albertel 3184:   foreach my $elem (@$arrayref) {
1.265     albertel 3185:     if(ref($elem) eq 'ARRAY') {
                   3186:       $result.=&arrayref2str($elem).'&';
                   3187:     } elsif(ref($elem) eq 'HASH') {
                   3188:       $result.=&hashref2str($elem).'&';
                   3189:     } elsif(ref($elem)) {
                   3190:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3191:     } else {
                   3192:       $result.=&escape($elem).'&';
                   3193:     }
                   3194:   }
                   3195:   $result=~s/\&$//;
1.265     albertel 3196:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3197:   return $result;
                   3198: }
                   3199: 
1.168     albertel 3200: sub hash2str {
1.204     albertel 3201:   my (%hash) = @_;
                   3202:   my $result=&hashref2str(\%hash);
1.265     albertel 3203:   $result=~s/^__HASH_REF__//;
                   3204:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3205:   return $result;
                   3206: }
                   3207: 
                   3208: sub hashref2str {
                   3209:   my ($hashref)=@_;
1.265     albertel 3210:   my $result='__HASH_REF__';
1.800     albertel 3211:   foreach my $key (sort(keys(%$hashref))) {
                   3212:     if (ref($key) eq 'ARRAY') {
                   3213:       $result.=&arrayref2str($key).'=';
                   3214:     } elsif (ref($key) eq 'HASH') {
                   3215:       $result.=&hashref2str($key).'=';
                   3216:     } elsif (ref($key)) {
1.265     albertel 3217:       $result.='=';
1.800     albertel 3218:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3219:     } else {
1.800     albertel 3220: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3221:     }
                   3222: 
1.800     albertel 3223:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3224:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3225:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3226:       $result.=&hashref2str($hashref->{$key}).'&';
                   3227:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3228:        $result.='&';
1.800     albertel 3229:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3230:     } else {
1.800     albertel 3231:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3232:     }
                   3233:   }
1.168     albertel 3234:   $result=~s/\&$//;
1.265     albertel 3235:   $result .= '__END_HASH_REF__';
1.168     albertel 3236:   return $result;
                   3237: }
                   3238: 
                   3239: sub str2hash {
1.265     albertel 3240:     my ($string)=@_;
                   3241:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3242:     return %$hash;
                   3243: }
                   3244: 
                   3245: sub str2hashref {
1.168     albertel 3246:   my ($string) = @_;
1.265     albertel 3247: 
                   3248:   my %hash;
                   3249: 
                   3250:   if($string !~ /^__HASH_REF__/) {
                   3251:       if (! ($string eq '' || !defined($string))) {
                   3252: 	  $hash{'error'}='Not hash reference';
                   3253:       }
                   3254:       return (\%hash, $string);
                   3255:   }
                   3256: 
                   3257:   $string =~ s/^__HASH_REF__//;
                   3258: 
                   3259:   while($string !~ /^__END_HASH_REF__/) {
                   3260:       #key
                   3261:       my $key='';
                   3262:       if($string =~ /^__HASH_REF__/) {
                   3263:           ($key, $string)=&str2hashref($string);
                   3264:           if(defined($key->{'error'})) {
                   3265:               $hash{'error'}='Bad data';
                   3266:               return (\%hash, $string);
                   3267:           }
                   3268:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3269:           ($key, $string)=&str2arrayref($string);
                   3270:           if($key->[0] eq 'Array reference error') {
                   3271:               $hash{'error'}='Bad data';
                   3272:               return (\%hash, $string);
                   3273:           }
                   3274:       } else {
                   3275:           $string =~ s/^(.*?)=//;
1.267     albertel 3276: 	  $key=&unescape($1);
1.265     albertel 3277:       }
                   3278:       $string =~ s/^=//;
                   3279: 
                   3280:       #value
                   3281:       my $value='';
                   3282:       if($string =~ /^__HASH_REF__/) {
                   3283:           ($value, $string)=&str2hashref($string);
                   3284:           if(defined($value->{'error'})) {
                   3285:               $hash{'error'}='Bad data';
                   3286:               return (\%hash, $string);
                   3287:           }
                   3288:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3289:           ($value, $string)=&str2arrayref($string);
                   3290:           if($value->[0] eq 'Array reference error') {
                   3291:               $hash{'error'}='Bad data';
                   3292:               return (\%hash, $string);
                   3293:           }
                   3294:       } else {
                   3295: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3296:       }
                   3297:       $string =~ s/^&//;
                   3298: 
                   3299:       $hash{$key}=$value;
1.204     albertel 3300:   }
1.265     albertel 3301: 
                   3302:   $string =~ s/^__END_HASH_REF__//;
                   3303: 
                   3304:   return (\%hash, $string);
1.204     albertel 3305: }
                   3306: 
                   3307: sub str2array {
1.265     albertel 3308:     my ($string)=@_;
                   3309:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3310:     return @$array;
                   3311: }
                   3312: 
                   3313: sub str2arrayref {
1.204     albertel 3314:   my ($string) = @_;
1.265     albertel 3315:   my @array;
                   3316: 
                   3317:   if($string !~ /^__ARRAY_REF__/) {
                   3318:       if (! ($string eq '' || !defined($string))) {
                   3319: 	  $array[0]='Array reference error';
                   3320:       }
                   3321:       return (\@array, $string);
                   3322:   }
                   3323: 
                   3324:   $string =~ s/^__ARRAY_REF__//;
                   3325: 
                   3326:   while($string !~ /^__END_ARRAY_REF__/) {
                   3327:       my $value='';
                   3328:       if($string =~ /^__HASH_REF__/) {
                   3329:           ($value, $string)=&str2hashref($string);
                   3330:           if(defined($value->{'error'})) {
                   3331:               $array[0] ='Array reference error';
                   3332:               return (\@array, $string);
                   3333:           }
                   3334:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3335:           ($value, $string)=&str2arrayref($string);
                   3336:           if($value->[0] eq 'Array reference error') {
                   3337:               $array[0] ='Array reference error';
                   3338:               return (\@array, $string);
                   3339:           }
                   3340:       } else {
                   3341: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3342:       }
                   3343:       $string =~ s/^&//;
                   3344: 
                   3345:       push(@array, $value);
1.191     harris41 3346:   }
1.265     albertel 3347: 
                   3348:   $string =~ s/^__END_ARRAY_REF__//;
                   3349: 
                   3350:   return (\@array, $string);
1.168     albertel 3351: }
                   3352: 
1.167     albertel 3353: # -------------------------------------------------------------------Temp Store
                   3354: 
1.168     albertel 3355: sub tmpreset {
                   3356:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3357:   if (!$symb) {
                   3358:     $symb=&symbread();
1.620     albertel 3359:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3360:   }
                   3361:   $symb=escape($symb);
                   3362: 
1.620     albertel 3363:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3364:   $namespace=~s/\//\_/g;
                   3365:   $namespace=~s/\W//g;
                   3366: 
1.620     albertel 3367:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3368:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3369:   if ($domain eq 'public' && $stuname eq 'public') {
                   3370:       $stuname=$ENV{'REMOTE_ADDR'};
                   3371:   }
1.168     albertel 3372:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3373:   my %hash;
                   3374:   if (tie(%hash,'GDBM_File',
                   3375: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3376: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3377:     foreach my $key (keys %hash) {
1.180     albertel 3378:       if ($key=~ /:$symb/) {
1.168     albertel 3379: 	delete($hash{$key});
                   3380:       }
                   3381:     }
                   3382:   }
                   3383: }
                   3384: 
1.167     albertel 3385: sub tmpstore {
1.168     albertel 3386:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3387: 
                   3388:   if (!$symb) {
                   3389:     $symb=&symbread();
1.620     albertel 3390:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3391:   }
                   3392:   $symb=escape($symb);
                   3393: 
                   3394:   if (!$namespace) {
                   3395:     # I don't think we would ever want to store this for a course.
                   3396:     # it seems this will only be used if we don't have a course.
1.620     albertel 3397:     #$namespace=$env{'request.course.id'};
1.168     albertel 3398:     #if (!$namespace) {
1.620     albertel 3399:       $namespace=$env{'request.state'};
1.168     albertel 3400:     #}
                   3401:   }
                   3402:   $namespace=~s/\//\_/g;
                   3403:   $namespace=~s/\W//g;
1.620     albertel 3404:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3405:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3406:   if ($domain eq 'public' && $stuname eq 'public') {
                   3407:       $stuname=$ENV{'REMOTE_ADDR'};
                   3408:   }
1.168     albertel 3409:   my $now=time;
                   3410:   my %hash;
                   3411:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3412:   if (tie(%hash,'GDBM_File',
                   3413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3414: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3415:     $hash{"version:$symb"}++;
                   3416:     my $version=$hash{"version:$symb"};
                   3417:     my $allkeys=''; 
                   3418:     foreach my $key (keys(%$storehash)) {
                   3419:       $allkeys.=$key.':';
1.591     albertel 3420:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3421:     }
                   3422:     $hash{"$version:$symb:timestamp"}=$now;
                   3423:     $allkeys.='timestamp';
                   3424:     $hash{"$version:keys:$symb"}=$allkeys;
                   3425:     if (untie(%hash)) {
                   3426:       return 'ok';
                   3427:     } else {
                   3428:       return "error:$!";
                   3429:     }
                   3430:   } else {
                   3431:     return "error:$!";
                   3432:   }
                   3433: }
1.167     albertel 3434: 
1.168     albertel 3435: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3436: 
1.168     albertel 3437: sub tmprestore {
                   3438:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3439: 
1.168     albertel 3440:   if (!$symb) {
                   3441:     $symb=&symbread();
1.620     albertel 3442:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3443:   }
                   3444:   $symb=escape($symb);
                   3445: 
1.620     albertel 3446:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3447: 
1.620     albertel 3448:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3449:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3450:   if ($domain eq 'public' && $stuname eq 'public') {
                   3451:       $stuname=$ENV{'REMOTE_ADDR'};
                   3452:   }
1.168     albertel 3453:   my %returnhash;
                   3454:   $namespace=~s/\//\_/g;
                   3455:   $namespace=~s/\W//g;
                   3456:   my %hash;
                   3457:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3458:   if (tie(%hash,'GDBM_File',
                   3459: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3460: 	  &GDBM_READER(),0640)) {
1.168     albertel 3461:     my $version=$hash{"version:$symb"};
                   3462:     $returnhash{'version'}=$version;
                   3463:     my $scope;
                   3464:     for ($scope=1;$scope<=$version;$scope++) {
                   3465:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3466:       my @keys=split(/:/,$vkeys);
                   3467:       my $key;
                   3468:       $returnhash{"$scope:keys"}=$vkeys;
                   3469:       foreach $key (@keys) {
1.591     albertel 3470: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3471: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3472:       }
                   3473:     }
1.168     albertel 3474:     if (!(untie(%hash))) {
                   3475:       return "error:$!";
                   3476:     }
                   3477:   } else {
                   3478:     return "error:$!";
                   3479:   }
                   3480:   return %returnhash;
1.167     albertel 3481: }
                   3482: 
1.9       www      3483: # ----------------------------------------------------------------------- Store
                   3484: 
                   3485: sub store {
1.124     www      3486:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3487:     my $home='';
                   3488: 
1.168     albertel 3489:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3490: 
1.213     www      3491:     $symb=&symbclean($symb);
1.122     albertel 3492:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3493: 
1.620     albertel 3494:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3495:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3496: 
                   3497:     &devalidate($symb,$stuname,$domain);
1.109     www      3498: 
                   3499:     $symb=escape($symb);
1.187     www      3500:     if (!$namespace) { 
1.620     albertel 3501:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3502:           return ''; 
                   3503:        } 
                   3504:     }
1.620     albertel 3505:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3506: 
                   3507:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3508:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3509: 
1.12      www      3510:     my $namevalue='';
1.800     albertel 3511:     foreach my $key (keys(%$storehash)) {
                   3512:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3513:     }
1.12      www      3514:     $namevalue=~s/\&$//;
1.187     www      3515:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3516:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3517: }
                   3518: 
1.47      www      3519: # -------------------------------------------------------------- Critical Store
                   3520: 
                   3521: sub cstore {
1.124     www      3522:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3523:     my $home='';
                   3524: 
1.168     albertel 3525:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3526: 
1.213     www      3527:     $symb=&symbclean($symb);
1.122     albertel 3528:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3529: 
1.620     albertel 3530:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3531:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3532: 
                   3533:     &devalidate($symb,$stuname,$domain);
1.109     www      3534: 
                   3535:     $symb=escape($symb);
1.187     www      3536:     if (!$namespace) { 
1.620     albertel 3537:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3538:           return ''; 
                   3539:        } 
                   3540:     }
1.620     albertel 3541:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3542: 
                   3543:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3544:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3545: 
1.47      www      3546:     my $namevalue='';
1.800     albertel 3547:     foreach my $key (keys(%$storehash)) {
                   3548:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3549:     }
1.47      www      3550:     $namevalue=~s/\&$//;
1.187     www      3551:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3552:     return critical
                   3553:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3554: }
                   3555: 
1.9       www      3556: # --------------------------------------------------------------------- Restore
                   3557: 
                   3558: sub restore {
1.124     www      3559:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3560:     my $home='';
                   3561: 
1.168     albertel 3562:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3563: 
1.122     albertel 3564:     if (!$symb) {
                   3565:       unless ($symb=escape(&symbread())) { return ''; }
                   3566:     } else {
1.213     www      3567:       $symb=&escape(&symbclean($symb));
1.122     albertel 3568:     }
1.188     www      3569:     if (!$namespace) { 
1.620     albertel 3570:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3571:           return ''; 
                   3572:        } 
                   3573:     }
1.620     albertel 3574:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3575:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3576:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3577:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3578: 
1.12      www      3579:     my %returnhash=();
1.800     albertel 3580:     foreach my $line (split(/\&/,$answer)) {
                   3581: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3582:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3583:     }
1.75      www      3584:     my $version;
                   3585:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3586:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3587:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3588:        }
1.75      www      3589:     }
1.13      www      3590:     return %returnhash;
1.34      www      3591: }
                   3592: 
                   3593: # ---------------------------------------------------------- Course Description
                   3594: 
                   3595: sub coursedescription {
1.731     albertel 3596:     my ($courseid,$args)=@_;
1.34      www      3597:     $courseid=~s/^\///;
1.49      www      3598:     $courseid=~s/\_/\//g;
1.34      www      3599:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3600:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3601:     my $normalid=$cdomain.'_'.$cnum;
                   3602:     # need to always cache even if we get errors otherwise we keep 
                   3603:     # trying and trying and trying to get the course description.
                   3604:     my %envhash=();
                   3605:     my %returnhash=();
1.731     albertel 3606:     
                   3607:     my $expiretime=600;
                   3608:     if ($env{'request.course.id'} eq $normalid) {
                   3609: 	$expiretime=120;
                   3610:     }
                   3611: 
                   3612:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3613:     if (!$args->{'freshen_cache'}
                   3614: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3615: 	foreach my $key (keys(%env)) {
                   3616: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3617: 	    my ($setting) = $1;
                   3618: 	    $returnhash{$setting} = $env{$key};
                   3619: 	}
                   3620: 	return %returnhash;
                   3621:     }
                   3622: 
                   3623:     # get the data agin
                   3624:     if (!$args->{'one_time'}) {
                   3625: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3626:     }
1.811     albertel 3627: 
1.34      www      3628:     if ($chome ne 'no_host') {
1.302     albertel 3629:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3630:        if (!exists($returnhash{'con_lost'})) {
                   3631:            $returnhash{'home'}= $chome;
                   3632: 	   $returnhash{'domain'} = $cdomain;
                   3633: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3634:            if (!defined($returnhash{'type'})) {
                   3635:                $returnhash{'type'} = 'Course';
                   3636:            }
1.130     albertel 3637:            while (my ($name,$value) = each %returnhash) {
1.53      www      3638:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3639:            }
1.270     www      3640:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3641:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3642: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3643:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3644:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3645:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3646:        }
                   3647:     }
1.731     albertel 3648:     if (!$args->{'one_time'}) {
1.949     raeburn  3649: 	&appenv(\%envhash);
1.731     albertel 3650:     }
1.302     albertel 3651:     return %returnhash;
1.461     www      3652: }
                   3653: 
                   3654: # -------------------------------------------------See if a user is privileged
                   3655: 
                   3656: sub privileged {
                   3657:     my ($username,$domain)=@_;
                   3658:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3659: 			&homeserver($username,$domain));
                   3660:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3661:     my $now=time;
                   3662:     if ($rolesdump ne '') {
1.800     albertel 3663:         foreach my $entry (split(/&/,$rolesdump)) {
                   3664: 	    if ($entry!~/^rolesdef_/) {
                   3665: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3666: 		$area=~s/\_\w\w$//;
                   3667: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3668: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3669: 		    my $active=1;
                   3670: 		    if ($tend) {
                   3671: 			if ($tend<$now) { $active=0; }
                   3672: 		    }
                   3673: 		    if ($tstart) {
                   3674: 			if ($tstart>$now) { $active=0; }
                   3675: 		    }
                   3676: 		    if ($active) { return 1; }
                   3677: 		}
                   3678: 	    }
                   3679: 	}
                   3680:     }
                   3681:     return 0;
1.9       www      3682: }
1.1       albertel 3683: 
1.103     harris41 3684: # -------------------------------------------------------- Get user privileges
1.11      www      3685: 
                   3686: sub rolesinit {
                   3687:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3688:     my %userroles;
1.11      www      3689:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3690:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3691:     my %allroles=();
1.678     raeburn  3692:     my %allgroups=();   
1.11      www      3693:     my $now=time;
1.966     raeburn  3694:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3695:     my $group_privs;
1.11      www      3696: 
                   3697:     if ($rolesdump ne '') {
1.800     albertel 3698:         foreach my $entry (split(/&/,$rolesdump)) {
                   3699: 	  if ($entry!~/^rolesdef_/) {
                   3700:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3701: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3702:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3703: 	    if ($role=~/^cr/) { 
1.807     albertel 3704: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3705: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3706: 		    ($tend,$tstart)=split('_',$trest);
                   3707: 		} else {
                   3708: 		    $trole=$role;
                   3709: 		}
1.678     raeburn  3710:             } elsif ($role =~ m|^gr/|) {
                   3711:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3712:                 ($trole,$group_privs) = split(/\//,$trole);
                   3713:                 $group_privs = &unescape($group_privs);
1.587     albertel 3714: 	    } else {
                   3715: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3716: 	    }
1.743     albertel 3717: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3718: 					 $username);
                   3719: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3720:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3721:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3722:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3723: 		my $spec=$trole.'.'.$area;
                   3724: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3725: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3726:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3727:                 } elsif ($trole eq 'gr') {
                   3728:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3729: 		} else {
1.567     raeburn  3730:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3731: 		}
1.12      www      3732:             }
1.662     raeburn  3733:           }
1.191     harris41 3734:         }
1.743     albertel 3735:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3736:         $userroles{'user.adv'}    = $adv;
                   3737: 	$userroles{'user.author'} = $author;
1.620     albertel 3738:         $env{'user.adv'}=$adv;
1.11      www      3739:     }
1.743     albertel 3740:     return \%userroles;  
1.11      www      3741: }
                   3742: 
1.567     raeburn  3743: sub set_arearole {
                   3744:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3745: # log the associated role with the area
                   3746:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3747:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3748: }
                   3749: 
                   3750: sub custom_roleprivs {
                   3751:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3752:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3753:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3754:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3755:         my ($rdummy,$roledef)=
                   3756:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3757:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3758:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3759:             if (defined($syspriv)) {
                   3760:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3761:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3762:             }
                   3763:             if ($tdomain ne '') {
                   3764:                 if (defined($dompriv)) {
                   3765:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3766:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3767:                 }
                   3768:                 if (($trest ne '') && (defined($coursepriv))) {
                   3769:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3770:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3771:                 }
                   3772:             }
                   3773:         }
                   3774:     }
                   3775: }
                   3776: 
1.678     raeburn  3777: sub group_roleprivs {
                   3778:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3779:     my $access = 1;
                   3780:     my $now = time;
                   3781:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3782:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3783:     if ($access) {
1.811     albertel 3784:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3785:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3786:     }
                   3787: }
1.567     raeburn  3788: 
                   3789: sub standard_roleprivs {
                   3790:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3791:     if (defined($pr{$trole.':s'})) {
                   3792:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3793:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3794:     }
                   3795:     if ($tdomain ne '') {
                   3796:         if (defined($pr{$trole.':d'})) {
                   3797:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3798:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3799:         }
                   3800:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3801:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3802:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3803:         }
                   3804:     }
                   3805: }
                   3806: 
                   3807: sub set_userprivs {
1.678     raeburn  3808:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3809:     my $author=0;
                   3810:     my $adv=0;
1.678     raeburn  3811:     my %grouproles = ();
                   3812:     if (keys(%{$allgroups}) > 0) {
                   3813:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3814:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3815:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3816:                 $trole = $1;
                   3817:                 $area = $2;
1.681     raeburn  3818:                 $sec = $3;
                   3819:                 $extendedarea = $area.$sec;
                   3820:                 if (exists($$allgroups{$area})) {
                   3821:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3822:                         my $spec = $trole.'.'.$extendedarea;
                   3823:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3824:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3825:                     }
                   3826:                 }
                   3827:             }
                   3828:         }
                   3829:     }
1.800     albertel 3830:     foreach my $group (keys(%grouproles)) {
                   3831:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3832:     }
1.800     albertel 3833:     foreach my $role (keys(%{$allroles})) {
                   3834:         my %thesepriv;
1.941     raeburn  3835:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3836:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3837:             if ($item ne '') {
                   3838:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3839:                 if ($restrictions eq '') {
                   3840:                     $thesepriv{$privilege}='F';
                   3841:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3842:                     $thesepriv{$privilege}.=$restrictions;
                   3843:                 }
                   3844:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3845:             }
                   3846:         }
                   3847:         my $thesestr='';
1.800     albertel 3848:         foreach my $priv (keys(%thesepriv)) {
                   3849: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3850: 	}
                   3851:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3852:     }
                   3853:     return ($author,$adv);
                   3854: }
                   3855: 
1.12      www      3856: # --------------------------------------------------------------- get interface
                   3857: 
                   3858: sub get {
1.131     albertel 3859:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3860:    my $items='';
1.800     albertel 3861:    foreach my $item (@$storearr) {
                   3862:        $items.=&escape($item).'&';
1.191     harris41 3863:    }
1.12      www      3864:    $items=~s/\&$//;
1.620     albertel 3865:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3866:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3867:    my $uhome=&homeserver($uname,$udomain);
                   3868: 
1.133     albertel 3869:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3870:    my @pairs=split(/\&/,$rep);
1.273     albertel 3871:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3872:      return @pairs;
                   3873:    }
1.15      www      3874:    my %returnhash=();
1.42      www      3875:    my $i=0;
1.800     albertel 3876:    foreach my $item (@$storearr) {
                   3877:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3878:       $i++;
1.191     harris41 3879:    }
1.15      www      3880:    return %returnhash;
1.27      www      3881: }
                   3882: 
                   3883: # --------------------------------------------------------------- del interface
                   3884: 
                   3885: sub del {
1.133     albertel 3886:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3887:    my $items='';
1.800     albertel 3888:    foreach my $item (@$storearr) {
                   3889:        $items.=&escape($item).'&';
1.191     harris41 3890:    }
1.984     neumanie 3891: 
1.27      www      3892:    $items=~s/\&$//;
1.620     albertel 3893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3894:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3895:    my $uhome=&homeserver($uname,$udomain);
                   3896:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3897: }
                   3898: 
                   3899: # -------------------------------------------------------------- dump interface
                   3900: 
                   3901: sub dump {
1.755     albertel 3902:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3904:     if (!$uname) { $uname=$env{'user.name'}; }
                   3905:     my $uhome=&homeserver($uname,$udomain);
                   3906:     if ($regexp) {
                   3907: 	$regexp=&escape($regexp);
                   3908:     } else {
                   3909: 	$regexp='.';
                   3910:     }
                   3911:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3912:     my @pairs=split(/\&/,$rep);
                   3913:     my %returnhash=();
                   3914:     foreach my $item (@pairs) {
                   3915: 	my ($key,$value)=split(/=/,$item,2);
                   3916: 	$key = &unescape($key);
                   3917: 	next if ($key =~ /^error: 2 /);
                   3918: 	$returnhash{$key}=&thaw_unescape($value);
                   3919:     }
                   3920:     return %returnhash;
1.407     www      3921: }
                   3922: 
1.717     albertel 3923: # --------------------------------------------------------- dumpstore interface
                   3924: 
                   3925: sub dumpstore {
                   3926:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3928:    if (!$uname) { $uname=$env{'user.name'}; }
                   3929:    my $uhome=&homeserver($uname,$udomain);
                   3930:    if ($regexp) {
                   3931:        $regexp=&escape($regexp);
                   3932:    } else {
                   3933:        $regexp='.';
                   3934:    }
                   3935:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3936:    my @pairs=split(/\&/,$rep);
                   3937:    my %returnhash=();
                   3938:    foreach my $item (@pairs) {
                   3939:        my ($key,$value)=split(/=/,$item,2);
                   3940:        next if ($key =~ /^error: 2 /);
                   3941:        $returnhash{$key}=&thaw_unescape($value);
                   3942:    }
                   3943:    return %returnhash;
1.717     albertel 3944: }
                   3945: 
1.407     www      3946: # -------------------------------------------------------------- keys interface
                   3947: 
                   3948: sub getkeys {
                   3949:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3950:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3951:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3952:    my $uhome=&homeserver($uname,$udomain);
                   3953:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3954:    my @keyarray=();
1.800     albertel 3955:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3956:       next if ($key =~ /^error: 2 /);
1.800     albertel 3957:       push(@keyarray,&unescape($key));
1.407     www      3958:    }
                   3959:    return @keyarray;
1.318     matthew  3960: }
                   3961: 
1.319     matthew  3962: # --------------------------------------------------------------- currentdump
                   3963: sub currentdump {
1.328     matthew  3964:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3965:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3966:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3967:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3968:    my $uhome = &homeserver($sname,$sdom);
                   3969:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3970:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3971:    #
1.318     matthew  3972:    my %returnhash=();
1.319     matthew  3973:    #
                   3974:    if ($rep eq "unknown_cmd") { 
                   3975:        # an old lond will not know currentdump
                   3976:        # Do a dump and make it look like a currentdump
1.822     albertel 3977:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3978:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3979:        my %hash = @tmp;
                   3980:        @tmp=();
1.424     matthew  3981:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3982:    } else {
                   3983:        my @pairs=split(/\&/,$rep);
1.800     albertel 3984:        foreach my $pair (@pairs) {
                   3985:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3986:            my ($symb,$param) = split(/:/,$key);
                   3987:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3988:                                                         &thaw_unescape($value);
1.319     matthew  3989:        }
1.191     harris41 3990:    }
1.12      www      3991:    return %returnhash;
1.424     matthew  3992: }
                   3993: 
                   3994: sub convert_dump_to_currentdump{
                   3995:     my %hash = %{shift()};
                   3996:     my %returnhash;
                   3997:     # Code ripped from lond, essentially.  The only difference
                   3998:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3999:     # we might run in to problems with parameter names =~ /^v\./
                   4000:     while (my ($key,$value) = each(%hash)) {
                   4001:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4002: 	$symb  = &unescape($symb);
                   4003: 	$param = &unescape($param);
1.424     matthew  4004:         next if ($v eq 'version' || $symb eq 'keys');
                   4005:         next if (exists($returnhash{$symb}) &&
                   4006:                  exists($returnhash{$symb}->{$param}) &&
                   4007:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4008:         $returnhash{$symb}->{$param}=$value;
                   4009:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4010:     }
                   4011:     #
                   4012:     # Remove all of the keys in the hashes which keep track of
                   4013:     # the version of the parameter.
                   4014:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4015:         # use a foreach because we are going to delete from the hash.
                   4016:         foreach my $key (keys(%$param_hash)) {
                   4017:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4018:         }
                   4019:     }
                   4020:     return \%returnhash;
1.12      www      4021: }
                   4022: 
1.627     albertel 4023: # ------------------------------------------------------ critical inc interface
                   4024: 
                   4025: sub cinc {
                   4026:     return &inc(@_,'critical');
                   4027: }
                   4028: 
1.449     matthew  4029: # --------------------------------------------------------------- inc interface
                   4030: 
                   4031: sub inc {
1.627     albertel 4032:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4033:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4034:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4035:     my $uhome=&homeserver($uname,$udomain);
                   4036:     my $items='';
                   4037:     if (! ref($store)) {
                   4038:         # got a single value, so use that instead
                   4039:         $items = &escape($store).'=&';
                   4040:     } elsif (ref($store) eq 'SCALAR') {
                   4041:         $items = &escape($$store).'=&';        
                   4042:     } elsif (ref($store) eq 'ARRAY') {
                   4043:         $items = join('=&',map {&escape($_);} @{$store});
                   4044:     } elsif (ref($store) eq 'HASH') {
                   4045:         while (my($key,$value) = each(%{$store})) {
                   4046:             $items.= &escape($key).'='.&escape($value).'&';
                   4047:         }
                   4048:     }
                   4049:     $items=~s/\&$//;
1.627     albertel 4050:     if ($critical) {
                   4051: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4052:     } else {
                   4053: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4054:     }
1.449     matthew  4055: }
                   4056: 
1.12      www      4057: # --------------------------------------------------------------- put interface
                   4058: 
                   4059: sub put {
1.134     albertel 4060:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4062:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4063:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4064:    my $items='';
1.800     albertel 4065:    foreach my $item (keys(%$storehash)) {
                   4066:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4067:    }
1.12      www      4068:    $items=~s/\&$//;
1.134     albertel 4069:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4070: }
                   4071: 
1.631     albertel 4072: # ------------------------------------------------------------ newput interface
                   4073: 
                   4074: sub newput {
                   4075:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4077:    if (!$uname) { $uname=$env{'user.name'}; }
                   4078:    my $uhome=&homeserver($uname,$udomain);
                   4079:    my $items='';
                   4080:    foreach my $key (keys(%$storehash)) {
                   4081:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4082:    }
                   4083:    $items=~s/\&$//;
                   4084:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4085: }
                   4086: 
                   4087: # ---------------------------------------------------------  putstore interface
                   4088: 
1.524     raeburn  4089: sub putstore {
1.715     albertel 4090:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4092:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4093:    my $uhome=&homeserver($uname,$udomain);
                   4094:    my $items='';
1.715     albertel 4095:    foreach my $key (keys(%$storehash)) {
                   4096:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4097:    }
1.715     albertel 4098:    $items=~s/\&$//;
1.716     albertel 4099:    my $esc_symb=&escape($symb);
                   4100:    my $esc_v=&escape($version);
1.715     albertel 4101:    my $reply =
1.716     albertel 4102:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4103: 	      $uhome);
                   4104:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4105:        # gfall back to way things use to be done
1.715     albertel 4106:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4107: 			    $uname);
1.524     raeburn  4108:    }
1.715     albertel 4109:    return $reply;
                   4110: }
                   4111: 
                   4112: sub old_putstore {
1.716     albertel 4113:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4114:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4115:     if (!$uname) { $uname=$env{'user.name'}; }
                   4116:     my $uhome=&homeserver($uname,$udomain);
                   4117:     my %newstorehash;
1.800     albertel 4118:     foreach my $item (keys(%$storehash)) {
                   4119: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4120: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4121:     }
                   4122:     my $items='';
                   4123:     my %allitems = ();
1.800     albertel 4124:     foreach my $item (keys(%newstorehash)) {
                   4125: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4126: 	    my $key = $1.':keys:'.$2;
                   4127: 	    $allitems{$key} .= $3.':';
                   4128: 	}
1.800     albertel 4129: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4130:     }
1.800     albertel 4131:     foreach my $item (keys(%allitems)) {
                   4132: 	$allitems{$item} =~ s/\:$//;
                   4133: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4134:     }
                   4135:     $items=~s/\&$//;
                   4136:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4137: }
                   4138: 
1.47      www      4139: # ------------------------------------------------------ critical put interface
                   4140: 
                   4141: sub cput {
1.134     albertel 4142:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4144:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4145:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4146:    my $items='';
1.800     albertel 4147:    foreach my $item (keys(%$storehash)) {
                   4148:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4149:    }
1.47      www      4150:    $items=~s/\&$//;
1.134     albertel 4151:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4152: }
                   4153: 
                   4154: # -------------------------------------------------------------- eget interface
                   4155: 
                   4156: sub eget {
1.133     albertel 4157:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4158:    my $items='';
1.800     albertel 4159:    foreach my $item (@$storearr) {
                   4160:        $items.=&escape($item).'&';
1.191     harris41 4161:    }
1.12      www      4162:    $items=~s/\&$//;
1.620     albertel 4163:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4164:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4165:    my $uhome=&homeserver($uname,$udomain);
                   4166:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4167:    my @pairs=split(/\&/,$rep);
                   4168:    my %returnhash=();
1.42      www      4169:    my $i=0;
1.800     albertel 4170:    foreach my $item (@$storearr) {
                   4171:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4172:       $i++;
1.191     harris41 4173:    }
1.12      www      4174:    return %returnhash;
                   4175: }
                   4176: 
1.667     albertel 4177: # ------------------------------------------------------------ tmpput interface
                   4178: sub tmpput {
1.802     raeburn  4179:     my ($storehash,$server,$context)=@_;
1.667     albertel 4180:     my $items='';
1.800     albertel 4181:     foreach my $item (keys(%$storehash)) {
                   4182: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4183:     }
                   4184:     $items=~s/\&$//;
1.802     raeburn  4185:     if (defined($context)) {
                   4186:         $items .= ':'.&escape($context);
                   4187:     }
1.667     albertel 4188:     return &reply("tmpput:$items",$server);
                   4189: }
                   4190: 
                   4191: # ------------------------------------------------------------ tmpget interface
                   4192: sub tmpget {
1.688     albertel 4193:     my ($token,$server)=@_;
                   4194:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4195:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4196:     my %returnhash;
                   4197:     foreach my $item (split(/\&/,$rep)) {
                   4198: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4199:         next if ($key =~ /^error: 2 /);
1.667     albertel 4200: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4201:     }
                   4202:     return %returnhash;
                   4203: }
                   4204: 
1.688     albertel 4205: # ------------------------------------------------------------ tmpget interface
                   4206: sub tmpdel {
                   4207:     my ($token,$server)=@_;
                   4208:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4209:     return &reply("tmpdel:$token",$server);
                   4210: }
                   4211: 
1.765     albertel 4212: # -------------------------------------------------- portfolio access checking
                   4213: 
                   4214: sub portfolio_access {
1.766     albertel 4215:     my ($requrl) = @_;
1.765     albertel 4216:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4217:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4218:     if ($result) {
                   4219:         my %setters;
                   4220:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4221:             my ($startblock,$endblock) =
                   4222:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4223:             if ($startblock && $endblock) {
                   4224:                 return 'B';
                   4225:             }
                   4226:         } else {
                   4227:             my ($startblock,$endblock) =
                   4228:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4229:             if ($startblock && $endblock) {
                   4230:                 return 'B';
                   4231:             }
                   4232:         }
                   4233:     }
1.765     albertel 4234:     if ($result eq 'ok') {
1.766     albertel 4235:        return 'F';
1.765     albertel 4236:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4237:        return 'A';
1.765     albertel 4238:     }
1.766     albertel 4239:     return '';
1.765     albertel 4240: }
                   4241: 
                   4242: sub get_portfolio_access {
1.767     albertel 4243:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4244: 
                   4245:     if (!ref($access_hash)) {
                   4246: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4247: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4248: 						   $file_name);
                   4249: 	$access_hash = $access_controls{$file_name};
                   4250:     }
                   4251: 
1.765     albertel 4252:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4253:     my $now = time;
                   4254:     if (ref($access_hash) eq 'HASH') {
                   4255:         foreach my $key (keys(%{$access_hash})) {
                   4256:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4257:             if ($start > $now) {
                   4258:                 next;
                   4259:             }
                   4260:             if ($end && $end<$now) {
                   4261:                 next;
                   4262:             }
                   4263:             if ($scope eq 'public') {
                   4264:                 $public = $key;
                   4265:                 last;
                   4266:             } elsif ($scope eq 'guest') {
                   4267:                 $guest = $key;
                   4268:             } elsif ($scope eq 'domains') {
                   4269:                 push(@domains,$key);
                   4270:             } elsif ($scope eq 'users') {
                   4271:                 push(@users,$key);
                   4272:             } elsif ($scope eq 'course') {
                   4273:                 push(@courses,$key);
                   4274:             } elsif ($scope eq 'group') {
                   4275:                 push(@groups,$key);
                   4276:             }
                   4277:         }
                   4278:         if ($public) {
                   4279:             return 'ok';
                   4280:         }
                   4281:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4282:             if ($guest) {
                   4283:                 return $guest;
                   4284:             }
                   4285:         } else {
                   4286:             if (@domains > 0) {
                   4287:                 foreach my $domkey (@domains) {
                   4288:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4289:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4290:                             return 'ok';
                   4291:                         }
                   4292:                     }
                   4293:                 }
                   4294:             }
                   4295:             if (@users > 0) {
                   4296:                 foreach my $userkey (@users) {
1.865     raeburn  4297:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4298:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4299:                             if (ref($item) eq 'HASH') {
                   4300:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4301:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4302:                                     return 'ok';
                   4303:                                 }
                   4304:                             }
                   4305:                         }
                   4306:                     } 
1.765     albertel 4307:                 }
                   4308:             }
                   4309:             my %roleshash;
                   4310:             my @courses_and_groups = @courses;
                   4311:             push(@courses_and_groups,@groups); 
                   4312:             if (@courses_and_groups > 0) {
                   4313:                 my (%allgroups,%allroles); 
                   4314:                 my ($start,$end,$role,$sec,$group);
                   4315:                 foreach my $envkey (%env) {
1.811     albertel 4316:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4317:                         my $cid = $2.'_'.$3; 
                   4318:                         if ($1 eq 'gr') {
                   4319:                             $group = $4;
                   4320:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4321:                         } else {
                   4322:                             if ($4 eq '') {
                   4323:                                 $sec = 'none';
                   4324:                             } else {
                   4325:                                 $sec = $4;
                   4326:                             }
                   4327:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4328:                         }
1.811     albertel 4329:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4330:                         my $cid = $2.'_'.$3;
                   4331:                         if ($4 eq '') {
                   4332:                             $sec = 'none';
                   4333:                         } else {
                   4334:                             $sec = $4;
                   4335:                         }
                   4336:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4337:                     }
                   4338:                 }
                   4339:                 if (keys(%allroles) == 0) {
                   4340:                     return;
                   4341:                 }
                   4342:                 foreach my $key (@courses_and_groups) {
                   4343:                     my %content = %{$$access_hash{$key}};
                   4344:                     my $cnum = $content{'number'};
                   4345:                     my $cdom = $content{'domain'};
                   4346:                     my $cid = $cdom.'_'.$cnum;
                   4347:                     if (!exists($allroles{$cid})) {
                   4348:                         next;
                   4349:                     }    
                   4350:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4351:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4352:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4353:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4354:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4355:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4356:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4357:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4358:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4359:                                         if (grep/^all$/,@sections) {
                   4360:                                             return 'ok';
                   4361:                                         } else {
                   4362:                                             if (grep/^$sec$/,@sections) {
                   4363:                                                 return 'ok';
                   4364:                                             }
                   4365:                                         }
                   4366:                                     }
                   4367:                                 }
                   4368:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4369:                                     if (grep/^none$/,@groups) {
                   4370:                                         return 'ok';
                   4371:                                     }
                   4372:                                 } else {
                   4373:                                     if (grep/^all$/,@groups) {
                   4374:                                         return 'ok';
                   4375:                                     } 
                   4376:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4377:                                         if (grep/^$group$/,@groups) {
                   4378:                                             return 'ok';
                   4379:                                         }
                   4380:                                     }
                   4381:                                 } 
                   4382:                             }
                   4383:                         }
                   4384:                     }
                   4385:                 }
                   4386:             }
                   4387:             if ($guest) {
                   4388:                 return $guest;
                   4389:             }
                   4390:         }
                   4391:     }
                   4392:     return;
                   4393: }
                   4394: 
                   4395: sub course_group_datechecker {
                   4396:     my ($dates,$now,$status) = @_;
                   4397:     my ($start,$end) = split(/\./,$dates);
                   4398:     if (!$start && !$end) {
                   4399:         return 'ok';
                   4400:     }
                   4401:     if (grep/^active$/,@{$status}) {
                   4402:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4403:             return 'ok';
                   4404:         }
                   4405:     }
                   4406:     if (grep/^previous$/,@{$status}) {
                   4407:         if ($end > $now ) {
                   4408:             return 'ok';
                   4409:         }
                   4410:     }
                   4411:     if (grep/^future$/,@{$status}) {
                   4412:         if ($start > $now) {
                   4413:             return 'ok';
                   4414:         }
                   4415:     }
                   4416:     return; 
                   4417: }
                   4418: 
                   4419: sub parse_portfolio_url {
                   4420:     my ($url) = @_;
                   4421: 
                   4422:     my ($type,$udom,$unum,$group,$file_name);
                   4423:     
1.823     albertel 4424:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4425: 	$type = 1;
                   4426:         $udom = $1;
                   4427:         $unum = $2;
                   4428:         $file_name = $3;
1.823     albertel 4429:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4430: 	$type = 2;
                   4431:         $udom = $1;
                   4432:         $unum = $2;
                   4433:         $group = $3;
                   4434:         $file_name = $3.'/'.$4;
                   4435:     }
                   4436:     if (wantarray) {
                   4437: 	return ($type,$udom,$unum,$file_name,$group);
                   4438:     }
                   4439:     return $type;
                   4440: }
                   4441: 
                   4442: sub is_portfolio_url {
                   4443:     my ($url) = @_;
                   4444:     return scalar(&parse_portfolio_url($url));
                   4445: }
                   4446: 
1.798     raeburn  4447: sub is_portfolio_file {
                   4448:     my ($file) = @_;
1.820     raeburn  4449:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4450:         return 1;
                   4451:     }
                   4452:     return;
                   4453: }
                   4454: 
1.976     raeburn  4455: sub usertools_access {
1.985     raeburn  4456:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4457:     my ($access,%tools);
                   4458:     if ($context eq '') {
                   4459:         $context = 'tools';
                   4460:     }
                   4461:     if ($context eq 'requestcourses') {
                   4462:         %tools = (
                   4463:                       official   => 1,
                   4464:                       unofficial => 1,
                   4465:                  );
                   4466:     } else {
                   4467:         %tools = (
                   4468:                       aboutme   => 1,
                   4469:                       blog      => 1,
                   4470:                       portfolio => 1,
                   4471:                  );
                   4472:     }
1.976     raeburn  4473:     return if (!defined($tools{$tool}));
                   4474: 
                   4475:     if ((!defined($udom)) || (!defined($uname))) {
                   4476:         $udom = $env{'user.domain'};
                   4477:         $uname = $env{'user.name'};
                   4478:     }
                   4479: 
1.978     raeburn  4480:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4481:         if ($action ne 'reload') {
1.985     raeburn  4482:             if ($context eq 'requestcourses') {
                   4483:                 return $env{'environment.canrequest.'.$tool};
                   4484:             } else {
                   4485:                 return $env{'environment.availabletools.'.$tool};
                   4486:             }
                   4487:         }
1.976     raeburn  4488:     }
                   4489: 
                   4490:     my ($toolstatus,$inststatus);
                   4491: 
1.985     raeburn  4492:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4493:          ($action ne 'reload')) {
                   4494:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4495:         $inststatus = $env{'environment.inststatus'};
                   4496:     } else {
1.985     raeburn  4497:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4498:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4499:         $inststatus = $userenv{'inststatus'};
                   4500:     }
                   4501: 
                   4502:     if ($toolstatus ne '') {
                   4503:         if ($toolstatus) {
                   4504:             $access = 1;
                   4505:         } else {
                   4506:             $access = 0;
                   4507:         }
                   4508:         return $access;
                   4509:     }
                   4510: 
                   4511:     my $is_adv = &is_advanced_user($udom,$uname);
                   4512:     my %domdef = &get_domain_defaults($udom);
                   4513:     if (ref($domdef{$tool}) eq 'HASH') {
                   4514:         if ($is_adv) {
                   4515:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4516:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4517:                     $access = 1;
                   4518:                 } else {
                   4519:                     $access = 0;
                   4520:                 }
                   4521:                 return $access;
                   4522:             }
                   4523:         }
                   4524:         if ($inststatus ne '') {
                   4525:             my ($hasaccess,$hasnoaccess);
                   4526:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4527:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4528:                     if ($domdef{$tool}{$affiliation}) {
                   4529:                         $hasaccess = 1;
                   4530:                     } else {
                   4531:                         $hasnoaccess = 1;
                   4532:                     }
                   4533:                 }
                   4534:             }
                   4535:             if ($hasaccess || $hasnoaccess) {
                   4536:                 if ($hasaccess) {
                   4537:                     $access = 1;
                   4538:                 } elsif ($hasnoaccess) {
                   4539:                     $access = 0; 
                   4540:                 }
                   4541:                 return $access;
                   4542:             }
                   4543:         } else {
                   4544:             if ($domdef{$tool}{'default'} ne '') {
                   4545:                 if ($domdef{$tool}{'default'}) {
                   4546:                     $access = 1;
                   4547:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4548:                     $access = 0;
                   4549:                 }
                   4550:                 return $access;
                   4551:             }
                   4552:         }
                   4553:     } else {
1.985     raeburn  4554:         if ($context eq 'tools') {
                   4555:             $access = 1;
                   4556:         } else {
                   4557:             $access = 0;
                   4558:         }
1.976     raeburn  4559:         return $access;
                   4560:     }
                   4561: }
                   4562: 
                   4563: sub is_advanced_user {
                   4564:     my ($udom,$uname) = @_;
                   4565:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4566:     my %allroles;
                   4567:     my $is_adv;
                   4568:     foreach my $role (keys(%roleshash)) {
                   4569:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4570:         my $area = '/'.$tdomain.'/'.$trest;
                   4571:         if ($sec ne '') {
                   4572:             $area .= '/'.$sec;
                   4573:         }
                   4574:         if (($area ne '') && ($trole ne '')) {
                   4575:             my $spec=$trole.'.'.$area;
                   4576:             if ($trole =~ /^cr\//) {
                   4577:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4578:             } elsif ($trole ne 'gr') {
                   4579:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4580:             }
                   4581:         }
                   4582:     }
                   4583:     foreach my $role (keys(%allroles)) {
                   4584:         last if ($is_adv);
                   4585:         foreach my $item (split(/:/,$allroles{$role})) {
                   4586:             if ($item ne '') {
                   4587:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4588:                 if ($privilege eq 'adv') {
                   4589:                     $is_adv = 1;
                   4590:                     last;
                   4591:                 }
                   4592:             }
                   4593:         }
                   4594:     }
                   4595:     return $is_adv;
                   4596: }
1.798     raeburn  4597: 
1.341     www      4598: # ---------------------------------------------- Custom access rule evaluation
                   4599: 
                   4600: sub customaccess {
                   4601:     my ($priv,$uri)=@_;
1.807     albertel 4602:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4603:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4604:     $udom = &LONCAPA::clean_domain($udom);
                   4605:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4606:     my $access=0;
1.800     albertel 4607:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4608: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4609: 	if ($type eq 'user') {
                   4610: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4611: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4612: 		if ($tdom) {
                   4613: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4614: 		}
1.896     albertel 4615: 		if ($tuname) {
                   4616: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4617: 		}
                   4618: 		$access=($effect eq 'allow');
                   4619: 		last;
                   4620: 	    }
                   4621: 	} else {
                   4622: 	    if ($role) {
                   4623: 		if ($role ne $urole) { next; }
                   4624: 	    }
                   4625: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4626: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4627: 		if ($tdom) {
                   4628: 		    if ($tdom ne $udom) { next; }
                   4629: 		}
                   4630: 		if ($tcrs) {
                   4631: 		    if ($tcrs ne $ucrs) { next; }
                   4632: 		}
                   4633: 		if ($tsec) {
                   4634: 		    if ($tsec ne $usec) { next; }
                   4635: 		}
                   4636: 		$access=($effect eq 'allow');
                   4637: 		last;
                   4638: 	    }
                   4639: 	    if ($realm eq '' && $role eq '') {
                   4640: 		$access=($effect eq 'allow');
                   4641: 	    }
1.402     bowersj2 4642: 	}
1.341     www      4643:     }
                   4644:     return $access;
                   4645: }
                   4646: 
1.103     harris41 4647: # ------------------------------------------------- Check for a user privilege
1.12      www      4648: 
                   4649: sub allowed {
1.810     raeburn  4650:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4651:     my $ver_orguri=$uri;
1.439     www      4652:     $uri=&deversion($uri);
1.152     www      4653:     my $orguri=$uri;
1.52      www      4654:     $uri=&declutter($uri);
1.809     raeburn  4655: 
1.810     raeburn  4656:     if ($priv eq 'evb') {
                   4657: # Evade communication block restrictions for specified role in a course
                   4658:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4659:             return $1;
                   4660:         } else {
                   4661:             return;
                   4662:         }
                   4663:     }
                   4664: 
1.620     albertel 4665:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4666: # Free bre access to adm and meta resources
1.775     albertel 4667:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4668: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4669: 	&& ($priv eq 'bre')) {
1.14      www      4670: 	return 'F';
1.159     www      4671:     }
                   4672: 
1.545     banghart 4673: # Free bre access to user's own portfolio contents
1.714     raeburn  4674:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4675:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4676: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4677:         my %setters;
                   4678:         my ($startblock,$endblock) = 
                   4679:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4680:         if ($startblock && $endblock) {
                   4681:             return 'B';
                   4682:         } else {
                   4683:             return 'F';
                   4684:         }
1.545     banghart 4685:     }
                   4686: 
1.762     raeburn  4687: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4688:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4689:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4690:         if (exists($env{'request.course.id'})) {
                   4691:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4692:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4693:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4694:                 my $courseprivid=$env{'request.course.id'};
                   4695:                 $courseprivid=~s/\_/\//;
                   4696:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4697:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4698:                     return $1; 
1.762     raeburn  4699:                 } else {
                   4700:                     if ($env{'request.course.sec'}) {
                   4701:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4702:                     }
                   4703:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4704:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4705:                         return $2;
                   4706:                     }
1.714     raeburn  4707:                 }
                   4708:             }
                   4709:         }
                   4710:     }
                   4711: 
1.159     www      4712: # Free bre to public access
                   4713: 
                   4714:     if ($priv eq 'bre') {
1.238     www      4715:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4716: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4717:            return 'F'; 
                   4718:         }
1.238     www      4719:         if ($copyright eq 'priv') {
                   4720:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4721: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4722: 		return '';
                   4723:             }
                   4724:         }
                   4725:         if ($copyright eq 'domain') {
                   4726:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4727: 	    unless (($env{'user.domain'} eq $1) ||
                   4728:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4729: 		return '';
                   4730:             }
1.262     matthew  4731:         }
1.620     albertel 4732:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4733:             # Library role, so allow browsing of resources in this domain.
                   4734:             return 'F';
1.238     www      4735:         }
1.341     www      4736:         if ($copyright eq 'custom') {
                   4737: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4738:         }
1.14      www      4739:     }
1.264     matthew  4740:     # Domain coordinator is trying to create a course
1.620     albertel 4741:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4742:         # uri is the requested domain in this case.
                   4743:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4744:         # a role of dc for the domain in question.
1.620     albertel 4745:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4746:     }
1.29      www      4747: 
1.52      www      4748:     my $thisallowed='';
                   4749:     my $statecond=0;
                   4750:     my $courseprivid='';
                   4751: 
                   4752: # Course
                   4753: 
1.620     albertel 4754:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4755:        $thisallowed.=$1;
                   4756:     }
1.29      www      4757: 
1.52      www      4758: # Domain
                   4759: 
1.620     albertel 4760:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4761:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4762:        $thisallowed.=$1;
                   4763:     }
1.52      www      4764: 
                   4765: # Course: uri itself is a course
1.66      www      4766:     my $courseuri=$uri;
                   4767:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4768:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4769: 
1.620     albertel 4770:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4771:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4772:        $thisallowed.=$1;
                   4773:     }
1.29      www      4774: 
1.665     albertel 4775: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4776: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4777:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4778: 	$thisallowed='';
1.671     raeburn  4779:         my ($match)=&is_on_map($uri);
                   4780:         if ($match) {
                   4781:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4782:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4783:                 $thisallowed.=$1;
                   4784:             }
                   4785:         } else {
1.705     albertel 4786:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4787:             if ($refuri) {
                   4788:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4789:                     $thisallowed='F';
1.671     raeburn  4790:                 } else {
                   4791:                     $refuri=&declutter($refuri);
                   4792:                     my ($match) = &is_on_map($refuri);
                   4793:                     if ($match) {
                   4794:                         $thisallowed='F';
                   4795:                     }
1.669     raeburn  4796:                 }
1.671     raeburn  4797:             }
                   4798:         }
1.314     www      4799:     }
1.492     albertel 4800: 
1.766     albertel 4801:     if ($priv eq 'bre'
                   4802: 	&& $thisallowed ne 'F' 
                   4803: 	&& $thisallowed ne '2'
                   4804: 	&& &is_portfolio_url($uri)) {
                   4805: 	$thisallowed = &portfolio_access($uri);
                   4806:     }
                   4807:     
1.52      www      4808: # Full access at system, domain or course-wide level? Exit.
1.29      www      4809:     if ($thisallowed=~/F/) {
                   4810: 	return 'F';
                   4811:     }
                   4812: 
1.52      www      4813: # If this is generating or modifying users, exit with special codes
1.29      www      4814: 
1.643     www      4815:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4816: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4817: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4818: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4819: 	    unless ($auname) { return $thisallowed; }
                   4820: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4821: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4822: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4823: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4824: 	}
1.52      www      4825: 	return $thisallowed;
                   4826:     }
                   4827: #
1.103     harris41 4828: # Gathered so far: system, domain and course wide privileges
1.52      www      4829: #
                   4830: # Course: See if uri or referer is an individual resource that is part of 
                   4831: # the course
                   4832: 
1.620     albertel 4833:     if ($env{'request.course.id'}) {
1.232     www      4834: 
1.620     albertel 4835:        $courseprivid=$env{'request.course.id'};
                   4836:        if ($env{'request.course.sec'}) {
                   4837:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4838:        }
                   4839:        $courseprivid=~s/\_/\//;
                   4840:        my $checkreferer=1;
1.232     www      4841:        my ($match,$cond)=&is_on_map($uri);
                   4842:        if ($match) {
                   4843:            $statecond=$cond;
1.620     albertel 4844:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4845:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4846:                $thisallowed.=$1;
                   4847:                $checkreferer=0;
                   4848:            }
1.29      www      4849:        }
1.83      www      4850:        
1.148     www      4851:        if ($checkreferer) {
1.620     albertel 4852: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4853:             unless ($refuri) {
1.800     albertel 4854:                 foreach my $key (keys(%env)) {
                   4855: 		    if ($key=~/^httpref\..*\*/) {
                   4856: 			my $pattern=$key;
1.156     www      4857:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4858:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4859:                         $pattern=~s/\//\\\//g;
1.152     www      4860:                         if ($orguri=~/$pattern/) {
1.800     albertel 4861: 			    $refuri=$env{$key};
1.148     www      4862:                         }
                   4863:                     }
1.191     harris41 4864:                 }
1.148     www      4865:             }
1.232     www      4866: 
1.148     www      4867:          if ($refuri) { 
1.152     www      4868: 	  $refuri=&declutter($refuri);
1.232     www      4869:           my ($match,$cond)=&is_on_map($refuri);
                   4870:             if ($match) {
                   4871:               my $refstatecond=$cond;
1.620     albertel 4872:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4873:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4874:                   $thisallowed.=$1;
1.53      www      4875:                   $uri=$refuri;
                   4876:                   $statecond=$refstatecond;
1.52      www      4877:               }
                   4878:           }
1.148     www      4879:         }
1.29      www      4880:        }
1.52      www      4881:    }
1.29      www      4882: 
1.52      www      4883: #
1.103     harris41 4884: # Gathered now: all privileges that could apply, and condition number
1.52      www      4885: # 
                   4886: #
                   4887: # Full or no access?
                   4888: #
1.29      www      4889: 
1.52      www      4890:     if ($thisallowed=~/F/) {
                   4891: 	return 'F';
                   4892:     }
1.29      www      4893: 
1.52      www      4894:     unless ($thisallowed) {
                   4895:         return '';
                   4896:     }
1.29      www      4897: 
1.52      www      4898: # Restrictions exist, deal with them
                   4899: #
                   4900: #   C:according to course preferences
                   4901: #   R:according to resource settings
                   4902: #   L:unless locked
                   4903: #   X:according to user session state
                   4904: #
                   4905: 
                   4906: # Possibly locked functionality, check all courses
1.54      www      4907: # Locks might take effect only after 10 minutes cache expiration for other
                   4908: # courses, and 2 minutes for current course
1.52      www      4909: 
                   4910:     my $envkey;
                   4911:     if ($thisallowed=~/L/) {
1.620     albertel 4912:         foreach $envkey (keys %env) {
1.54      www      4913:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4914:                my $courseid=$2;
                   4915:                my $roleid=$1.'.'.$2;
1.92      www      4916:                $courseid=~s/^\///;
1.54      www      4917:                my $expiretime=600;
1.620     albertel 4918:                if ($env{'request.role'} eq $roleid) {
1.54      www      4919: 		  $expiretime=120;
                   4920:                }
                   4921: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4922:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4923:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4924: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4925:                }
1.620     albertel 4926:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4927:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4928: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4929:                        &log($env{'user.domain'},$env{'user.name'},
                   4930:                             $env{'user.home'},
1.57      www      4931:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4932:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4933:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4934: 		       return '';
                   4935:                    }
                   4936:                }
1.620     albertel 4937:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4938:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4939: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4940:                        &log($env{'user.domain'},$env{'user.name'},
                   4941:                             $env{'user.home'},
1.57      www      4942:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4943:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4944:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4945: 		       return '';
                   4946:                    }
                   4947:                }
                   4948: 	   }
1.29      www      4949:        }
1.52      www      4950:     }
                   4951:    
                   4952: #
                   4953: # Rest of the restrictions depend on selected course
                   4954: #
                   4955: 
1.620     albertel 4956:     unless ($env{'request.course.id'}) {
1.766     albertel 4957: 	if ($thisallowed eq 'A') {
                   4958: 	    return 'A';
1.814     raeburn  4959:         } elsif ($thisallowed eq 'B') {
                   4960:             return 'B';
1.766     albertel 4961: 	} else {
                   4962: 	    return '1';
                   4963: 	}
1.52      www      4964:     }
1.29      www      4965: 
1.52      www      4966: #
                   4967: # Now user is definitely in a course
                   4968: #
1.53      www      4969: 
                   4970: 
                   4971: # Course preferences
                   4972: 
                   4973:    if ($thisallowed=~/C/) {
1.620     albertel 4974:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4975:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4976:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4977: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4978: 	   if ($priv ne 'pch') { 
                   4979: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4980: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4981: 			$env{'request.course.id'});
                   4982: 	   }
1.237     www      4983:            return '';
                   4984:        }
                   4985: 
1.620     albertel 4986:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4987: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4988: 	   if ($priv ne 'pch') { 
                   4989: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4990: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4991: 			$env{'request.course.id'});
                   4992: 	   }
1.54      www      4993:            return '';
                   4994:        }
1.53      www      4995:    }
                   4996: 
                   4997: # Resource preferences
                   4998: 
                   4999:    if ($thisallowed=~/R/) {
1.620     albertel 5000:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5001:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5002: 	   if ($priv ne 'pch') { 
                   5003: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5004: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5005: 	   }
                   5006: 	   return '';
1.54      www      5007:        }
1.53      www      5008:    }
1.30      www      5009: 
1.246     www      5010: # Restricted by state or randomout?
1.30      www      5011: 
1.52      www      5012:    if ($thisallowed=~/X/) {
1.620     albertel 5013:       if ($env{'acc.randomout'}) {
1.579     albertel 5014: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5015:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5016:             return ''; 
                   5017:          }
1.247     www      5018:       }
                   5019:       if (&condval($statecond)) {
1.52      www      5020: 	 return '2';
                   5021:       } else {
                   5022:          return '';
                   5023:       }
                   5024:    }
1.30      www      5025: 
1.766     albertel 5026:     if ($thisallowed eq 'A') {
                   5027: 	return 'A';
1.814     raeburn  5028:     } elsif ($thisallowed eq 'B') {
                   5029:         return 'B';
1.766     albertel 5030:     }
1.52      www      5031:    return 'F';
1.232     www      5032: }
                   5033: 
1.710     albertel 5034: sub split_uri_for_cond {
                   5035:     my $uri=&deversion(&declutter(shift));
                   5036:     my @uriparts=split(/\//,$uri);
                   5037:     my $filename=pop(@uriparts);
                   5038:     my $pathname=join('/',@uriparts);
                   5039:     return ($pathname,$filename);
                   5040: }
1.232     www      5041: # --------------------------------------------------- Is a resource on the map?
                   5042: 
                   5043: sub is_on_map {
1.710     albertel 5044:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5045:     #Trying to find the conditional for the file
1.620     albertel 5046:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5047: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5048:     if ($match) {
1.289     bowersj2 5049: 	return (1,$1);
                   5050:     } else {
1.434     www      5051: 	return (0,0);
1.289     bowersj2 5052:     }
1.12      www      5053: }
                   5054: 
1.427     www      5055: # --------------------------------------------------------- Get symb from alias
                   5056: 
                   5057: sub get_symb_from_alias {
                   5058:     my $symb=shift;
                   5059:     my ($map,$resid,$url)=&decode_symb($symb);
                   5060: # Already is a symb
                   5061:     if ($url) { return $symb; }
                   5062: # Must be an alias
                   5063:     my $aliassymb='';
                   5064:     my %bighash;
1.620     albertel 5065:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5066:                             &GDBM_READER(),0640)) {
                   5067:         my $rid=$bighash{'mapalias_'.$symb};
                   5068: 	if ($rid) {
                   5069: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5070: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5071: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5072: 	}
                   5073:         untie %bighash;
                   5074:     }
                   5075:     return $aliassymb;
                   5076: }
                   5077: 
1.12      www      5078: # ----------------------------------------------------------------- Define Role
                   5079: 
                   5080: sub definerole {
                   5081:   if (allowed('mcr','/')) {
                   5082:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5083:     foreach my $role (split(':',$sysrole)) {
                   5084: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5085:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5086:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5087: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5088:                return "refused:s:$crole&$cqual"; 
                   5089:             }
                   5090:         }
1.191     harris41 5091:     }
1.800     albertel 5092:     foreach my $role (split(':',$domrole)) {
                   5093: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5094:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5095:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5096: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5097:                return "refused:d:$crole&$cqual"; 
                   5098:             }
                   5099:         }
1.191     harris41 5100:     }
1.800     albertel 5101:     foreach my $role (split(':',$courole)) {
                   5102: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5103:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5104:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5105: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5106:                return "refused:c:$crole&$cqual"; 
                   5107:             }
                   5108:         }
1.191     harris41 5109:     }
1.620     albertel 5110:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5111:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5112: 	        "rolesdef_$rolename=".
                   5113:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5114:     return reply($command,$env{'user.home'});
1.12      www      5115:   } else {
                   5116:     return 'refused';
                   5117:   }
1.105     harris41 5118: }
                   5119: 
                   5120: # ---------------- Make a metadata query against the network of library servers
                   5121: 
                   5122: sub metadata_query {
1.244     matthew  5123:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5124:     my %rhash;
1.845     albertel 5125:     my %libserv = &all_library();
1.244     matthew  5126:     my @server_list = (defined($server_array) ? @$server_array
                   5127:                                               : keys(%libserv) );
                   5128:     for my $server (@server_list) {
1.118     harris41 5129: 	unless ($custom or $customshow) {
                   5130: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5131: 	    $rhash{$server}=$reply;
                   5132: 	}
                   5133: 	else {
                   5134: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5135: 			     &escape($custom).':'.&escape($customshow),
                   5136: 			     $server);
                   5137: 	    $rhash{$server}=$reply;
                   5138: 	}
1.112     harris41 5139:     }
1.118     harris41 5140:     return \%rhash;
1.240     www      5141: }
                   5142: 
                   5143: # ----------------------------------------- Send log queries and wait for reply
                   5144: 
                   5145: sub log_query {
                   5146:     my ($uname,$udom,$query,%filters)=@_;
                   5147:     my $uhome=&homeserver($uname,$udom);
                   5148:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5149:     my $uhost=&hostname($uhome);
1.800     albertel 5150:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5151:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5152:                        $uhome);
1.479     albertel 5153:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5154:     return get_query_reply($queryid);
                   5155: }
                   5156: 
1.818     raeburn  5157: # -------------------------- Update MySQL table for portfolio file
                   5158: 
                   5159: sub update_portfolio_table {
1.821     raeburn  5160:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5161:     if ($group ne '') {
                   5162:         $file_name =~s /^\Q$group\E//;
                   5163:     }
1.818     raeburn  5164:     my $homeserver = &homeserver($uname,$udom);
                   5165:     my $queryid=
1.821     raeburn  5166:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5167:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5168:     my $reply = &get_query_reply($queryid);
                   5169:     return $reply;
                   5170: }
                   5171: 
1.899     raeburn  5172: # -------------------------- Update MySQL allusers table
                   5173: 
                   5174: sub update_allusers_table {
                   5175:     my ($uname,$udom,$names) = @_;
                   5176:     my $homeserver = &homeserver($uname,$udom);
                   5177:     my $queryid=
                   5178:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5179:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5180:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5181:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5182:                'generation='.&escape($names->{'generation'}).'%%'.
                   5183:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5184:                'id='.&escape($names->{'id'}),$homeserver);
                   5185:     my $reply = &get_query_reply($queryid);
                   5186:     return $reply;
                   5187: }
                   5188: 
1.508     raeburn  5189: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5190: 
                   5191: sub fetch_enrollment_query {
1.511     raeburn  5192:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5193:     my $homeserver;
1.547     raeburn  5194:     my $maxtries = 1;
1.508     raeburn  5195:     if ($context eq 'automated') {
                   5196:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5197:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5198:     } else {
                   5199:         $homeserver = &homeserver($cnum,$dom);
                   5200:     }
1.838     albertel 5201:     my $host=&hostname($homeserver);
1.506     raeburn  5202:     my $cmd = '';
1.800     albertel 5203:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5204:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5205:     }
                   5206:     $cmd =~ s/%%$//;
                   5207:     $cmd = &escape($cmd);
                   5208:     my $query = 'fetchenrollment';
1.620     albertel 5209:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5210:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5211:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5212:         return 'error: '.$queryid;
                   5213:     }
1.506     raeburn  5214:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5215:     my $tries = 1;
                   5216:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5217:         $reply = &get_query_reply($queryid);
                   5218:         $tries ++;
                   5219:     }
1.526     raeburn  5220:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5221:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5222:     } else {
1.901     albertel 5223:         my @responses = split(/:/,$reply);
1.515     raeburn  5224:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5225:             foreach my $line (@responses) {
                   5226:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5227:                 $$replyref{$key} = $value;
                   5228:             }
                   5229:         } else {
1.506     raeburn  5230:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5231:             foreach my $line (@responses) {
                   5232:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5233:                 $$replyref{$key} = $value;
                   5234:                 if ($value > 0) {
1.800     albertel 5235:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5236:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5237:                         my $destname = $pathname.'/'.$filename;
                   5238:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5239:                         if ($xml_classlist =~ /^error/) {
                   5240:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5241:                         } else {
1.506     raeburn  5242:                             if ( open(FILE,">$destname") ) {
                   5243:                                 print FILE &unescape($xml_classlist);
                   5244:                                 close(FILE);
1.526     raeburn  5245:                             } else {
                   5246:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5247:                             }
                   5248:                         }
                   5249:                     }
                   5250:                 }
                   5251:             }
                   5252:         }
                   5253:         return 'ok';
                   5254:     }
                   5255:     return 'error';
                   5256: }
                   5257: 
1.242     www      5258: sub get_query_reply {
                   5259:     my $queryid=shift;
1.240     www      5260:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5261:     my $reply='';
                   5262:     for (1..100) {
                   5263: 	sleep 2;
                   5264:         if (-e $replyfile.'.end') {
1.448     albertel 5265: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5266: 		$reply = join('',<$fh>);
                   5267: 		close($fh);
1.240     www      5268: 	   } else { return 'error: reply_file_error'; }
1.242     www      5269:            return &unescape($reply);
                   5270: 	}
1.240     www      5271:     }
1.242     www      5272:     return 'timeout:'.$queryid;
1.240     www      5273: }
                   5274: 
                   5275: sub courselog_query {
1.241     www      5276: #
                   5277: # possible filters:
                   5278: # url: url or symb
                   5279: # username
                   5280: # domain
                   5281: # action: view, submit, grade
                   5282: # start: timestamp
                   5283: # end: timestamp
                   5284: #
1.240     www      5285:     my (%filters)=@_;
1.620     albertel 5286:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5287:     if ($filters{'url'}) {
                   5288: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5289:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5290:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5291:     }
1.620     albertel 5292:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5293:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5294:     return &log_query($cname,$cdom,'courselog',%filters);
                   5295: }
                   5296: 
                   5297: sub userlog_query {
1.858     raeburn  5298: #
                   5299: # possible filters:
                   5300: # action: log check role
                   5301: # start: timestamp
                   5302: # end: timestamp
                   5303: #
1.240     www      5304:     my ($uname,$udom,%filters)=@_;
                   5305:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5306: }
                   5307: 
1.506     raeburn  5308: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5309: 
                   5310: sub auto_run {
1.508     raeburn  5311:     my ($cnum,$cdom) = @_;
1.876     raeburn  5312:     my $response = 0;
                   5313:     my $settings;
                   5314:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5315:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5316:         $settings = $domconfig{'autoenroll'};
                   5317:         if ($settings->{'run'} eq '1') {
                   5318:             $response = 1;
                   5319:         }
                   5320:     } else {
1.934     raeburn  5321:         my $homeserver;
                   5322:         if (&is_course($cdom,$cnum)) {
                   5323:             $homeserver = &homeserver($cnum,$cdom);
                   5324:         } else {
                   5325:             $homeserver = &domain($cdom,'primary');
                   5326:         }
                   5327:         if ($homeserver ne 'no_host') {
                   5328:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5329:         }
1.876     raeburn  5330:     }
1.506     raeburn  5331:     return $response;
                   5332: }
1.776     albertel 5333: 
1.506     raeburn  5334: sub auto_get_sections {
1.508     raeburn  5335:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5336:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5337:     my @secs = ();
1.511     raeburn  5338:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5339:     unless ($response eq 'refused') {
1.901     albertel 5340:         @secs = split(/:/,$response);
1.506     raeburn  5341:     }
                   5342:     return @secs;
                   5343: }
1.776     albertel 5344: 
1.506     raeburn  5345: sub auto_new_course {
1.508     raeburn  5346:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5347:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5348:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5349:     return $response;
                   5350: }
1.776     albertel 5351: 
1.506     raeburn  5352: sub auto_validate_courseID {
1.508     raeburn  5353:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5354:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5355:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5356:     return $response;
                   5357: }
1.776     albertel 5358: 
1.506     raeburn  5359: sub auto_create_password {
1.873     raeburn  5360:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5361:     my ($homeserver,$response);
1.506     raeburn  5362:     my $create_passwd = 0;
                   5363:     my $authchk = '';
1.873     raeburn  5364:     if ($udom =~ /^$match_domain$/) {
                   5365:         $homeserver = &domain($udom,'primary');
                   5366:     }
                   5367:     if ($homeserver eq '') {
                   5368:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5369:             $homeserver = &homeserver($cnum,$cdom);
                   5370:         }
                   5371:     }
                   5372:     if ($homeserver eq '') {
                   5373:         $authchk = 'nodomain';
1.506     raeburn  5374:     } else {
1.873     raeburn  5375:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5376:         if ($response eq 'refused') {
                   5377:             $authchk = 'refused';
                   5378:         } else {
1.901     albertel 5379:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5380:         }
1.506     raeburn  5381:     }
                   5382:     return ($authparam,$create_passwd,$authchk);
                   5383: }
                   5384: 
1.706     raeburn  5385: sub auto_photo_permission {
                   5386:     my ($cnum,$cdom,$students) = @_;
                   5387:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5388:     my ($outcome,$perm_reqd,$conditions) = 
                   5389: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5390:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5391: 	return (undef,undef);
                   5392:     }
1.706     raeburn  5393:     return ($outcome,$perm_reqd,$conditions);
                   5394: }
                   5395: 
                   5396: sub auto_checkphotos {
                   5397:     my ($uname,$udom,$pid) = @_;
                   5398:     my $homeserver = &homeserver($uname,$udom);
                   5399:     my ($result,$resulttype);
                   5400:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5401: 				   &escape($uname).':'.&escape($pid),
                   5402: 				   $homeserver));
1.709     albertel 5403:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5404: 	return (undef,undef);
                   5405:     }
1.706     raeburn  5406:     if ($outcome) {
                   5407:         ($result,$resulttype) = split(/:/,$outcome);
                   5408:     } 
                   5409:     return ($result,$resulttype);
                   5410: }
                   5411: 
                   5412: sub auto_photochoice {
                   5413:     my ($cnum,$cdom) = @_;
                   5414:     my $homeserver = &homeserver($cnum,$cdom);
                   5415:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5416: 						       &escape($cdom),
                   5417: 						       $homeserver)));
1.709     albertel 5418:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5419: 	return (undef,undef);
                   5420:     }
1.706     raeburn  5421:     return ($update,$comment);
                   5422: }
                   5423: 
                   5424: sub auto_photoupdate {
                   5425:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5426:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5427:     my $host=&hostname($homeserver);
1.706     raeburn  5428:     my $cmd = '';
                   5429:     my $maxtries = 1;
1.800     albertel 5430:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5431:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5432:     }
                   5433:     $cmd =~ s/%%$//;
                   5434:     $cmd = &escape($cmd);
                   5435:     my $query = 'institutionalphotos';
                   5436:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5437:     unless ($queryid=~/^\Q$host\E\_/) {
                   5438:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5439:         return 'error: '.$queryid;
                   5440:     }
                   5441:     my $reply = &get_query_reply($queryid);
                   5442:     my $tries = 1;
                   5443:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5444:         $reply = &get_query_reply($queryid);
                   5445:         $tries ++;
                   5446:     }
                   5447:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5448:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5449:     } else {
                   5450:         my @responses = split(/:/,$reply);
                   5451:         my $outcome = shift(@responses); 
                   5452:         foreach my $item (@responses) {
                   5453:             my ($key,$value) = split(/=/,$item);
                   5454:             $$photo{$key} = $value;
                   5455:         }
                   5456:         return $outcome;
                   5457:     }
                   5458:     return 'error';
                   5459: }
                   5460: 
1.521     raeburn  5461: sub auto_instcode_format {
1.793     albertel 5462:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5463: 	$cat_order) = @_;
1.521     raeburn  5464:     my $courses = '';
1.772     raeburn  5465:     my @homeservers;
1.521     raeburn  5466:     if ($caller eq 'global') {
1.841     albertel 5467: 	my %servers = &get_servers($codedom,'library');
                   5468: 	foreach my $tryserver (keys(%servers)) {
                   5469: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5470: 		push(@homeservers,$tryserver);
                   5471: 	    }
1.584     raeburn  5472:         }
1.521     raeburn  5473:     } else {
1.772     raeburn  5474:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5475:     }
1.793     albertel 5476:     foreach my $code (keys(%{$instcodes})) {
                   5477:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5478:     }
                   5479:     chop($courses);
1.772     raeburn  5480:     my $ok_response = 0;
                   5481:     my $response;
                   5482:     while (@homeservers > 0 && $ok_response == 0) {
                   5483:         my $server = shift(@homeservers); 
                   5484:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5485:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5486:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5487: 		split(/:/,$response);
1.772     raeburn  5488:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5489:             push(@{$codetitles},&str2array($codetitles_str));
                   5490:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5491:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5492:             $ok_response = 1;
                   5493:         }
                   5494:     }
                   5495:     if ($ok_response) {
1.521     raeburn  5496:         return 'ok';
1.772     raeburn  5497:     } else {
                   5498:         return $response;
1.521     raeburn  5499:     }
                   5500: }
                   5501: 
1.792     raeburn  5502: sub auto_instcode_defaults {
                   5503:     my ($domain,$returnhash,$code_order) = @_;
                   5504:     my @homeservers;
1.841     albertel 5505: 
                   5506:     my %servers = &get_servers($domain,'library');
                   5507:     foreach my $tryserver (keys(%servers)) {
                   5508: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5509: 	    push(@homeservers,$tryserver);
                   5510: 	}
1.792     raeburn  5511:     }
1.841     albertel 5512: 
1.792     raeburn  5513:     my $response;
1.841     albertel 5514:     foreach my $server (@homeservers) {
1.792     raeburn  5515:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5516:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5517: 	
                   5518: 	foreach my $pair (split(/\&/,$response)) {
                   5519: 	    my ($name,$value)=split(/\=/,$pair);
                   5520: 	    if ($name eq 'code_order') {
                   5521: 		@{$code_order} = split(/\&/,&unescape($value));
                   5522: 	    } else {
                   5523: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5524: 	    }
                   5525: 	}
                   5526: 	return 'ok';
1.792     raeburn  5527:     }
1.841     albertel 5528: 
                   5529:     return $response;
1.792     raeburn  5530: } 
                   5531: 
1.777     albertel 5532: sub auto_validate_class_sec {
1.918     raeburn  5533:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5534:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5535:     my $ownerlist;
                   5536:     if (ref($owners) eq 'ARRAY') {
                   5537:         $ownerlist = join(',',@{$owners});
                   5538:     } else {
                   5539:         $ownerlist = $owners;
                   5540:     }
1.773     raeburn  5541:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5542:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5543:     return $response;
                   5544: }
                   5545: 
1.679     raeburn  5546: # ------------------------------------------------------- Course Group routines
                   5547: 
                   5548: sub get_coursegroups {
1.809     raeburn  5549:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5550:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5551: }
                   5552: 
1.679     raeburn  5553: sub modify_coursegroup {
                   5554:     my ($cdom,$cnum,$groupsettings) = @_;
                   5555:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5556: }
                   5557: 
1.809     raeburn  5558: sub toggle_coursegroup_status {
                   5559:     my ($cdom,$cnum,$group,$action) = @_;
                   5560:     my ($from_namespace,$to_namespace);
                   5561:     if ($action eq 'delete') {
                   5562:         $from_namespace = 'coursegroups';
                   5563:         $to_namespace = 'deleted_groups';
                   5564:     } else {
                   5565:         $from_namespace = 'deleted_groups';
                   5566:         $to_namespace = 'coursegroups';
                   5567:     }
                   5568:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5569:     if (my $tmp = &error(%curr_group)) {
                   5570:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5571:         return ('read error',$tmp);
                   5572:     } else {
                   5573:         my %savedsettings = %curr_group; 
1.809     raeburn  5574:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5575:         my $deloutcome;
                   5576:         if ($result eq 'ok') {
1.809     raeburn  5577:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5578:         } else {
                   5579:             return ('write error',$result);
                   5580:         }
                   5581:         if ($deloutcome eq 'ok') {
                   5582:             return 'ok';
                   5583:         } else {
                   5584:             return ('delete error',$deloutcome);
                   5585:         }
                   5586:     }
                   5587: }
                   5588: 
1.679     raeburn  5589: sub modify_group_roles {
1.957     raeburn  5590:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5591:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5592:     my $role = 'gr/'.&escape($userprivs);
                   5593:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5594:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5595:     if ($result eq 'ok') {
                   5596:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5597:     }
1.679     raeburn  5598:     return $result;
                   5599: }
                   5600: 
                   5601: sub modify_coursegroup_membership {
                   5602:     my ($cdom,$cnum,$membership) = @_;
                   5603:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5604:     return $result;
                   5605: }
                   5606: 
1.682     raeburn  5607: sub get_active_groups {
                   5608:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5609:     my $now = time;
                   5610:     my %groups = ();
                   5611:     foreach my $key (keys(%env)) {
1.811     albertel 5612:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5613:             my ($start,$end) = split(/\./,$env{$key});
                   5614:             if (($end!=0) && ($end<$now)) { next; }
                   5615:             if (($start!=0) && ($start>$now)) { next; }
                   5616:             if ($1 eq $cdom && $2 eq $cnum) {
                   5617:                 $groups{$3} = $env{$key} ;
                   5618:             }
                   5619:         }
                   5620:     }
                   5621:     return %groups;
                   5622: }
                   5623: 
1.683     raeburn  5624: sub get_group_membership {
                   5625:     my ($cdom,$cnum,$group) = @_;
                   5626:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5627: }
                   5628: 
                   5629: sub get_users_groups {
                   5630:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5631:     my @usersgroups;
1.683     raeburn  5632:     my $cachetime=1800;
                   5633: 
                   5634:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5635:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5636:     if (defined($cached)) {
1.734     albertel 5637:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5638:     } else {  
                   5639:         $grouplist = '';
1.816     raeburn  5640:         my $courseurl = &courseid_to_courseurl($courseid);
                   5641:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5642:         my $access_end = $env{'course.'.$courseid.
                   5643:                               '.default_enrollment_end_date'};
                   5644:         my $now = time;
                   5645:         foreach my $key (keys(%roleshash)) {
                   5646:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5647:                 my $group = $1;
                   5648:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5649:                     my $start = $2;
                   5650:                     my $end = $1;
                   5651:                     if ($start == -1) { next; } # deleted from group
                   5652:                     if (($start!=0) && ($start>$now)) { next; }
                   5653:                     if (($end!=0) && ($end<$now)) {
                   5654:                         if ($access_end && $access_end < $now) {
                   5655:                             if ($access_end - $end < 86400) {
                   5656:                                 push(@usersgroups,$group);
1.733     raeburn  5657:                             }
                   5658:                         }
1.817     raeburn  5659:                         next;
1.733     raeburn  5660:                     }
1.817     raeburn  5661:                     push(@usersgroups,$group);
1.683     raeburn  5662:                 }
                   5663:             }
                   5664:         }
1.817     raeburn  5665:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5666:         $grouplist = join(':',@usersgroups);
                   5667:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5668:     }
1.733     raeburn  5669:     return @usersgroups;
1.683     raeburn  5670: }
                   5671: 
                   5672: sub devalidate_getgroups_cache {
                   5673:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5674:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5675: 
1.683     raeburn  5676:     my $hashid="$udom:$uname:$courseid";
                   5677:     &devalidate_cache_new('getgroups',$hashid);
                   5678: }
                   5679: 
1.12      www      5680: # ------------------------------------------------------------------ Plain Text
                   5681: 
                   5682: sub plaintext {
1.988     raeburn  5683:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5684:     if ($short =~ /^cr/) {
                   5685: 	return (split('/',$short))[-1];
                   5686:     }
1.742     raeburn  5687:     if (!defined($cid)) {
                   5688:         $cid = $env{'request.course.id'};
                   5689:     }
1.988     raeburn  5690:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5691:         unless ($forcedefault) {
                   5692:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5693:             &Apache::lonlocal::mt_escape(\$roletext);
                   5694:             return &Apache::lonlocal::mt($roletext);
                   5695:         }
1.742     raeburn  5696:     }
                   5697:     my %rolenames = (
                   5698:                       Course => 'std',
                   5699:                       Group => 'alt1',
                   5700:                     );
                   5701:     if (defined($type) && 
                   5702:          defined($rolenames{$type}) && 
                   5703:          defined($prp{$short}{$rolenames{$type}})) {
                   5704:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5705:     } else {
                   5706:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5707:     }
1.12      www      5708: }
                   5709: 
                   5710: # ----------------------------------------------------------------- Assign Role
                   5711: 
                   5712: sub assignrole {
1.957     raeburn  5713:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5714:         $context)=@_;
1.21      www      5715:     my $mrole;
                   5716:     if ($role =~ /^cr\//) {
1.393     www      5717:         my $cwosec=$url;
1.811     albertel 5718:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5719: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5720:            &logthis('Refused custom assignrole: '.
                   5721:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5722: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5723:            return 'refused'; 
                   5724:         }
1.21      www      5725:         $mrole='cr';
1.678     raeburn  5726:     } elsif ($role =~ /^gr\//) {
                   5727:         my $cwogrp=$url;
1.811     albertel 5728:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5729:         unless (&allowed('mdg',$cwogrp)) {
                   5730:             &logthis('Refused group assignrole: '.
                   5731:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5732:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5733:             return 'refused';
                   5734:         }
                   5735:         $mrole='gr';
1.21      www      5736:     } else {
1.82      www      5737:         my $cwosec=$url;
1.811     albertel 5738:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5739:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5740:             my $refused;
                   5741:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5742:                 if (!(&allowed('c'.$role,$url))) {
                   5743:                     $refused = 1;
                   5744:                 }
                   5745:             } else {
                   5746:                 $refused = 1;
                   5747:             }
1.947     raeburn  5748:             if ($refused) {
                   5749:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5750:                     $refused = '';
                   5751:                 } else {
                   5752:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5753:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5754: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5755:                     return 'refused';
                   5756:                 }
1.932     raeburn  5757:             }
1.104     www      5758:         }
1.21      www      5759:         $mrole=$role;
                   5760:     }
1.620     albertel 5761:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5762:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5763:     if ($end) { $command.='_'.$end; }
1.21      www      5764:     if ($start) {
                   5765: 	if ($end) { 
1.81      www      5766:            $command.='_'.$start; 
1.21      www      5767:         } else {
1.81      www      5768:            $command.='_0_'.$start;
1.21      www      5769:         }
                   5770:     }
1.739     raeburn  5771:     my $origstart = $start;
                   5772:     my $origend = $end;
1.957     raeburn  5773:     my $delflag;
1.357     www      5774: # actually delete
                   5775:     if ($deleteflag) {
1.373     www      5776: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5777: # modify command to delete the role
1.620     albertel 5778:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5779:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5780: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5781: # set start and finish to negative values for userrolelog
                   5782:            $start=-1;
                   5783:            $end=-1;
1.957     raeburn  5784:            $delflag = 1;
1.357     www      5785:         }
                   5786:     }
                   5787: # send command
1.349     www      5788:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5789: # log new user role if status is ok
1.349     www      5790:     if ($answer eq 'ok') {
1.663     raeburn  5791: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5792: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5793:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5794:         unless ($role =~ /^gr/) {
                   5795:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5796:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5797:         }
1.349     www      5798:     }
                   5799:     return $answer;
1.169     harris41 5800: }
                   5801: 
                   5802: # -------------------------------------------------- Modify user authentication
1.197     www      5803: # Overrides without validation
                   5804: 
1.169     harris41 5805: sub modifyuserauth {
                   5806:     my ($udom,$uname,$umode,$upass)=@_;
                   5807:     my $uhome=&homeserver($uname,$udom);
1.197     www      5808:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5809:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5810:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5811:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5812:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5813: 		     &escape($upass),$uhome);
1.620     albertel 5814:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5815:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5816:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5817:     &log($udom,,$uname,$uhome,
1.620     albertel 5818:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5819:                                      $env{'user.name'}.', '.$umode.
1.197     www      5820:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5821:     unless ($reply eq 'ok') {
1.197     www      5822:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5823: 	return 'error: '.$reply;
                   5824:     }   
1.170     harris41 5825:     return 'ok';
1.80      www      5826: }
                   5827: 
1.81      www      5828: # --------------------------------------------------------------- Modify a user
1.80      www      5829: 
1.81      www      5830: sub modifyuser {
1.206     matthew  5831:     my ($udom,    $uname, $uid,
                   5832:         $umode,   $upass, $first,
                   5833:         $middle,  $last,  $gene,
1.963     raeburn  5834:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5835:     $udom= &LONCAPA::clean_domain($udom);
                   5836:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5837:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5838:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5839: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5840:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5841:                                      ' desiredhome not specified'). 
1.620     albertel 5842:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5843:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5844:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5845: # ----------------------------------------------------------------- Create User
1.406     albertel 5846:     if (($uhome eq 'no_host') && 
                   5847: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5848:         my $unhome='';
1.844     albertel 5849:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5850:             $unhome = $desiredhome;
1.620     albertel 5851: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5852: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5853:         } else { # load balancing routine for determining $unhome
1.81      www      5854:             my $loadm=10000000;
1.841     albertel 5855: 	    my %servers = &get_servers($udom,'library');
                   5856: 	    foreach my $tryserver (keys(%servers)) {
                   5857: 		my $answer=reply('load',$tryserver);
                   5858: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5859: 		    $loadm=$answer;
                   5860: 		    $unhome=$tryserver;
                   5861: 		}
1.80      www      5862: 	    }
                   5863:         }
                   5864:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5865: 	    return 'error: unable to find a home server for '.$uname.
                   5866:                    ' in domain '.$udom;
1.80      www      5867:         }
                   5868:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5869:                          &escape($upass),$unhome);
                   5870: 	unless ($reply eq 'ok') {
                   5871:             return 'error: '.$reply;
                   5872:         }   
1.230     stredwic 5873:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5874:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5875: 	    return 'error: unable verify users home machine.';
1.80      www      5876:         }
1.209     matthew  5877:     }   # End of creation of new user
1.80      www      5878: # ---------------------------------------------------------------------- Add ID
                   5879:     if ($uid) {
                   5880:        $uid=~tr/A-Z/a-z/;
                   5881:        my %uidhash=&idrget($udom,$uname);
1.196     www      5882:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5883:          && (!$forceid)) {
1.80      www      5884: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5885: 	      return 'error: user id "'.$uid.'" does not match '.
                   5886:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5887:           }
                   5888:        } else {
                   5889: 	  &idput($udom,($uname => $uid));
                   5890:        }
                   5891:     }
                   5892: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5893:     my @tmp=&get('environment',
1.899     raeburn  5894: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5895:                     'permanentemail','inststatus'],
1.134     albertel 5896: 		   $udom,$uname);
1.313     matthew  5897:     my %names;
                   5898:     if ($tmp[0] =~ m/^error:.*/) { 
                   5899:         %names=(); 
                   5900:     } else {
                   5901:         %names = @tmp;
                   5902:     }
1.388     www      5903: #
                   5904: # Make sure to not trash student environment if instructor does not bother
                   5905: # to supply name and email information
                   5906: #
                   5907:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5908:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5909:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5910:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5911:     if ($email) {
                   5912:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5913:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5914:     }
1.899     raeburn  5915:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  5916:     if (defined($inststatus)) {
                   5917:         $names{'inststatus'} = '';
                   5918:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   5919:         if (ref($usertypes) eq 'HASH') {
                   5920:             my @okstatuses; 
                   5921:             foreach my $item (split(/:/,$inststatus)) {
                   5922:                 if (defined($usertypes->{$item})) {
                   5923:                     push(@okstatuses,$item);  
                   5924:                 }
                   5925:             }
                   5926:             if (@okstatuses) {
                   5927:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   5928:             }
                   5929:         }
                   5930:     }
1.134     albertel 5931:     my $reply = &put('environment', \%names, $udom,$uname);
                   5932:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5933:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5934:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5935:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5936:                  $umode.', '.$first.', '.$middle.', '.
                   5937: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5938:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5939:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5940:     } else {
                   5941:         $logmsg .= ' during self creation';
                   5942:     }
                   5943:     &logthis($logmsg);
1.134     albertel 5944:     return 'ok';
1.80      www      5945: }
                   5946: 
1.81      www      5947: # -------------------------------------------------------------- Modify student
1.80      www      5948: 
1.81      www      5949: sub modifystudent {
                   5950:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5951:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  5952:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 5953:     if (!$cid) {
1.620     albertel 5954: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5955: 	    return 'not_in_class';
                   5956: 	}
1.80      www      5957:     }
                   5958: # --------------------------------------------------------------- Make the user
1.81      www      5959:     my $reply=&modifyuser
1.209     matthew  5960: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  5961:          $desiredhome,$email,$inststatus);
1.80      www      5962:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5963:     # This will cause &modify_student_enrollment to get the uid from the
                   5964:     # students environment
                   5965:     $uid = undef if (!$forceid);
1.455     albertel 5966:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5967: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5968:     return $reply;
                   5969: }
                   5970: 
                   5971: sub modify_student_enrollment {
1.957     raeburn  5972:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5973:     my ($cdom,$cnum,$chome);
                   5974:     if (!$cid) {
1.620     albertel 5975: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5976: 	    return 'not_in_class';
                   5977: 	}
1.620     albertel 5978: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5979: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5980:     } else {
                   5981: 	($cdom,$cnum)=split(/_/,$cid);
                   5982:     }
1.620     albertel 5983:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5984:     if (!$chome) {
1.457     raeburn  5985: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5986:     }
1.455     albertel 5987:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5988:     # Make sure the user exists
1.81      www      5989:     my $uhome=&homeserver($uname,$udom);
                   5990:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5991: 	return 'error: no such user';
                   5992:     }
1.297     matthew  5993:     # Get student data if we were not given enough information
                   5994:     if (!defined($first)  || $first  eq '' || 
                   5995:         !defined($last)   || $last   eq '' || 
                   5996:         !defined($uid)    || $uid    eq '' || 
                   5997:         !defined($middle) || $middle eq '' || 
                   5998:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5999:         # They did not supply us with enough data to enroll the student, so
                   6000:         # we need to pick up more information.
1.297     matthew  6001:         my %tmp = &get('environment',
1.294     matthew  6002:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6003:                        ,$udom,$uname);
                   6004: 
1.800     albertel 6005:         #foreach my $key (keys(%tmp)) {
                   6006:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6007:         #}
1.294     matthew  6008:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6009:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6010:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6011:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6012:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6013:     }
1.556     albertel 6014:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6015:     my $reply=cput('classlist',
                   6016: 		   {"$uname:$udom" => 
1.515     raeburn  6017: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6018: 		   $cdom,$cnum);
1.81      www      6019:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6020: 	return 'error: '.$reply;
1.652     albertel 6021:     } else {
                   6022: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6023:     }
1.297     matthew  6024:     # Add student role to user
1.83      www      6025:     my $uurl='/'.$cid;
1.81      www      6026:     $uurl=~s/\_/\//g;
                   6027:     if ($usec) {
                   6028: 	$uurl.='/'.$usec;
                   6029:     }
1.957     raeburn  6030:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6031: }
                   6032: 
1.556     albertel 6033: sub format_name {
                   6034:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6035:     my $name;
                   6036:     if ($first ne 'lastname') {
                   6037: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6038:     } else {
                   6039: 	if ($lastname=~/\S/) {
                   6040: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6041: 	    $name=~s/\s+,/,/;
                   6042: 	} else {
                   6043: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6044: 	}
                   6045:     }
                   6046:     $name=~s/^\s+//;
                   6047:     $name=~s/\s+$//;
                   6048:     $name=~s/\s+/ /g;
                   6049:     return $name;
                   6050: }
                   6051: 
1.84      www      6052: # ------------------------------------------------- Write to course preferences
                   6053: 
                   6054: sub writecoursepref {
                   6055:     my ($courseid,%prefs)=@_;
                   6056:     $courseid=~s/^\///;
                   6057:     $courseid=~s/\_/\//g;
                   6058:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6059:     my $chome=homeserver($cnum,$cdomain);
                   6060:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6061: 	return 'error: no such course';
                   6062:     }
                   6063:     my $cstring='';
1.800     albertel 6064:     foreach my $pref (keys(%prefs)) {
                   6065: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6066:     }
1.84      www      6067:     $cstring=~s/\&$//;
                   6068:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6069: }
                   6070: 
                   6071: # ---------------------------------------------------------- Make/modify course
                   6072: 
                   6073: sub createcourse {
1.741     raeburn  6074:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6075:         $course_owner,$crstype)=@_;
1.84      www      6076:     $url=&declutter($url);
                   6077:     my $cid='';
1.264     matthew  6078:     unless (&allowed('ccc',$udom)) {
1.84      www      6079:         return 'refused';
                   6080:     }
                   6081: # ------------------------------------------------------------------- Create ID
1.674     www      6082:    my $uname=int(1+rand(9)).
                   6083:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6084:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6085:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6086: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6087:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6088:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6089:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6090:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6091:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6092:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6093:            return 'error: unable to generate unique course-ID';
                   6094:        } 
                   6095:    }
1.264     matthew  6096: # ------------------------------------------------ Check supplied server name
1.620     albertel 6097:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6098:     if (! &is_library($course_server)) {
1.264     matthew  6099:         return 'error:bad server name '.$course_server;
                   6100:     }
1.84      www      6101: # ------------------------------------------------------------- Make the course
                   6102:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6103:                       $course_server);
1.84      www      6104:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6105:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6106:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6107: 	return 'error: no such course';
                   6108:     }
1.271     www      6109: # ----------------------------------------------------------------- Course made
1.516     raeburn  6110: # log existence
1.918     raeburn  6111:     my $newcourse = {
                   6112:                     $udom.'_'.$uname => {
1.921     raeburn  6113:                                      description => $description,
                   6114:                                      inst_code   => $inst_code,
                   6115:                                      owner       => $course_owner,
                   6116:                                      type        => $crstype,
1.918     raeburn  6117:                                                 },
                   6118:                     };
1.921     raeburn  6119:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6120: # set toplevel url
1.271     www      6121:     my $topurl=$url;
                   6122:     unless ($nonstandard) {
                   6123: # ------------------------------------------ For standard courses, make top url
                   6124:         my $mapurl=&clutter($url);
1.278     www      6125:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6126:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6127: <map>
                   6128: <resource id="1" type="start"></resource>
                   6129: <resource id="2" src="$mapurl"></resource>
                   6130: <resource id="3" type="finish"></resource>
                   6131: <link index="1" from="1" to="2"></link>
                   6132: <link index="2" from="2" to="3"></link>
                   6133: </map>
                   6134: ENDINITMAP
                   6135:         $topurl=&declutter(
1.638     albertel 6136:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6137:                           );
                   6138:     }
                   6139: # ----------------------------------------------------------- Write preferences
1.84      www      6140:     &writecoursepref($udom.'_'.$uname,
                   6141:                      ('description' => $description,
1.271     www      6142:                       'url'         => $topurl));
1.84      www      6143:     return '/'.$udom.'/'.$uname;
                   6144: }
                   6145: 
1.813     albertel 6146: sub is_course {
                   6147:     my ($cdom,$cnum) = @_;
                   6148:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6149: 				undef,'.');
1.813     albertel 6150:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6151:         return 1;
                   6152:     }
                   6153:     return 0;
                   6154: }
                   6155: 
1.21      www      6156: # ---------------------------------------------------------- Assign Custom Role
                   6157: 
                   6158: sub assigncustomrole {
1.957     raeburn  6159:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6160:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6161:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6162: }
                   6163: 
                   6164: # ----------------------------------------------------------------- Revoke Role
                   6165: 
                   6166: sub revokerole {
1.957     raeburn  6167:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6168:     my $now=time;
1.965     raeburn  6169:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6170: }
                   6171: 
                   6172: # ---------------------------------------------------------- Revoke Custom Role
                   6173: 
                   6174: sub revokecustomrole {
1.957     raeburn  6175:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6176:     my $now=time;
1.357     www      6177:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6178:            $deleteflag,$selfenroll,$context);
1.17      www      6179: }
                   6180: 
1.533     banghart 6181: # ------------------------------------------------------------ Disk usage
1.535     albertel 6182: sub diskusage {
1.955     raeburn  6183:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6184:     $directorypath =~ s/\/$//;
                   6185:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6186:                        .&escape($getpropath).':'.&escape($uname).':'
                   6187:                        .&escape($udom),homeserver($uname,$udom));
                   6188:     if ($listing eq 'unknown_cmd') {
                   6189:         if ($getpropath) {
                   6190:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6191:         }
                   6192:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6193:     }
1.514     albertel 6194:     return $listing;
1.512     banghart 6195: }
                   6196: 
1.566     banghart 6197: sub is_locked {
                   6198:     my ($file_name, $domain, $user) = @_;
                   6199:     my @check;
                   6200:     my $is_locked;
                   6201:     push @check, $file_name;
1.613     albertel 6202:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6203: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6204:     my ($tmp)=keys(%locked);
                   6205:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6206:     
1.566     banghart 6207:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6208:         $is_locked = 'false';
                   6209:         foreach my $entry (@{$locked{$file_name}}) {
                   6210:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6211:                $is_locked = 'true';
                   6212:                last;
1.745     raeburn  6213:            }
                   6214:        }
1.566     banghart 6215:     } else {
                   6216:         $is_locked = 'false';
                   6217:     }
                   6218: }
                   6219: 
1.759     albertel 6220: sub declutter_portfile {
                   6221:     my ($file) = @_;
1.833     albertel 6222:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6223:     return $file;
                   6224: }
                   6225: 
1.559     banghart 6226: # ------------------------------------------------------------- Mark as Read Only
                   6227: 
                   6228: sub mark_as_readonly {
                   6229:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6230:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6231:     my ($tmp)=keys(%current_permissions);
                   6232:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6233:     foreach my $file (@{$files}) {
1.759     albertel 6234: 	$file = &declutter_portfile($file);
1.561     banghart 6235:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6236:     }
1.613     albertel 6237:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6238:     return;
                   6239: }
                   6240: 
1.572     banghart 6241: # ------------------------------------------------------------Save Selected Files
                   6242: 
                   6243: sub save_selected_files {
                   6244:     my ($user, $path, @files) = @_;
                   6245:     my $filename = $user."savedfiles";
1.573     banghart 6246:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6247:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6248:     foreach my $file (@files) {
1.620     albertel 6249:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6250:     }
                   6251:     foreach my $file (@other_files) {
1.574     banghart 6252:         print (OUT $file."\n");
1.572     banghart 6253:     }
1.574     banghart 6254:     close (OUT);
1.572     banghart 6255:     return 'ok';
                   6256: }
                   6257: 
1.574     banghart 6258: sub clear_selected_files {
                   6259:     my ($user) = @_;
                   6260:     my $filename = $user."savedfiles";
                   6261:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6262:     print (OUT undef);
                   6263:     close (OUT);
                   6264:     return ("ok");    
                   6265: }
                   6266: 
1.572     banghart 6267: sub files_in_path {
                   6268:     my ($user, $path) = @_;
                   6269:     my $filename = $user."savedfiles";
                   6270:     my %return_files;
1.574     banghart 6271:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6272:     while (my $line_in = <IN>) {
1.574     banghart 6273:         chomp ($line_in);
                   6274:         my @paths_and_file = split (m!/!, $line_in);
                   6275:         my $file_part = pop (@paths_and_file);
                   6276:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6277:         $path_part.='/';
                   6278:         my $path_and_file = $path_part.$file_part;
                   6279:         if ($path_part eq $path) {
                   6280:             $return_files{$file_part}= 'selected';
                   6281:         }
                   6282:     }
1.574     banghart 6283:     close (IN);
                   6284:     return (\%return_files);
1.572     banghart 6285: }
                   6286: 
                   6287: # called in portfolio select mode, to show files selected NOT in current directory
                   6288: sub files_not_in_path {
                   6289:     my ($user, $path) = @_;
                   6290:     my $filename = $user."savedfiles";
                   6291:     my @return_files;
                   6292:     my $path_part;
1.800     albertel 6293:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6294:     while (my $line = <IN>) {
1.572     banghart 6295:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6296:         my @paths_and_file = split(m|/|, $line);
                   6297:         my $file_part = pop(@paths_and_file);
                   6298:         chomp($file_part);
                   6299:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6300:         $path_part .= '/';
                   6301:         my $path_and_file = $path_part.$file_part;
                   6302:         if ($path_part ne $path) {
1.800     albertel 6303:             push(@return_files, ($path_and_file));
1.572     banghart 6304:         }
                   6305:     }
1.800     albertel 6306:     close(OUT);
1.574     banghart 6307:     return (@return_files);
1.572     banghart 6308: }
                   6309: 
1.745     raeburn  6310: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6311: 
1.745     raeburn  6312: sub get_portfile_permissions {
                   6313:     my ($domain,$user) = @_;
1.613     albertel 6314:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6315:     my ($tmp)=keys(%current_permissions);
                   6316:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6317:     return \%current_permissions;
                   6318: }
                   6319: 
                   6320: #---------------------------------------------Get portfolio file access controls
                   6321: 
1.749     raeburn  6322: sub get_access_controls {
1.745     raeburn  6323:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6324:     my %access;
                   6325:     my $real_file = $file;
                   6326:     $file =~ s/\.meta$//;
1.745     raeburn  6327:     if (defined($file)) {
1.749     raeburn  6328:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6329:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6330:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6331:             }
                   6332:         }
1.745     raeburn  6333:     } else {
1.749     raeburn  6334:         foreach my $key (keys(%{$current_permissions})) {
                   6335:             if ($key =~ /\0accesscontrol$/) {
                   6336:                 if (defined($group)) {
                   6337:                     if ($key !~ m-^\Q$group\E/-) {
                   6338:                         next;
                   6339:                     }
                   6340:                 }
                   6341:                 my ($fullpath) = split(/\0/,$key);
                   6342:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6343:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6344:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6345:                     }
                   6346:                 }
                   6347:             }
                   6348:         }
                   6349:     }
                   6350:     return %access;
                   6351: }
                   6352: 
                   6353: sub modify_access_controls {
                   6354:     my ($file_name,$changes,$domain,$user)=@_;
                   6355:     my ($outcome,$deloutcome);
                   6356:     my %store_permissions;
                   6357:     my %new_values;
                   6358:     my %new_control;
                   6359:     my %translation;
                   6360:     my @deletions = ();
                   6361:     my $now = time;
                   6362:     if (exists($$changes{'activate'})) {
                   6363:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6364:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6365:             my $numnew = scalar(@newitems);
                   6366:             for (my $i=0; $i<$numnew; $i++) {
                   6367:                 my $newkey = $newitems[$i];
                   6368:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6369:                 if ($newkey =~ /^\d+:/) { 
                   6370:                     $newkey =~ s/^(\d+)/$newid/;
                   6371:                     $translation{$1} = $newid;
                   6372:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6373:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6374:                     $translation{$1} = $newid;
                   6375:                 }
1.749     raeburn  6376:                 $new_values{$file_name."\0".$newkey} = 
                   6377:                                           $$changes{'activate'}{$newitems[$i]};
                   6378:                 $new_control{$newkey} = $now;
                   6379:             }
                   6380:         }
                   6381:     }
                   6382:     my %todelete;
                   6383:     my %changed_items;
                   6384:     foreach my $action ('delete','update') {
                   6385:         if (exists($$changes{$action})) {
                   6386:             if (ref($$changes{$action}) eq 'HASH') {
                   6387:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6388:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6389:                     if ($action eq 'delete') { 
                   6390:                         $todelete{$itemnum} = 1;
                   6391:                     } else {
                   6392:                         $changed_items{$itemnum} = $key;
                   6393:                     }
                   6394:                 }
1.745     raeburn  6395:             }
                   6396:         }
1.749     raeburn  6397:     }
                   6398:     # get lock on access controls for file.
                   6399:     my $lockhash = {
                   6400:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6401:                                                        ':'.$env{'user.domain'},
                   6402:                    }; 
                   6403:     my $tries = 0;
                   6404:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6405:    
                   6406:     while (($gotlock ne 'ok') && $tries <3) {
                   6407:         $tries ++;
                   6408:         sleep 1;
                   6409:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6410:     }
                   6411:     if ($gotlock eq 'ok') {
                   6412:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6413:         my ($tmp)=keys(%curr_permissions);
                   6414:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6415:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6416:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6417:             if (ref($curr_controls) eq 'HASH') {
                   6418:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6419:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6420:                     if (defined($todelete{$itemnum})) {
                   6421:                         push(@deletions,$file_name."\0".$control_item);
                   6422:                     } else {
                   6423:                         if (defined($changed_items{$itemnum})) {
                   6424:                             $new_control{$changed_items{$itemnum}} = $now;
                   6425:                             push(@deletions,$file_name."\0".$control_item);
                   6426:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6427:                         } else {
                   6428:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6429:                         }
                   6430:                     }
1.745     raeburn  6431:                 }
                   6432:             }
                   6433:         }
1.970     raeburn  6434:         my ($group);
                   6435:         if (&is_course($domain,$user)) {
                   6436:             ($group,my $file) = split(/\//,$file_name,2);
                   6437:         }
1.749     raeburn  6438:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6439:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6440:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6441:         #  remove lock
                   6442:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6443:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6444:         my $sqlresult =
1.970     raeburn  6445:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6446:                                     $group);
1.749     raeburn  6447:     } else {
                   6448:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6449:     }
1.749     raeburn  6450:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6451: }
                   6452: 
1.827     raeburn  6453: sub make_public_indefinitely {
                   6454:     my ($requrl) = @_;
                   6455:     my $now = time;
                   6456:     my $action = 'activate';
                   6457:     my $aclnum = 0;
                   6458:     if (&is_portfolio_url($requrl)) {
                   6459:         my (undef,$udom,$unum,$file_name,$group) =
                   6460:             &parse_portfolio_url($requrl);
                   6461:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6462:         my %access_controls = &get_access_controls($current_perms,
                   6463:                                                    $group,$file_name);
                   6464:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6465:             my ($num,$scope,$end,$start) = 
                   6466:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6467:             if ($scope eq 'public') {
                   6468:                 if ($start <= $now && $end == 0) {
                   6469:                     $action = 'none';
                   6470:                 } else {
                   6471:                     $action = 'update';
                   6472:                     $aclnum = $num;
                   6473:                 }
                   6474:                 last;
                   6475:             }
                   6476:         }
                   6477:         if ($action eq 'none') {
                   6478:              return 'ok';
                   6479:         } else {
                   6480:             my %changes;
                   6481:             my $newend = 0;
                   6482:             my $newstart = $now;
                   6483:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6484:             $changes{$action}{$newkey} = {
                   6485:                 type => 'public',
                   6486:                 time => {
                   6487:                     start => $newstart,
                   6488:                     end   => $newend,
                   6489:                 },
                   6490:             };
                   6491:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6492:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6493:             return $outcome;
                   6494:         }
                   6495:     } else {
                   6496:         return 'invalid';
                   6497:     }
                   6498: }
                   6499: 
1.745     raeburn  6500: #------------------------------------------------------Get Marked as Read Only
                   6501: 
                   6502: sub get_marked_as_readonly {
                   6503:     my ($domain,$user,$what,$group) = @_;
                   6504:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6505:     my @readonly_files;
1.629     banghart 6506:     my $cmp1=$what;
                   6507:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6508:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6509:         if (defined($group)) {
                   6510:             if ($file_name !~ m-^\Q$group\E/-) {
                   6511:                 next;
                   6512:             }
                   6513:         }
1.561     banghart 6514:         if (ref($value) eq "ARRAY"){
                   6515:             foreach my $stored_what (@{$value}) {
1.629     banghart 6516:                 my $cmp2=$stored_what;
1.759     albertel 6517:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6518:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6519:                 }
1.629     banghart 6520:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6521:                     push(@readonly_files, $file_name);
1.745     raeburn  6522:                     last;
1.563     banghart 6523:                 } elsif (!defined($what)) {
                   6524:                     push(@readonly_files, $file_name);
1.745     raeburn  6525:                     last;
1.561     banghart 6526:                 }
                   6527:             }
1.745     raeburn  6528:         }
1.561     banghart 6529:     }
                   6530:     return @readonly_files;
                   6531: }
1.577     banghart 6532: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6533: 
1.577     banghart 6534: sub get_marked_as_readonly_hash {
1.745     raeburn  6535:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6536:     my %readonly_files;
1.745     raeburn  6537:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6538:         if (defined($group)) {
                   6539:             if ($file_name !~ m-^\Q$group\E/-) {
                   6540:                 next;
                   6541:             }
                   6542:         }
1.577     banghart 6543:         if (ref($value) eq "ARRAY"){
                   6544:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6545:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6546:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6547:                         if ($lock_descriptor eq 'graded') {
                   6548:                             $readonly_files{$file_name} = 'graded';
                   6549:                         } elsif ($lock_descriptor eq 'handback') {
                   6550:                             $readonly_files{$file_name} = 'handback';
                   6551:                         } else {
                   6552:                             if (!exists($readonly_files{$file_name})) {
                   6553:                                 $readonly_files{$file_name} = 'locked';
                   6554:                             }
                   6555:                         }
1.745     raeburn  6556:                     }
1.750     banghart 6557:                 } 
1.577     banghart 6558:             }
                   6559:         } 
                   6560:     }
                   6561:     return %readonly_files;
                   6562: }
1.559     banghart 6563: # ------------------------------------------------------------ Unmark as Read Only
                   6564: 
                   6565: sub unmark_as_readonly {
1.629     banghart 6566:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6567:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6568:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6569:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6570:     my $symb_crs = $what;
                   6571:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6572:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6573:     my ($tmp)=keys(%current_permissions);
                   6574:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6575:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6576:     foreach my $file (@readonly_files) {
1.759     albertel 6577: 	my $clean_file = &declutter_portfile($file);
                   6578: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6579: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6580:         my @new_locks;
                   6581:         my @del_keys;
                   6582:         if (ref($current_locks) eq "ARRAY"){
                   6583:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6584:                 my $compare=$locker;
1.749     raeburn  6585:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6586:                     $compare=join('',@{$locker});
1.746     raeburn  6587:                     if ($compare ne $symb_crs) {
                   6588:                         push(@new_locks, $locker);
                   6589:                     }
1.563     banghart 6590:                 }
                   6591:             }
1.650     albertel 6592:             if (scalar(@new_locks) > 0) {
1.563     banghart 6593:                 $current_permissions{$file} = \@new_locks;
                   6594:             } else {
                   6595:                 push(@del_keys, $file);
1.613     albertel 6596:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6597:                 delete($current_permissions{$file});
1.563     banghart 6598:             }
                   6599:         }
1.561     banghart 6600:     }
1.613     albertel 6601:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6602:     return;
                   6603: }
1.512     banghart 6604: 
1.17      www      6605: # ------------------------------------------------------------ Directory lister
                   6606: 
                   6607: sub dirlist {
1.955     raeburn  6608:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6609:     $uri=~s/^\///;
                   6610:     $uri=~s/\/$//;
1.253     stredwic 6611:     my ($udom, $uname);
1.955     raeburn  6612:     if ($getuserdir) {
1.253     stredwic 6613:         $udom = $userdomain;
                   6614:         $uname = $username;
1.955     raeburn  6615:     } else {
                   6616:         (undef,$udom,$uname)=split(/\//,$uri);
                   6617:         if(defined($userdomain)) {
                   6618:             $udom = $userdomain;
                   6619:         }
                   6620:         if(defined($username)) {
                   6621:             $uname = $username;
                   6622:         }
1.253     stredwic 6623:     }
1.955     raeburn  6624:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6625: 
1.955     raeburn  6626:     $dirRoot = $perlvar{'lonDocRoot'};
                   6627:     if (defined($getpropath)) {
                   6628:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6629:         $dirRoot =~ s/\/$//;
1.955     raeburn  6630:     } elsif (defined($getuserdir)) {
                   6631:         my $subdir=$uname.'__';
                   6632:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6633:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6634:                    ."/$udom/$subdir/$uname";
                   6635:     } elsif (defined($alternateRoot)) {
                   6636:         $dirRoot = $alternateRoot;
1.751     banghart 6637:     }
1.253     stredwic 6638: 
                   6639:     if($udom) {
                   6640:         if($uname) {
1.955     raeburn  6641:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6642:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6643:                               .':'.&escape($uname).':'.&escape($udom),
                   6644:                               &homeserver($uname,$udom));
                   6645:             if ($listing eq 'unknown_cmd') {
                   6646:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6647:                                   &homeserver($uname,$udom));
                   6648:             } else {
                   6649:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6650:             }
1.605     matthew  6651:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6652:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6653: 				  &homeserver($uname,$udom));
1.605     matthew  6654:                 @listing_results = split(/:/,$listing);
                   6655:             } else {
                   6656:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6657:             }
                   6658:             return @listing_results;
1.955     raeburn  6659:         } elsif(!$alternateRoot) {
1.800     albertel 6660:             my %allusers;
1.841     albertel 6661: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6662:  	    foreach my $tryserver (keys(%servers)) {
                   6663:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6664:                                   &escape($udom),$tryserver);
                   6665:                 if ($listing eq 'unknown_cmd') {
                   6666: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6667: 				      $udom, $tryserver);
                   6668:                 } else {
                   6669:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6670:                 }
1.841     albertel 6671: 		if ($listing eq 'unknown_cmd') {
                   6672: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6673: 				      $udom, $tryserver);
                   6674: 		    @listing_results = split(/:/,$listing);
                   6675: 		} else {
                   6676: 		    @listing_results =
                   6677: 			map { &unescape($_); } split(/:/,$listing);
                   6678: 		}
                   6679: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6680: 		    $listing_results[0] ne 'empty'       &&
                   6681: 		    $listing_results[0] ne 'con_lost') {
                   6682: 		    foreach my $line (@listing_results) {
                   6683: 			my ($entry) = split(/&/,$line,2);
                   6684: 			$allusers{$entry} = 1;
                   6685: 		    }
                   6686: 		}
1.253     stredwic 6687:             }
                   6688:             my $alluserstr='';
1.800     albertel 6689:             foreach my $user (sort(keys(%allusers))) {
                   6690:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6691:             }
                   6692:             $alluserstr=~s/:$//;
                   6693:             return split(/:/,$alluserstr);
                   6694:         } else {
1.800     albertel 6695:             return ('missing user name');
1.253     stredwic 6696:         }
1.955     raeburn  6697:     } elsif(!defined($getpropath)) {
1.841     albertel 6698:         my @all_domains = sort(&all_domains());
1.955     raeburn  6699:         foreach my $domain (@all_domains) {
                   6700:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6701:         }
                   6702:         return @all_domains;
                   6703:     } else {
1.800     albertel 6704:         return ('missing domain');
1.275     stredwic 6705:     }
                   6706: }
                   6707: 
                   6708: # --------------------------------------------- GetFileTimestamp
                   6709: # This function utilizes dirlist and returns the date stamp for
                   6710: # when it was last modified.  It will also return an error of -1
                   6711: # if an error occurs
                   6712: 
                   6713: sub GetFileTimestamp {
1.955     raeburn  6714:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6715:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6716:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6717:     my ($fileStat) = 
                   6718:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6719:                                  undef,$getuserdir);
1.275     stredwic 6720:     my @stats = split('&', $fileStat);
                   6721:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6722:         # @stats contains first the filename, then the stat output
                   6723:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6724:     } else {
                   6725:         return -1;
1.253     stredwic 6726:     }
1.26      www      6727: }
                   6728: 
1.712     albertel 6729: sub stat_file {
                   6730:     my ($uri) = @_;
1.787     albertel 6731:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6732: 
1.955     raeburn  6733:     my ($udom,$uname,$file);
1.712     albertel 6734:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6735: 	($udom,$uname,$file) =
1.811     albertel 6736: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6737: 	$file = 'userfiles/'.$file;
                   6738:     }
                   6739:     if ($uri =~ m-^/res/-) {
                   6740: 	($udom,$uname) = 
1.807     albertel 6741: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6742: 	$file = $uri;
                   6743:     }
                   6744: 
                   6745:     if (!$udom || !$uname || !$file) {
                   6746: 	# unable to handle the uri
                   6747: 	return ();
                   6748:     }
1.956     raeburn  6749:     my $getpropath;
                   6750:     if ($file =~ /^userfiles\//) {
                   6751:         $getpropath = 1;
                   6752:     }
1.955     raeburn  6753:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6754:     my @stats = split('&', $result);
1.721     banghart 6755:     
1.712     albertel 6756:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6757: 	shift(@stats); #filename is first
                   6758: 	return @stats;
                   6759:     }
                   6760:     return ();
                   6761: }
                   6762: 
1.26      www      6763: # -------------------------------------------------------- Value of a Condition
                   6764: 
1.713     albertel 6765: # gets the value of a specific preevaluated condition
                   6766: #    stored in the string  $env{user.state.<cid>}
                   6767: # or looks up a condition reference in the bighash and if if hasn't
                   6768: # already been evaluated recurses into docondval to get the value of
                   6769: # the condition, then memoizing it to 
                   6770: #   $env{user.state.<cid>.<condition>}
1.40      www      6771: sub directcondval {
                   6772:     my $number=shift;
1.620     albertel 6773:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6774: 	&Apache::lonuserstate::evalstate();
                   6775:     }
1.713     albertel 6776:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6777: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6778:     } elsif ($number =~ /^_/) {
                   6779: 	my $sub_condition;
                   6780: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6781: 		&GDBM_READER(),0640)) {
                   6782: 	    $sub_condition=$bighash{'conditions'.$number};
                   6783: 	    untie(%bighash);
                   6784: 	}
                   6785: 	my $value = &docondval($sub_condition);
1.949     raeburn  6786: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6787: 	return $value;
                   6788:     }
1.620     albertel 6789:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6790:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6791:     } else {
                   6792:        return 2;
                   6793:     }
                   6794: }
                   6795: 
1.713     albertel 6796: # get the collection of conditions for this resource
1.26      www      6797: sub condval {
                   6798:     my $condidx=shift;
1.54      www      6799:     my $allpathcond='';
1.713     albertel 6800:     foreach my $cond (split(/\|/,$condidx)) {
                   6801: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6802: 	    $allpathcond.=
                   6803: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6804: 	}
1.191     harris41 6805:     }
1.54      www      6806:     $allpathcond=~s/\|$//;
1.713     albertel 6807:     return &docondval($allpathcond);
                   6808: }
                   6809: 
                   6810: #evaluates an expression of conditions
                   6811: sub docondval {
                   6812:     my ($allpathcond) = @_;
                   6813:     my $result=0;
                   6814:     if ($env{'request.course.id'}
                   6815: 	&& defined($allpathcond)) {
                   6816: 	my $operand='|';
                   6817: 	my @stack;
                   6818: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6819: 	    if ($chunk eq '(') {
                   6820: 		push @stack,($operand,$result);
                   6821: 	    } elsif ($chunk eq ')') {
                   6822: 		my $before=pop @stack;
                   6823: 		if (pop @stack eq '&') {
                   6824: 		    $result=$result>$before?$before:$result;
                   6825: 		} else {
                   6826: 		    $result=$result>$before?$result:$before;
                   6827: 		}
                   6828: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6829: 		$operand=$chunk;
                   6830: 	    } else {
                   6831: 		my $new=directcondval($chunk);
                   6832: 		if ($operand eq '&') {
                   6833: 		    $result=$result>$new?$new:$result;
                   6834: 		} else {
                   6835: 		    $result=$result>$new?$result:$new;
                   6836: 		}
                   6837: 	    }
                   6838: 	}
1.26      www      6839:     }
                   6840:     return $result;
1.421     albertel 6841: }
                   6842: 
                   6843: # ---------------------------------------------------- Devalidate courseresdata
                   6844: 
                   6845: sub devalidatecourseresdata {
                   6846:     my ($coursenum,$coursedomain)=@_;
                   6847:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6848:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6849: }
                   6850: 
1.763     www      6851: 
1.200     www      6852: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6853: #
                   6854: #  Parameters:
                   6855: #      $coursenum    - Number of the course.
                   6856: #      $coursedomain - Domain at which the course was created.
                   6857: #  Returns:
                   6858: #     A hash of the course parameters along (I think) with timestamps
                   6859: #     and version info.
1.877     foxr     6860: 
1.624     albertel 6861: sub get_courseresdata {
                   6862:     my ($coursenum,$coursedomain)=@_;
1.200     www      6863:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6864:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6865:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6866:     my %dumpreply;
1.417     albertel 6867:     unless (defined($cached)) {
1.624     albertel 6868: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6869: 	$result=\%dumpreply;
1.251     albertel 6870: 	my ($tmp) = keys(%dumpreply);
                   6871: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6872: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6873: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6874: 	    return $tmp;
1.416     albertel 6875: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6876: 	    $result=undef;
1.599     albertel 6877: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6878: 	}
                   6879:     }
1.624     albertel 6880:     return $result;
                   6881: }
                   6882: 
1.633     albertel 6883: sub devalidateuserresdata {
                   6884:     my ($uname,$udom)=@_;
                   6885:     my $hashid="$udom:$uname";
                   6886:     &devalidate_cache_new('userres',$hashid);
                   6887: }
                   6888: 
1.624     albertel 6889: sub get_userresdata {
                   6890:     my ($uname,$udom)=@_;
                   6891:     #most student don\'t have any data set, check if there is some data
                   6892:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6893: 
                   6894:     my $hashid="$udom:$uname";
                   6895:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6896:     if (!defined($cached)) {
                   6897: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6898: 	$result=\%resourcedata;
                   6899: 	&do_cache_new('userres',$hashid,$result,600);
                   6900:     }
                   6901:     my ($tmp)=keys(%$result);
                   6902:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6903: 	return $result;
                   6904:     }
                   6905:     #error 2 occurs when the .db doesn't exist
                   6906:     if ($tmp!~/error: 2 /) {
1.672     albertel 6907: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6908: 		 " Trying to get resource data for ".
                   6909: 		 $uname." at ".$udom.": ".
                   6910: 		 $tmp."</font>");
                   6911:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6912: 	#&EXT_cache_set($udom,$uname);
                   6913: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6914: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6915:     }
                   6916:     return $tmp;
                   6917: }
1.879     foxr     6918: #----------------------------------------------- resdata - return resource data
                   6919: #  Purpose:
                   6920: #    Return resource data for either users or for a course.
                   6921: #  Parameters:
                   6922: #     $name      - Course/user name.
                   6923: #     $domain    - Name of the domain the user/course is registered on.
                   6924: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6925: #     @which     - Array of names of resources desired.
                   6926: #  Returns:
                   6927: #     The value of the first reasource in @which that is found in the
                   6928: #     resource hash.
                   6929: #  Exceptional Conditions:
                   6930: #     If the $type passed in is not valid (not the string 'course' or 
                   6931: #     'user', an undefined  reference is returned.
                   6932: #     If none of the resources are found, an undef is returned
1.624     albertel 6933: sub resdata {
                   6934:     my ($name,$domain,$type,@which)=@_;
                   6935:     my $result;
                   6936:     if ($type eq 'course') {
                   6937: 	$result=&get_courseresdata($name,$domain);
                   6938:     } elsif ($type eq 'user') {
                   6939: 	$result=&get_userresdata($name,$domain);
                   6940:     }
                   6941:     if (!ref($result)) { return $result; }    
1.251     albertel 6942:     foreach my $item (@which) {
1.927     albertel 6943: 	if (defined($result->{$item->[0]})) {
                   6944: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6945: 	}
1.250     albertel 6946:     }
1.291     albertel 6947:     return undef;
1.200     www      6948: }
                   6949: 
1.379     matthew  6950: #
                   6951: # EXT resource caching routines
                   6952: #
                   6953: 
                   6954: sub clear_EXT_cache_status {
1.383     albertel 6955:     &delenv('cache.EXT.');
1.379     matthew  6956: }
                   6957: 
                   6958: sub EXT_cache_status {
                   6959:     my ($target_domain,$target_user) = @_;
1.383     albertel 6960:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6961:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6962:         # We know already the user has no data
                   6963:         return 1;
                   6964:     } else {
                   6965:         return 0;
                   6966:     }
                   6967: }
                   6968: 
                   6969: sub EXT_cache_set {
                   6970:     my ($target_domain,$target_user) = @_;
1.383     albertel 6971:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6972:     #&appenv({$cachename => time});
1.379     matthew  6973: }
                   6974: 
1.28      www      6975: # --------------------------------------------------------- Value of a Variable
1.58      www      6976: sub EXT {
1.715     albertel 6977: 
1.395     albertel 6978:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6979:     unless ($varname) { return ''; }
1.218     albertel 6980:     #get real user name/domain, courseid and symb
                   6981:     my $courseid;
1.359     albertel 6982:     my $publicuser;
1.427     www      6983:     if ($symbparm) {
                   6984: 	$symbparm=&get_symb_from_alias($symbparm);
                   6985:     }
1.218     albertel 6986:     if (!($uname && $udom)) {
1.790     albertel 6987:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6988:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6989:     } else {
1.620     albertel 6990: 	$courseid=$env{'request.course.id'};
1.218     albertel 6991:     }
1.48      www      6992:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6993:     my $rest;
1.320     albertel 6994:     if (defined($therest[0])) {
1.48      www      6995:        $rest=join('.',@therest);
                   6996:     } else {
                   6997:        $rest='';
                   6998:     }
1.320     albertel 6999: 
1.57      www      7000:     my $qualifierrest=$qualifier;
                   7001:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7002:     my $spacequalifierrest=$space;
                   7003:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7004:     if ($realm eq 'user') {
1.48      www      7005: # --------------------------------------------------------------- user.resource
                   7006: 	if ($space eq 'resource') {
1.651     albertel 7007: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7008: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7009: 		 &&
1.744     albertel 7010: 		 ($symbparm eq &symbread()) ) {	
                   7011: 		# if we are in the middle of processing the resource the
                   7012: 		# get the value we are planning on committing
                   7013:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7014:                     return $Apache::lonhomework::results{$qualifierrest};
                   7015:                 } else {
                   7016:                     return $Apache::lonhomework::history{$qualifierrest};
                   7017:                 }
1.335     albertel 7018: 	    } else {
1.359     albertel 7019: 		my %restored;
1.620     albertel 7020: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7021: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7022: 		} else {
                   7023: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7024: 		}
1.335     albertel 7025: 		return $restored{$qualifierrest};
                   7026: 	    }
1.48      www      7027: # ----------------------------------------------------------------- user.access
                   7028:         } elsif ($space eq 'access') {
1.218     albertel 7029: 	    # FIXME - not supporting calls for a specific user
1.48      www      7030:             return &allowed($qualifier,$rest);
                   7031: # ------------------------------------------ user.preferences, user.environment
                   7032:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7033: 	    if (($uname eq $env{'user.name'}) &&
                   7034: 		($udom eq $env{'user.domain'})) {
                   7035: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7036: 	    } else {
1.359     albertel 7037: 		my %returnhash;
                   7038: 		if (!$publicuser) {
                   7039: 		    %returnhash=&userenvironment($udom,$uname,
                   7040: 						 $qualifierrest);
                   7041: 		}
1.218     albertel 7042: 		return $returnhash{$qualifierrest};
                   7043: 	    }
1.48      www      7044: # ----------------------------------------------------------------- user.course
                   7045:         } elsif ($space eq 'course') {
1.218     albertel 7046: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7047:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7048: # ------------------------------------------------------------------- user.role
                   7049:         } elsif ($space eq 'role') {
1.218     albertel 7050: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7051:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7052:             if ($qualifier eq 'value') {
                   7053: 		return $role;
                   7054:             } elsif ($qualifier eq 'extent') {
                   7055:                 return $where;
                   7056:             }
                   7057: # ----------------------------------------------------------------- user.domain
                   7058:         } elsif ($space eq 'domain') {
1.218     albertel 7059:             return $udom;
1.48      www      7060: # ------------------------------------------------------------------- user.name
                   7061:         } elsif ($space eq 'name') {
1.218     albertel 7062:             return $uname;
1.48      www      7063: # ---------------------------------------------------- Any other user namespace
1.29      www      7064:         } else {
1.359     albertel 7065: 	    my %reply;
                   7066: 	    if (!$publicuser) {
                   7067: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7068: 	    }
                   7069: 	    return $reply{$qualifierrest};
1.48      www      7070:         }
1.236     www      7071:     } elsif ($realm eq 'query') {
                   7072: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7073:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7074: 						[$spacequalifierrest]);
1.620     albertel 7075: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7076:    } elsif ($realm eq 'request') {
1.48      www      7077: # ------------------------------------------------------------- request.browser
                   7078:         if ($space eq 'browser') {
1.430     www      7079: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7080: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7081: 		    return 1;
                   7082: 		} else {
                   7083: 		    return 0;
                   7084: 		}
                   7085: 	    } else {
1.620     albertel 7086: 		return $env{'browser.'.$qualifier};
1.430     www      7087: 	    }
1.57      www      7088: # ------------------------------------------------------------ request.filename
                   7089:         } else {
1.620     albertel 7090:             return $env{'request.'.$spacequalifierrest};
1.29      www      7091:         }
1.28      www      7092:     } elsif ($realm eq 'course') {
1.48      www      7093: # ---------------------------------------------------------- course.description
1.620     albertel 7094:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7095:     } elsif ($realm eq 'resource') {
1.165     www      7096: 
1.620     albertel 7097: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7098: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7099: 	}
1.693     albertel 7100: 
                   7101: 	if ($space eq 'title') {
                   7102: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7103: 	    return &gettitle($symbparm);
                   7104: 	}
                   7105: 	
                   7106: 	if ($space eq 'map') {
                   7107: 	    my ($map) = &decode_symb($symbparm);
                   7108: 	    return &symbread($map);
                   7109: 	}
1.905     albertel 7110: 	if ($space eq 'filename') {
                   7111: 	    if ($symbparm) {
                   7112: 		return &clutter((&decode_symb($symbparm))[2]);
                   7113: 	    }
                   7114: 	    return &hreflocation('',$env{'request.filename'});
                   7115: 	}
1.693     albertel 7116: 
                   7117: 	my ($section, $group, @groups);
1.593     albertel 7118: 	my ($courselevelm,$courselevel);
1.539     albertel 7119: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7120: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7121: 
1.218     albertel 7122: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7123: 
1.60      www      7124: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7125: 	    my $symbp=$symbparm;
1.735     albertel 7126: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7127: 
                   7128: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7129: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7130: 
1.620     albertel 7131: 	    if (($env{'user.name'} eq $uname) &&
                   7132: 		($env{'user.domain'} eq $udom)) {
                   7133: 		$section=$env{'request.course.sec'};
1.733     raeburn  7134:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7135:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7136: 	    } else {
1.539     albertel 7137: 		if (! defined($usection)) {
1.551     albertel 7138: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7139: 		} else {
                   7140: 		    $section = $usection;
                   7141: 		}
1.733     raeburn  7142:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7143: 	    }
                   7144: 
                   7145: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7146: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7147: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7148: 
1.593     albertel 7149: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7150: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7151: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7152: 
1.60      www      7153: # ----------------------------------------------------------- first, check user
1.624     albertel 7154: 
                   7155: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7156: 				       ([$courselevelr,'resource'],
                   7157: 					[$courselevelm,'map'     ],
                   7158: 					[$courselevel, 'course'  ]));
1.931     albertel 7159: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7160: 
1.594     albertel 7161: # ------------------------------------------------ second, check some of course
1.684     raeburn  7162:             my $coursereply;
1.691     raeburn  7163:             if (@groups > 0) {
                   7164:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7165:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7166:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7167:             }
1.96      www      7168: 
1.684     raeburn  7169: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7170: 				  $env{'course.'.$courseid.'.domain'},
                   7171: 				  'course',
                   7172: 				  ([$seclevelr,   'resource'],
                   7173: 				   [$seclevelm,   'map'     ],
                   7174: 				   [$seclevel,    'course'  ],
                   7175: 				   [$courselevelr,'resource']));
                   7176: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7177: 
1.60      www      7178: # ------------------------------------------------------ third, check map parms
1.218     albertel 7179: 	    my %parmhash=();
                   7180: 	    my $thisparm='';
                   7181: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7182: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7183: 		    &GDBM_READER(),0640)) {
1.218     albertel 7184: 		$thisparm=$parmhash{$symbparm};
                   7185: 		untie(%parmhash);
                   7186: 	    }
1.927     albertel 7187: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7188: 	}
1.594     albertel 7189: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7190: 
1.218     albertel 7191: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7192: 	my $filename;
                   7193: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7194: 	if ($symbparm) {
1.409     www      7195: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7196: 	} else {
1.620     albertel 7197: 	    $filename=$env{'request.filename'};
1.282     albertel 7198: 	}
                   7199: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7200: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7201: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7202: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7203: 
1.927     albertel 7204: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7205: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7206: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7207: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7208: 				     $env{'course.'.$courseid.'.domain'},
                   7209: 				     'course',
1.927     albertel 7210: 				     ([$courselevelm,'map'   ],
                   7211: 				      [$courselevel, 'course']));
                   7212: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7213: 	}
1.145     www      7214: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7215: 	unless ($space eq '0') {
1.336     albertel 7216: 	    my @parts=split(/_/,$space);
                   7217: 	    my $id=pop(@parts);
                   7218: 	    my $part=join('_',@parts);
                   7219: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7220: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7221: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7222: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7223: 	}
1.395     albertel 7224: 	if ($recurse) { return undef; }
                   7225: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7226: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7227: # ---------------------------------------------------- Any other user namespace
                   7228:     } elsif ($realm eq 'environment') {
                   7229: # ----------------------------------------------------------------- environment
1.620     albertel 7230: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7231: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7232: 	} else {
1.770     albertel 7233: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7234: 		return '';
                   7235: 	    }
1.219     albertel 7236: 	    my %returnhash=&userenvironment($udom,$uname,
                   7237: 					    $spacequalifierrest);
                   7238: 	    return $returnhash{$spacequalifierrest};
                   7239: 	}
1.28      www      7240:     } elsif ($realm eq 'system') {
1.48      www      7241: # ----------------------------------------------------------------- system.time
                   7242: 	if ($space eq 'time') {
                   7243: 	    return time;
                   7244:         }
1.696     albertel 7245:     } elsif ($realm eq 'server') {
                   7246: # ----------------------------------------------------------------- system.time
                   7247: 	if ($space eq 'name') {
                   7248: 	    return $ENV{'SERVER_NAME'};
                   7249:         }
1.28      www      7250:     }
1.48      www      7251:     return '';
1.61      www      7252: }
                   7253: 
1.927     albertel 7254: sub get_reply {
                   7255:     my ($reply_value) = @_;
1.940     raeburn  7256:     if (ref($reply_value) eq 'ARRAY') {
                   7257:         if (wantarray) {
                   7258: 	    return @$reply_value;
                   7259:         }
                   7260:         return $reply_value->[0];
                   7261:     } else {
                   7262:         return $reply_value;
1.927     albertel 7263:     }
                   7264: }
                   7265: 
1.691     raeburn  7266: sub check_group_parms {
                   7267:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7268:     my @groupitems = ();
                   7269:     my $resultitem;
1.927     albertel 7270:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7271:     foreach my $group (@{$groups}) {
                   7272:         foreach my $level (@levels) {
1.927     albertel 7273:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7274:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7275:         }
                   7276:     }
                   7277:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7278:                             $env{'course.'.$courseid.'.domain'},
                   7279:                                      'course',@groupitems);
                   7280:     return $coursereply;
                   7281: }
                   7282: 
                   7283: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7284:     my ($courseid,@groups) = @_;
                   7285:     @groups = sort(@groups);
1.691     raeburn  7286:     return @groups;
                   7287: }
                   7288: 
1.395     albertel 7289: sub packages_tab_default {
                   7290:     my ($uri,$varname)=@_;
                   7291:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7292: 
                   7293:     my (@extension,@specifics,$do_default);
                   7294:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7295: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7296: 	if ($pack_type eq 'default') {
                   7297: 	    $do_default=1;
                   7298: 	} elsif ($pack_type eq 'extension') {
                   7299: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7300: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7301: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7302: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7303: 	}
                   7304:     }
                   7305:     # first look for a package that matches the requested part id
                   7306:     foreach my $package (@specifics) {
                   7307: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7308: 	next if ($pack_part ne $part);
                   7309: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7310: 	    return $packagetab{"$pack_type&$name&default"};
                   7311: 	}
                   7312:     }
                   7313:     # look for any possible matching non extension_ package
                   7314:     foreach my $package (@specifics) {
                   7315: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7316: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7317: 	    return $packagetab{"$pack_type&$name&default"};
                   7318: 	}
1.585     albertel 7319: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7320: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7321: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7322: 	}
                   7323:     }
1.738     albertel 7324:     # look for any posible extension_ match
                   7325:     foreach my $package (@extension) {
                   7326: 	my ($package,$pack_type)=@{$package};
                   7327: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7328: 	    return $packagetab{"$pack_type&$name&default"};
                   7329: 	}
                   7330: 	if (defined($packagetab{$package."&$name&default"})) {
                   7331: 	    return $packagetab{$package."&$name&default"};
                   7332: 	}
                   7333:     }
                   7334:     # look for a global default setting
                   7335:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7336: 	return $packagetab{"default&$name&default"};
                   7337:     }
1.395     albertel 7338:     return undef;
                   7339: }
                   7340: 
1.334     albertel 7341: sub add_prefix_and_part {
                   7342:     my ($prefix,$part)=@_;
                   7343:     my $keyroot;
                   7344:     if (defined($prefix) && $prefix !~ /^__/) {
                   7345: 	# prefix that has a part already
                   7346: 	$keyroot=$prefix;
                   7347:     } elsif (defined($prefix)) {
                   7348: 	# prefix that is missing a part
                   7349: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7350:     } else {
                   7351: 	# no prefix at all
                   7352: 	if (defined($part)) { $keyroot='_'.$part; }
                   7353:     }
                   7354:     return $keyroot;
                   7355: }
                   7356: 
1.71      www      7357: # ---------------------------------------------------------------- Get metadata
                   7358: 
1.599     albertel 7359: my %metaentry;
1.71      www      7360: sub metadata {
1.176     www      7361:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7362:     $uri=&declutter($uri);
1.288     albertel 7363:     # if it is a non metadata possible uri return quickly
1.529     albertel 7364:     if (($uri eq '') || 
                   7365: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7366: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7367:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7368: 	return undef;
                   7369:     }
                   7370:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7371: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7372: 	return undef;
1.288     albertel 7373:     }
1.73      www      7374:     my $filename=$uri;
                   7375:     $uri=~s/\.meta$//;
1.172     www      7376: #
                   7377: # Is the metadata already cached?
1.177     www      7378: # Look at timestamp of caching
1.172     www      7379: # Everything is cached by the main uri, libraries are never directly cached
                   7380: #
1.428     albertel 7381:     if (!defined($liburi)) {
1.599     albertel 7382: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7383: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7384:     }
                   7385:     {
1.172     www      7386: #
                   7387: # Is this a recursive call for a library?
                   7388: #
1.599     albertel 7389: #	if (! exists($metacache{$uri})) {
                   7390: #	    $metacache{$uri}={};
                   7391: #	}
1.924     albertel 7392: 	my $cachetime = 60*60;
1.171     www      7393:         if ($liburi) {
                   7394: 	    $liburi=&declutter($liburi);
                   7395:             $filename=$liburi;
1.401     bowersj2 7396:         } else {
1.599     albertel 7397: 	    &devalidate_cache_new('meta',$uri);
                   7398: 	    undef(%metaentry);
1.401     bowersj2 7399: 	}
1.140     www      7400:         my %metathesekeys=();
1.73      www      7401:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7402: 	my $metastring;
1.924     albertel 7403: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7404: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7405: 	    $metastring = 
1.929     albertel 7406: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7407: 					  ('grade_target' => 'meta'));
                   7408: 	    $cachetime = 1; # only want this cached in the child not long term
                   7409: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7410: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7411: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7412: 	    $metastring=&getfile($file);
1.489     albertel 7413: 	}
1.208     albertel 7414:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7415:         my $token;
1.140     www      7416:         undef %metathesekeys;
1.71      www      7417:         while ($token=$parser->get_token) {
1.339     albertel 7418: 	    if ($token->[0] eq 'S') {
                   7419: 		if (defined($token->[2]->{'package'})) {
1.172     www      7420: #
                   7421: # This is a package - get package info
                   7422: #
1.339     albertel 7423: 		    my $package=$token->[2]->{'package'};
                   7424: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7425: 		    if (defined($token->[2]->{'id'})) { 
                   7426: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7427: 		    }
1.599     albertel 7428: 		    if ($metaentry{':packages'}) {
                   7429: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7430: 		    } else {
1.599     albertel 7431: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7432: 		    }
1.736     albertel 7433: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7434: 			my $part=$keyroot;
                   7435: 			$part=~s/^\_//;
1.736     albertel 7436: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7437: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7438: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7439: 			    # ignore package.tab specified default values
                   7440:                             # here &package_tab_default() will fetch those
                   7441: 			    if ($subp eq 'default') { next; }
1.736     albertel 7442: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7443: 			    my $unikey;
                   7444: 			    if ($pack =~ /_0$/) {
                   7445: 				$unikey='parameter_0_'.$name;
                   7446: 				$part=0;
                   7447: 			    } else {
                   7448: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7449: 			    }
1.339     albertel 7450: 			    if ($subp eq 'display') {
                   7451: 				$value.=' [Part: '.$part.']';
                   7452: 			    }
1.599     albertel 7453: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7454: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7455: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7456: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7457: 			    }
1.599     albertel 7458: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7459: 				$metaentry{':'.$unikey}=
                   7460: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7461: 			    }
1.339     albertel 7462: 			}
                   7463: 		    }
                   7464: 		} else {
1.172     www      7465: #
                   7466: # This is not a package - some other kind of start tag
1.339     albertel 7467: #
                   7468: 		    my $entry=$token->[1];
                   7469: 		    my $unikey;
                   7470: 		    if ($entry eq 'import') {
                   7471: 			$unikey='';
                   7472: 		    } else {
                   7473: 			$unikey=$entry;
                   7474: 		    }
                   7475: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7476: 
                   7477: 		    if (defined($token->[2]->{'id'})) { 
                   7478: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7479: 		    }
1.175     www      7480: 
1.339     albertel 7481: 		    if ($entry eq 'import') {
1.175     www      7482: #
                   7483: # Importing a library here
1.339     albertel 7484: #
                   7485: 			if ($depthcount<20) {
                   7486: 			    my $location=$parser->get_text('/import');
                   7487: 			    my $dir=$filename;
                   7488: 			    $dir=~s|[^/]*$||;
                   7489: 			    $location=&filelocation($dir,$location);
1.736     albertel 7490: 			    my $metadata = 
                   7491: 				&metadata($uri,'keys', $location,$unikey,
                   7492: 					  $depthcount+1);
                   7493: 			    foreach my $meta (split(',',$metadata)) {
                   7494: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7495: 				$metathesekeys{$meta}=1;
1.339     albertel 7496: 			    }
                   7497: 			}
                   7498: 		    } else { 
                   7499: 			
                   7500: 			if (defined($token->[2]->{'name'})) { 
                   7501: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7502: 			}
                   7503: 			$metathesekeys{$unikey}=1;
1.736     albertel 7504: 			foreach my $param (@{$token->[3]}) {
                   7505: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7506: 				$token->[2]->{$param};
1.339     albertel 7507: 			}
                   7508: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7509: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7510: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7511: 		 # only ws inside the tag, and not in default, so use default
                   7512: 		 # as value
1.599     albertel 7513: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7514: 			} elsif ( $internaltext =~ /\S/ ) {
                   7515: 		  # something interesting inside the tag
                   7516: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7517: 			} else {
1.908     albertel 7518: 		  # no interesting values, don't set a default
1.339     albertel 7519: 			}
1.172     www      7520: # end of not-a-package not-a-library import
1.339     albertel 7521: 		    }
1.172     www      7522: # end of not-a-package start tag
1.339     albertel 7523: 		}
1.172     www      7524: # the next is the end of "start tag"
1.339     albertel 7525: 	    }
                   7526: 	}
1.483     albertel 7527: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7528: 	$extension = lc($extension);
                   7529: 	if ($extension eq 'htm') { $extension='html'; }
                   7530: 
1.737     albertel 7531: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7532: 	    #no specific packages #how's our extension
                   7533: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7534: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7535: 					 \%metathesekeys);
                   7536: 	}
1.883     albertel 7537: 
                   7538: 	if (!exists($metaentry{':packages'})
                   7539: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7540: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7541: 		#no specific packages well let's get default then
                   7542: 		if ($key!~/^default&/) { next; }
1.488     albertel 7543: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7544: 					     \%metathesekeys);
                   7545: 	    }
                   7546: 	}
1.338     www      7547: # are there custom rights to evaluate
1.599     albertel 7548: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7549: 
1.338     www      7550:     #
                   7551:     # Importing a rights file here
1.339     albertel 7552:     #
                   7553: 	    unless ($depthcount) {
1.599     albertel 7554: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7555: 		my $dir=$filename;
                   7556: 		$dir=~s|[^/]*$||;
                   7557: 		$location=&filelocation($dir,$location);
1.736     albertel 7558: 		my $rights_metadata =
                   7559: 		    &metadata($uri,'keys',$location,'_rights',
                   7560: 			      $depthcount+1);
                   7561: 		foreach my $rights (split(',',$rights_metadata)) {
                   7562: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7563: 		    $metathesekeys{$rights}=1;
1.339     albertel 7564: 		}
                   7565: 	    }
                   7566: 	}
1.737     albertel 7567: 	# uniqifiy package listing
                   7568: 	my %seen;
                   7569: 	my @uniq_packages =
                   7570: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7571: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7572: 
                   7573: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7574: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7575: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7576: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7577: # this is the end of "was not already recently cached
1.71      www      7578:     }
1.599     albertel 7579:     return $metaentry{':'.$what};
1.261     albertel 7580: }
                   7581: 
1.488     albertel 7582: sub metadata_create_package_def {
1.483     albertel 7583:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7584:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7585:     if ($subp eq 'default') { next; }
                   7586:     
1.599     albertel 7587:     if (defined($metaentry{':packages'})) {
                   7588: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7589:     } else {
1.599     albertel 7590: 	$metaentry{':packages'}=$package;
1.483     albertel 7591:     }
                   7592:     my $value=$packagetab{$key};
                   7593:     my $unikey;
                   7594:     $unikey='parameter_0_'.$name;
1.599     albertel 7595:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7596:     $$metathesekeys{$unikey}=1;
1.599     albertel 7597:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7598: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7599:     }
1.599     albertel 7600:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7601: 	$metaentry{':'.$unikey}=
                   7602: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7603:     }
                   7604: }
                   7605: 
1.261     albertel 7606: sub metadata_generate_part0 {
                   7607:     my ($metadata,$metacache,$uri) = @_;
                   7608:     my %allnames;
1.737     albertel 7609:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7610: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7611: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7612: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7613: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7614: 	    $allnames{$name}=$part;
                   7615: 	  }
                   7616: 	}
                   7617:     }
                   7618:     foreach my $name (keys(%allnames)) {
                   7619:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7620:       my $key=":parameter_0_$name";
1.261     albertel 7621:       $$metacache{"$key.part"}='0';
                   7622:       $$metacache{"$key.name"}=$name;
1.428     albertel 7623:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7624: 					   $allnames{$name}.'_'.$name.
                   7625: 					   '.type'};
1.428     albertel 7626:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7627: 			     '.display'};
1.644     www      7628:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7629:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7630:       $$metacache{"$key.display"}=$olddis;
                   7631:     }
1.71      www      7632: }
                   7633: 
1.764     albertel 7634: # ------------------------------------------------------ Devalidate title cache
                   7635: 
                   7636: sub devalidate_title_cache {
                   7637:     my ($url)=@_;
                   7638:     if (!$env{'request.course.id'}) { return; }
                   7639:     my $symb=&symbread($url);
                   7640:     if (!$symb) { return; }
                   7641:     my $key=$env{'request.course.id'}."\0".$symb;
                   7642:     &devalidate_cache_new('title',$key);
                   7643: }
                   7644: 
1.301     www      7645: # ------------------------------------------------- Get the title of a resource
                   7646: 
                   7647: sub gettitle {
                   7648:     my $urlsymb=shift;
                   7649:     my $symb=&symbread($urlsymb);
1.534     albertel 7650:     if ($symb) {
1.620     albertel 7651: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7652: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7653: 	if (defined($cached)) { 
                   7654: 	    return $result;
                   7655: 	}
1.534     albertel 7656: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7657: 	my $title='';
1.907     albertel 7658: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7659: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7660: 	} else {
                   7661: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7662: 		    &GDBM_READER(),0640)) {
                   7663: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7664: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7665: 		untie(%bighash);
                   7666: 	    }
1.534     albertel 7667: 	}
                   7668: 	$title=~s/\&colon\;/\:/gs;
                   7669: 	if ($title) {
1.599     albertel 7670: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7671: 	}
                   7672: 	$urlsymb=$url;
                   7673:     }
                   7674:     my $title=&metadata($urlsymb,'title');
                   7675:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7676:     return $title;
1.301     www      7677: }
1.613     albertel 7678: 
1.614     albertel 7679: sub get_slot {
                   7680:     my ($which,$cnum,$cdom)=@_;
                   7681:     if (!$cnum || !$cdom) {
1.790     albertel 7682: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7683: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7684: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7685:     }
1.703     albertel 7686:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7687:     my %slotinfo;
                   7688:     if (exists($remembered{$key})) {
                   7689: 	$slotinfo{$which} = $remembered{$key};
                   7690:     } else {
                   7691: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7692: 	&Apache::lonhomework::showhash(%slotinfo);
                   7693: 	my ($tmp)=keys(%slotinfo);
                   7694: 	if ($tmp=~/^error:/) { return (); }
                   7695: 	$remembered{$key} = $slotinfo{$which};
                   7696:     }
1.616     albertel 7697:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7698: 	return %{$slotinfo{$which}};
                   7699:     }
                   7700:     return $slotinfo{$which};
1.614     albertel 7701: }
1.31      www      7702: # ------------------------------------------------- Update symbolic store links
                   7703: 
                   7704: sub symblist {
                   7705:     my ($mapname,%newhash)=@_;
1.438     www      7706:     $mapname=&deversion(&declutter($mapname));
1.31      www      7707:     my %hash;
1.620     albertel 7708:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7709:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7710:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7711: 	    foreach my $url (keys %newhash) {
                   7712: 		next if ($url eq 'last_known'
                   7713: 			 && $env{'form.no_update_last_known'});
                   7714: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7715: 						    $newhash{$url}->[1],
                   7716: 						    $newhash{$url}->[0]);
1.191     harris41 7717:             }
1.31      www      7718:             if (untie(%hash)) {
                   7719: 		return 'ok';
                   7720:             }
                   7721:         }
                   7722:     }
                   7723:     return 'error';
1.212     www      7724: }
                   7725: 
                   7726: # --------------------------------------------------------------- Verify a symb
                   7727: 
                   7728: sub symbverify {
1.510     www      7729:     my ($symb,$thisurl)=@_;
                   7730:     my $thisfn=$thisurl;
1.439     www      7731:     $thisfn=&declutter($thisfn);
1.215     www      7732: # direct jump to resource in page or to a sequence - will construct own symbs
                   7733:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7734: # check URL part
1.409     www      7735:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7736: 
1.431     www      7737:     unless ($url eq $thisfn) { return 0; }
1.213     www      7738: 
1.216     www      7739:     $symb=&symbclean($symb);
1.510     www      7740:     $thisurl=&deversion($thisurl);
1.439     www      7741:     $thisfn=&deversion($thisfn);
1.213     www      7742: 
                   7743:     my %bighash;
                   7744:     my $okay=0;
1.431     www      7745: 
1.620     albertel 7746:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7747:                             &GDBM_READER(),0640)) {
1.510     www      7748:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7749:         unless ($ids) { 
1.510     www      7750:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7751:         }
                   7752:         if ($ids) {
                   7753: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7754: 	    foreach my $id (split(/\,/,$ids)) {
                   7755: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7756:                if (
                   7757:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7758:    eq $symb) { 
1.620     albertel 7759: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7760: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7761: 		       $okay=1; 
                   7762: 		   }
                   7763: 	       }
1.216     www      7764: 	   }
                   7765:         }
1.213     www      7766: 	untie(%bighash);
                   7767:     }
                   7768:     return $okay;
1.31      www      7769: }
                   7770: 
1.210     www      7771: # --------------------------------------------------------------- Clean-up symb
                   7772: 
                   7773: sub symbclean {
                   7774:     my $symb=shift;
1.568     albertel 7775:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7776: # remove version from map
                   7777:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7778: 
1.210     www      7779: # remove version from URL
                   7780:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7781: 
1.507     www      7782: # remove wrapper
                   7783: 
1.510     www      7784:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7785:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7786:     return $symb;
1.409     www      7787: }
                   7788: 
                   7789: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7790: 
                   7791: sub encode_symb {
                   7792:     my ($map,$resid,$url)=@_;
                   7793:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7794: }
1.409     www      7795: 
                   7796: sub decode_symb {
1.568     albertel 7797:     my $symb=shift;
                   7798:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7799:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7800:     return (&fixversion($map),$resid,&fixversion($url));
                   7801: }
                   7802: 
                   7803: sub fixversion {
                   7804:     my $fn=shift;
1.609     banghart 7805:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7806:     my %bighash;
                   7807:     my $uri=&clutter($fn);
1.620     albertel 7808:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7809: # is this cached?
1.599     albertel 7810:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7811:     if (defined($cached)) { return $result; }
                   7812: # unfortunately not cached, or expired
1.620     albertel 7813:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7814: 	    &GDBM_READER(),0640)) {
                   7815:  	if ($bighash{'version_'.$uri}) {
                   7816:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7817:  	    unless (($version eq 'mostrecent') || 
                   7818: 		    ($version==&getversion($uri))) {
1.440     www      7819:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7820:  	    }
                   7821:  	}
                   7822:  	untie %bighash;
1.413     www      7823:     }
1.599     albertel 7824:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7825: }
                   7826: 
                   7827: sub deversion {
                   7828:     my $url=shift;
                   7829:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7830:     return $url;
1.210     www      7831: }
                   7832: 
1.31      www      7833: # ------------------------------------------------------ Return symb list entry
                   7834: 
                   7835: sub symbread {
1.249     www      7836:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7837:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7838:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7839: # no filename provided? try from environment
1.44      www      7840:     unless ($thisfn) {
1.620     albertel 7841:         if ($env{'request.symb'}) {
                   7842: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7843: 	}
1.620     albertel 7844: 	$thisfn=$env{'request.filename'};
1.44      www      7845:     }
1.569     albertel 7846:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7847: # is that filename actually a symb? Verify, clean, and return
                   7848:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7849: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7850: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7851: 	}
1.242     www      7852:     }
1.44      www      7853:     $thisfn=declutter($thisfn);
1.31      www      7854:     my %hash;
1.37      www      7855:     my %bighash;
                   7856:     my $syval='';
1.620     albertel 7857:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7858:         my $targetfn = $thisfn;
1.609     banghart 7859:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7860:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7861:         }
1.687     albertel 7862: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7863: 	    $targetfn=$1;
                   7864: 	}
1.620     albertel 7865:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7866:                       &GDBM_READER(),0640)) {
1.481     raeburn  7867: 	    $syval=$hash{$targetfn};
1.37      www      7868:             untie(%hash);
                   7869:         }
                   7870: # ---------------------------------------------------------- There was an entry
                   7871:         if ($syval) {
1.601     albertel 7872: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7873: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7874: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7875: 		    #return $env{$cache_str}='';
1.601     albertel 7876: 		#}    
                   7877: 		#$syval.=$1;
                   7878: 	    #}
1.37      www      7879:         } else {
                   7880: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7881:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7882:                             &GDBM_READER(),0640)) {
1.37      www      7883: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7884:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7885:               unless ($ids) { 
                   7886:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7887:               }
                   7888:               unless ($ids) {
                   7889: # alias?
                   7890: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7891:               }
1.37      www      7892:               if ($ids) {
                   7893: # ------------------------------------------------------------------- Has ID(s)
                   7894:                  my @possibilities=split(/\,/,$ids);
1.39      www      7895:                  if ($#possibilities==0) {
                   7896: # ----------------------------------------------- There is only one possibility
1.37      www      7897: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7898: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7899: 						    $resid,$thisfn);
1.249     www      7900:                  } elsif (!$donotrecurse) {
1.39      www      7901: # ------------------------------------------ There is more than one possibility
                   7902:                      my $realpossible=0;
1.800     albertel 7903:                      foreach my $id (@possibilities) {
                   7904: 			 my $file=$bighash{'src_'.$id};
1.39      www      7905:                          if (&allowed('bre',$file)) {
1.800     albertel 7906:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7907:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7908: 				$realpossible++;
1.626     albertel 7909:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7910: 						    $resid,$thisfn);
1.39      www      7911:                             }
                   7912: 			 }
1.191     harris41 7913:                      }
1.39      www      7914: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7915:                  } else {
                   7916:                      $syval='';
1.37      www      7917:                  }
                   7918: 	      }
                   7919:               untie(%bighash)
1.481     raeburn  7920:            }
1.31      www      7921:         }
1.62      www      7922:         if ($syval) {
1.620     albertel 7923: 	    return $env{$cache_str}=$syval;
1.62      www      7924:         }
1.31      www      7925:     }
1.949     raeburn  7926:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7927:     return $env{$cache_str}='';
1.31      www      7928: }
                   7929: 
                   7930: # ---------------------------------------------------------- Return random seed
                   7931: 
1.32      www      7932: sub numval {
                   7933:     my $txt=shift;
                   7934:     $txt=~tr/A-J/0-9/;
                   7935:     $txt=~tr/a-j/0-9/;
                   7936:     $txt=~tr/K-T/0-9/;
                   7937:     $txt=~tr/k-t/0-9/;
                   7938:     $txt=~tr/U-Z/0-5/;
                   7939:     $txt=~tr/u-z/0-5/;
                   7940:     $txt=~s/\D//g;
1.564     albertel 7941:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7942:     return int($txt);
1.368     albertel 7943: }
                   7944: 
1.484     albertel 7945: sub numval2 {
                   7946:     my $txt=shift;
                   7947:     $txt=~tr/A-J/0-9/;
                   7948:     $txt=~tr/a-j/0-9/;
                   7949:     $txt=~tr/K-T/0-9/;
                   7950:     $txt=~tr/k-t/0-9/;
                   7951:     $txt=~tr/U-Z/0-5/;
                   7952:     $txt=~tr/u-z/0-5/;
                   7953:     $txt=~s/\D//g;
                   7954:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7955:     my $total;
                   7956:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7957:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7958:     return int($total);
                   7959: }
                   7960: 
1.575     albertel 7961: sub numval3 {
                   7962:     use integer;
                   7963:     my $txt=shift;
                   7964:     $txt=~tr/A-J/0-9/;
                   7965:     $txt=~tr/a-j/0-9/;
                   7966:     $txt=~tr/K-T/0-9/;
                   7967:     $txt=~tr/k-t/0-9/;
                   7968:     $txt=~tr/U-Z/0-5/;
                   7969:     $txt=~tr/u-z/0-5/;
                   7970:     $txt=~s/\D//g;
                   7971:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7972:     my $total;
                   7973:     foreach my $val (@txts) { $total+=$val; }
                   7974:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7975:     return $total;
                   7976: }
                   7977: 
1.675     albertel 7978: sub digest {
                   7979:     my ($data)=@_;
                   7980:     my $digest=&Digest::MD5::md5($data);
                   7981:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7982:     my ($e,$f);
                   7983:     {
                   7984:         use integer;
                   7985:         $e=($a+$b);
                   7986:         $f=($c+$d);
                   7987:         if ($_64bit) {
                   7988:             $e=(($e<<32)>>32);
                   7989:             $f=(($f<<32)>>32);
                   7990:         }
                   7991:     }
                   7992:     if (wantarray) {
                   7993: 	return ($e,$f);
                   7994:     } else {
                   7995: 	my $g;
                   7996: 	{
                   7997: 	    use integer;
                   7998: 	    $g=($e+$f);
                   7999: 	    if ($_64bit) {
                   8000: 		$g=(($g<<32)>>32);
                   8001: 	    }
                   8002: 	}
                   8003: 	return $g;
                   8004:     }
                   8005: }
                   8006: 
1.368     albertel 8007: sub latest_rnd_algorithm_id {
1.675     albertel 8008:     return '64bit5';
1.366     albertel 8009: }
1.32      www      8010: 
1.503     albertel 8011: sub get_rand_alg {
                   8012:     my ($courseid)=@_;
1.790     albertel 8013:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8014:     if ($courseid) {
1.620     albertel 8015: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8016:     }
                   8017:     return &latest_rnd_algorithm_id();
                   8018: }
                   8019: 
1.562     albertel 8020: sub validCODE {
                   8021:     my ($CODE)=@_;
                   8022:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8023:     return 0;
                   8024: }
                   8025: 
1.491     albertel 8026: sub getCODE {
1.620     albertel 8027:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8028:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8029: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8030: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8031: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8032:     }
                   8033:     return undef;
                   8034: }
                   8035: 
1.31      www      8036: sub rndseed {
1.155     albertel 8037:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8038:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8039:     if (!defined($symb)) {
1.366     albertel 8040: 	unless ($symb=$wsymb) { return time; }
                   8041:     }
                   8042:     if (!$courseid) { $courseid=$wcourseid; }
                   8043:     if (!$domain) { $domain=$wdomain; }
                   8044:     if (!$username) { $username=$wusername }
1.503     albertel 8045:     my $which=&get_rand_alg();
1.803     albertel 8046: 
1.491     albertel 8047:     if (defined(&getCODE())) {
1.675     albertel 8048: 	if ($which eq '64bit5') {
                   8049: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8050: 	} elsif ($which eq '64bit4') {
1.575     albertel 8051: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8052: 	} else {
                   8053: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8054: 	}
1.675     albertel 8055:     } elsif ($which eq '64bit5') {
                   8056: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8057:     } elsif ($which eq '64bit4') {
                   8058: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8059:     } elsif ($which eq '64bit3') {
                   8060: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8061:     } elsif ($which eq '64bit2') {
                   8062: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8063:     } elsif ($which eq '64bit') {
                   8064: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8065:     }
                   8066:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8067: }
                   8068: 
                   8069: sub rndseed_32bit {
                   8070:     my ($symb,$courseid,$domain,$username)=@_;
                   8071:     {
                   8072: 	use integer;
                   8073: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8074: 	my $symbseed=numval($symb) << 22;
                   8075: 	my $namechck=unpack("%32C*",$username) << 17;
                   8076: 	my $nameseed=numval($username) << 12;
                   8077: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8078: 	my $courseseed=unpack("%32C*",$courseid);
                   8079: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8080: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8081: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8082: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8083: 	return $num;
                   8084:     }
                   8085: }
                   8086: 
                   8087: sub rndseed_64bit {
                   8088:     my ($symb,$courseid,$domain,$username)=@_;
                   8089:     {
                   8090: 	use integer;
                   8091: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8092: 	my $symbseed=numval($symb) << 10;
                   8093: 	my $namechck=unpack("%32S*",$username);
                   8094: 	
                   8095: 	my $nameseed=numval($username) << 21;
                   8096: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8097: 	my $courseseed=unpack("%32S*",$courseid);
                   8098: 	
                   8099: 	my $num1=$symbchck+$symbseed+$namechck;
                   8100: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8101: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8102: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8103: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8104: 	return "$num1,$num2";
1.155     albertel 8105:     }
1.366     albertel 8106: }
                   8107: 
1.443     albertel 8108: sub rndseed_64bit2 {
                   8109:     my ($symb,$courseid,$domain,$username)=@_;
                   8110:     {
                   8111: 	use integer;
                   8112: 	# strings need to be an even # of cahracters long, it it is odd the
                   8113:         # last characters gets thrown away
                   8114: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8115: 	my $symbseed=numval($symb) << 10;
                   8116: 	my $namechck=unpack("%32S*",$username.' ');
                   8117: 	
                   8118: 	my $nameseed=numval($username) << 21;
1.501     albertel 8119: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8120: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8121: 	
                   8122: 	my $num1=$symbchck+$symbseed+$namechck;
                   8123: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8124: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8125: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8126: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8127: 	return "$num1,$num2";
                   8128:     }
                   8129: }
                   8130: 
                   8131: sub rndseed_64bit3 {
                   8132:     my ($symb,$courseid,$domain,$username)=@_;
                   8133:     {
                   8134: 	use integer;
                   8135: 	# strings need to be an even # of cahracters long, it it is odd the
                   8136:         # last characters gets thrown away
                   8137: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8138: 	my $symbseed=numval2($symb) << 10;
                   8139: 	my $namechck=unpack("%32S*",$username.' ');
                   8140: 	
                   8141: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8142: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8143: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8144: 	
                   8145: 	my $num1=$symbchck+$symbseed+$namechck;
                   8146: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8147: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8148: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8149: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8150: 	
1.503     albertel 8151: 	return "$num1:$num2";
1.443     albertel 8152:     }
                   8153: }
                   8154: 
1.575     albertel 8155: sub rndseed_64bit4 {
                   8156:     my ($symb,$courseid,$domain,$username)=@_;
                   8157:     {
                   8158: 	use integer;
                   8159: 	# strings need to be an even # of cahracters long, it it is odd the
                   8160:         # last characters gets thrown away
                   8161: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8162: 	my $symbseed=numval3($symb) << 10;
                   8163: 	my $namechck=unpack("%32S*",$username.' ');
                   8164: 	
                   8165: 	my $nameseed=numval3($username) << 21;
                   8166: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8167: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8168: 	
                   8169: 	my $num1=$symbchck+$symbseed+$namechck;
                   8170: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8171: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8172: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8173: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8174: 	
                   8175: 	return "$num1:$num2";
                   8176:     }
                   8177: }
                   8178: 
1.675     albertel 8179: sub rndseed_64bit5 {
                   8180:     my ($symb,$courseid,$domain,$username)=@_;
                   8181:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8182:     return "$num1:$num2";
                   8183: }
                   8184: 
1.366     albertel 8185: sub rndseed_CODE_64bit {
                   8186:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8187:     {
1.366     albertel 8188: 	use integer;
1.443     albertel 8189: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8190: 	my $symbseed=numval2($symb);
1.491     albertel 8191: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8192: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8193: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8194: 	my $num1=$symbseed+$CODEchck;
                   8195: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8196: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8197: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8198: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8199: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8200: 	return "$num1:$num2";
1.366     albertel 8201:     }
                   8202: }
                   8203: 
1.575     albertel 8204: sub rndseed_CODE_64bit4 {
                   8205:     my ($symb,$courseid,$domain,$username)=@_;
                   8206:     {
                   8207: 	use integer;
                   8208: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8209: 	my $symbseed=numval3($symb);
                   8210: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8211: 	my $CODEseed=numval3(&getCODE());
                   8212: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8213: 	my $num1=$symbseed+$CODEchck;
                   8214: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8215: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8216: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8217: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8218: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8219: 	return "$num1:$num2";
                   8220:     }
                   8221: }
                   8222: 
1.675     albertel 8223: sub rndseed_CODE_64bit5 {
                   8224:     my ($symb,$courseid,$domain,$username)=@_;
                   8225:     my $code = &getCODE();
                   8226:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8227:     return "$num1:$num2";
                   8228: }
                   8229: 
1.366     albertel 8230: sub setup_random_from_rndseed {
                   8231:     my ($rndseed)=@_;
1.503     albertel 8232:     if ($rndseed =~/([,:])/) {
                   8233: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8234: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8235:     } else {
                   8236: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8237:     }
1.36      albertel 8238: }
                   8239: 
1.474     albertel 8240: sub latest_receipt_algorithm_id {
1.835     albertel 8241:     return 'receipt3';
1.474     albertel 8242: }
                   8243: 
1.480     www      8244: sub recunique {
                   8245:     my $fucourseid=shift;
                   8246:     my $unique;
1.835     albertel 8247:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8248: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8249: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8250:     } else {
                   8251: 	$unique=$perlvar{'lonReceipt'};
                   8252:     }
                   8253:     return unpack("%32C*",$unique);
                   8254: }
                   8255: 
                   8256: sub recprefix {
                   8257:     my $fucourseid=shift;
                   8258:     my $prefix;
1.835     albertel 8259:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8260: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8261: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8262:     } else {
                   8263: 	$prefix=$perlvar{'lonHostID'};
                   8264:     }
                   8265:     return unpack("%32C*",$prefix);
                   8266: }
                   8267: 
1.76      www      8268: sub ireceipt {
1.474     albertel 8269:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8270: 
                   8271:     my $return =&recprefix($fucourseid).'-';
                   8272: 
                   8273:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8274: 	$env{'request.state'} eq 'construct') {
                   8275: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8276: 	return $return;
                   8277:     }
                   8278: 
1.76      www      8279:     my $cuname=unpack("%32C*",$funame);
                   8280:     my $cudom=unpack("%32C*",$fudom);
                   8281:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8282:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8283:     my $cunique=&recunique($fucourseid);
1.474     albertel 8284:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8285:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8286: 
1.790     albertel 8287: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8288: 			       
                   8289: 	$return.= ($cunique%$cuname+
                   8290: 		   $cunique%$cudom+
                   8291: 		   $cusymb%$cuname+
                   8292: 		   $cusymb%$cudom+
                   8293: 		   $cucourseid%$cuname+
                   8294: 		   $cucourseid%$cudom+
                   8295: 		   $cpart%$cuname+
                   8296: 		   $cpart%$cudom);
                   8297:     } else {
                   8298: 	$return.= ($cunique%$cuname+
                   8299: 		   $cunique%$cudom+
                   8300: 		   $cusymb%$cuname+
                   8301: 		   $cusymb%$cudom+
                   8302: 		   $cucourseid%$cuname+
                   8303: 		   $cucourseid%$cudom);
                   8304:     }
                   8305:     return $return;
1.76      www      8306: }
                   8307: 
                   8308: sub receipt {
1.474     albertel 8309:     my ($part)=@_;
1.790     albertel 8310:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8311:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8312: }
1.260     ng       8313: 
1.790     albertel 8314: sub whichuser {
                   8315:     my ($passedsymb)=@_;
                   8316:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8317:     if (defined($env{'form.grade_symb'})) {
                   8318: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8319: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8320: 	if (!$allowed &&
                   8321: 	    exists($env{'request.course.sec'}) &&
                   8322: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8323: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8324: 			      '/'.$env{'request.course.sec'});
                   8325: 	}
                   8326: 	if ($allowed) {
                   8327: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8328: 	    $courseid=$tmp_courseid;
                   8329: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8330: 	    ($name)=&get_env_multiple('form.grade_username');
                   8331: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8332: 	}
                   8333:     }
                   8334:     if (!$passedsymb) {
                   8335: 	$symb=&symbread();
                   8336:     } else {
                   8337: 	$symb=$passedsymb;
                   8338:     }
                   8339:     $courseid=$env{'request.course.id'};
                   8340:     $domain=$env{'user.domain'};
                   8341:     $name=$env{'user.name'};
                   8342:     if ($name eq 'public' && $domain eq 'public') {
                   8343: 	if (!defined($env{'form.username'})) {
                   8344: 	    $env{'form.username'}.=time.rand(10000000);
                   8345: 	}
                   8346: 	$name.=$env{'form.username'};
                   8347:     }
                   8348:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8349: 
                   8350: }
                   8351: 
1.36      albertel 8352: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8353: # returns either the contents of the file or 
                   8354: # -1 if the file doesn't exist
1.481     raeburn  8355: #
                   8356: # if the target is a file that was uploaded via DOCS, 
                   8357: # a check will be made to see if a current copy exists on the local server,
                   8358: # if it does this will be served, otherwise a copy will be retrieved from
                   8359: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8360: # the local server.   
1.472     albertel 8361: 
1.36      albertel 8362: sub getfile {
1.538     albertel 8363:     my ($file) = @_;
1.609     banghart 8364:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8365:     &repcopy($file);
                   8366:     return &readfile($file);
                   8367: }
                   8368: 
                   8369: sub repcopy_userfile {
                   8370:     my ($file)=@_;
1.609     banghart 8371:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8372:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8373:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8374: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8375:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8376:     if (-e "$file") {
1.828     www      8377: # we already have a local copy, check it out
1.538     albertel 8378: 	my @fileinfo = stat($file);
1.828     www      8379: 	my $rtncode;
                   8380: 	my $info;
1.538     albertel 8381: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8382: 	if ($lwpresp ne 'ok') {
1.828     www      8383: # there is no such file anymore, even though we had a local copy
1.482     albertel 8384: 	    if ($rtncode eq '404') {
1.538     albertel 8385: 		unlink($file);
1.482     albertel 8386: 	    }
                   8387: 	    return -1;
                   8388: 	}
                   8389: 	if ($info < $fileinfo[9]) {
1.828     www      8390: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8391: 	    return 'ok';
1.828     www      8392: 	} else {
                   8393: # the file is outdated, get rid of it
                   8394: 	    unlink($file);
1.482     albertel 8395: 	}
1.828     www      8396:     }
                   8397: # one way or the other, at this point, we don't have the file
                   8398: # construct the correct path for the file
                   8399:     my @parts = ($cdom,$cnum); 
                   8400:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8401: 	push @parts, split(/\//,$1);
                   8402:     }
                   8403:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8404:     foreach my $part (@parts) {
                   8405: 	$path .= '/'.$part;
                   8406: 	if (!-e $path) {
                   8407: 	    mkdir($path,0770);
1.482     albertel 8408: 	}
                   8409:     }
1.828     www      8410: # now the path exists for sure
                   8411: # get a user agent
                   8412:     my $ua=new LWP::UserAgent;
                   8413:     my $transferfile=$file.'.in.transfer';
                   8414: # FIXME: this should flock
                   8415:     if (-e $transferfile) { return 'ok'; }
                   8416:     my $request;
                   8417:     $uri=~s/^\///;
1.980     raeburn  8418:     my $homeserver = &homeserver($cnum,$cdom);
                   8419:     my $protocol = $protocol{$homeserver};
                   8420:     $protocol = 'http' if ($protocol ne 'https');
                   8421:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8422:     my $response=$ua->request($request,$transferfile);
                   8423: # did it work?
                   8424:     if ($response->is_error()) {
                   8425: 	unlink($transferfile);
                   8426: 	&logthis("Userfile repcopy failed for $uri");
                   8427: 	return -1;
                   8428:     }
                   8429: # worked, rename the transfer file
                   8430:     rename($transferfile,$file);
1.607     raeburn  8431:     return 'ok';
1.481     raeburn  8432: }
                   8433: 
1.517     albertel 8434: sub tokenwrapper {
                   8435:     my $uri=shift;
1.980     raeburn  8436:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8437:     $uri=~s|^/||;
1.620     albertel 8438:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8439:     my $token=$1;
1.552     albertel 8440:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8441:     if ($udom && $uname && $file) {
                   8442: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8443:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8444:         my $homeserver = &homeserver($uname,$udom);
                   8445:         my $protocol = $protocol{$homeserver};
                   8446:         $protocol = 'http' if ($protocol ne 'https');
                   8447:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8448:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8449:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8450:     } else {
                   8451:         return '/adm/notfound.html';
                   8452:     }
                   8453: }
                   8454: 
1.828     www      8455: # call with reqtype HEAD: get last modification time
                   8456: # call with reqtype GET: get the file contents
                   8457: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8458: #
1.481     raeburn  8459: sub getuploaded {
                   8460:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8461:     $uri=~s/^\///;
1.980     raeburn  8462:     my $homeserver = &homeserver($cnum,$cdom);
                   8463:     my $protocol = $protocol{$homeserver};
                   8464:     $protocol = 'http' if ($protocol ne 'https');
                   8465:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8466:     my $ua=new LWP::UserAgent;
                   8467:     my $request=new HTTP::Request($reqtype,$uri);
                   8468:     my $response=$ua->request($request);
                   8469:     $$rtncode = $response->code;
1.482     albertel 8470:     if (! $response->is_success()) {
                   8471: 	return 'failed';
                   8472:     }      
                   8473:     if ($reqtype eq 'HEAD') {
1.486     www      8474: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8475:     } elsif ($reqtype eq 'GET') {
                   8476: 	$$info = $response->content;
1.472     albertel 8477:     }
1.482     albertel 8478:     return 'ok';
1.36      albertel 8479: }
                   8480: 
1.481     raeburn  8481: sub readfile {
                   8482:     my $file = shift;
                   8483:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8484:     my $fh;
                   8485:     open($fh,"<$file");
                   8486:     my $a='';
1.800     albertel 8487:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8488:     return $a;
                   8489: }
                   8490: 
1.36      albertel 8491: sub filelocation {
1.590     banghart 8492:     my ($dir,$file) = @_;
                   8493:     my $location;
                   8494:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8495: 
                   8496:     if ($file =~ m-^/adm/-) {
                   8497: 	$file=~s-^/adm/wrapper/-/-;
                   8498: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8499:     }
1.882     albertel 8500: 
1.590     banghart 8501:     if ($file=~m:^/~:) { # is a contruction space reference
                   8502:         $location = $file;
                   8503:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8504:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8505: 	# is a correct contruction space reference
                   8506:         $location = $file;
1.956     raeburn  8507:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8508:         $location = $file;
1.609     banghart 8509:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8510:         my ($udom,$uname,$filename)=
1.811     albertel 8511:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8512:         my $home=&homeserver($uname,$udom);
                   8513:         my $is_me=0;
                   8514:         my @ids=&current_machine_ids();
                   8515:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8516:         if ($is_me) {
1.955     raeburn  8517:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8518:         } else {
                   8519:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8520:   	      $udom.'/'.$uname.'/'.$filename;
                   8521:         }
1.882     albertel 8522:     } elsif ($file =~ m-^/adm/-) {
                   8523: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8524:     } else {
                   8525:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8526:         $file=~s:^/res/:/:;
                   8527:         if ( !( $file =~ m:^/:) ) {
                   8528:             $location = $dir. '/'.$file;
                   8529:         } else {
                   8530:             $location = '/home/httpd/html/res'.$file;
                   8531:         }
1.59      albertel 8532:     }
1.590     banghart 8533:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8534:     while ($location=~m{/\.\./}) {
                   8535: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8536: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8537: 	} else {
                   8538: 	    $location=~ s{/\.\./}{/}g;
                   8539: 	}
                   8540:     } #remove dir/..
1.590     banghart 8541:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8542:     return $location;
1.46      www      8543: }
1.36      albertel 8544: 
1.46      www      8545: sub hreflocation {
                   8546:     my ($dir,$file)=@_;
1.980     raeburn  8547:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8548: 	$file=filelocation($dir,$file);
1.700     albertel 8549:     } elsif ($file=~m-^/adm/-) {
                   8550: 	$file=~s-^/adm/wrapper/-/-;
                   8551: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8552:     }
                   8553:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8554: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8555:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8556: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8557:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8558: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8559: 	    -/uploaded/$1/$2/-x;
1.46      www      8560:     }
1.913     albertel 8561:     if ($file=~ m{^/userfiles/}) {
                   8562: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8563:     }
1.462     albertel 8564:     return $file;
1.465     albertel 8565: }
                   8566: 
                   8567: sub current_machine_domains {
1.853     albertel 8568:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8569: }
                   8570: 
                   8571: sub machine_domains {
                   8572:     my ($hostname) = @_;
1.465     albertel 8573:     my @domains;
1.838     albertel 8574:     my %hostname = &all_hostnames();
1.465     albertel 8575:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8576: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8577: 	if ($hostname eq $name) {
1.844     albertel 8578: 	    push(@domains,&host_domain($id));
1.465     albertel 8579: 	}
                   8580:     }
                   8581:     return @domains;
                   8582: }
                   8583: 
                   8584: sub current_machine_ids {
1.853     albertel 8585:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8586: }
                   8587: 
                   8588: sub machine_ids {
                   8589:     my ($hostname) = @_;
                   8590:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8591:     my @ids;
1.888     albertel 8592:     my %name_to_host = &all_names();
1.889     albertel 8593:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8594: 	return @{ $name_to_host{$hostname} };
                   8595:     }
                   8596:     return;
1.31      www      8597: }
                   8598: 
1.824     raeburn  8599: sub additional_machine_domains {
                   8600:     my @domains;
                   8601:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8602:     while( my $line = <$fh>) {
                   8603:         $line =~ s/\s//g;
                   8604:         push(@domains,$line);
                   8605:     }
                   8606:     return @domains;
                   8607: }
                   8608: 
                   8609: sub default_login_domain {
                   8610:     my $domain = $perlvar{'lonDefDomain'};
                   8611:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8612:     foreach my $posdom (&current_machine_domains(),
                   8613:                         &additional_machine_domains()) {
                   8614:         if (lc($posdom) eq lc($testdomain)) {
                   8615:             $domain=$posdom;
                   8616:             last;
                   8617:         }
                   8618:     }
                   8619:     return $domain;
                   8620: }
                   8621: 
1.31      www      8622: # ------------------------------------------------------------- Declutters URLs
                   8623: 
                   8624: sub declutter {
                   8625:     my $thisfn=shift;
1.569     albertel 8626:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8627:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8628:     $thisfn=~s/^\///;
1.697     albertel 8629:     $thisfn=~s|^adm/wrapper/||;
                   8630:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8631:     $thisfn=~s/^res\///;
1.235     www      8632:     $thisfn=~s/\?.+$//;
1.268     www      8633:     return $thisfn;
                   8634: }
                   8635: 
                   8636: # ------------------------------------------------------------- Clutter up URLs
                   8637: 
                   8638: sub clutter {
                   8639:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8640:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8641: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8642:        $thisfn='/res'.$thisfn; 
                   8643:     }
1.694     albertel 8644:     if ($thisfn !~m|/adm|) {
1.695     albertel 8645: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8646: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8647: 	} else {
                   8648: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8649: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8650: 	    if ($embstyle eq 'ssi'
                   8651: 		|| ($embstyle eq 'hdn')
                   8652: 		|| ($embstyle eq 'rat')
                   8653: 		|| ($embstyle eq 'prv')
                   8654: 		|| ($embstyle eq 'ign')) {
                   8655: 		#do nothing with these
                   8656: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8657: 		|| ($embstyle eq 'emb')
                   8658: 		|| ($embstyle eq 'wrp')) {
                   8659: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8660: 	    } elsif ($embstyle eq 'unk'
                   8661: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8662: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8663: 	    } else {
1.718     www      8664: #		&logthis("Got a blank emb style");
1.695     albertel 8665: 	    }
1.694     albertel 8666: 	}
                   8667:     }
1.31      www      8668:     return $thisfn;
1.12      www      8669: }
                   8670: 
1.787     albertel 8671: sub clutter_with_no_wrapper {
                   8672:     my $uri = &clutter(shift);
                   8673:     if ($uri =~ m-^/adm/-) {
                   8674: 	$uri =~ s-^/adm/wrapper/-/-;
                   8675: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8676:     }
                   8677:     return $uri;
                   8678: }
                   8679: 
1.557     albertel 8680: sub freeze_escape {
                   8681:     my ($value)=@_;
                   8682:     if (ref($value)) {
                   8683: 	$value=&nfreeze($value);
                   8684: 	return '__FROZEN__'.&escape($value);
                   8685:     }
                   8686:     return &escape($value);
                   8687: }
                   8688: 
1.11      www      8689: 
1.557     albertel 8690: sub thaw_unescape {
                   8691:     my ($value)=@_;
                   8692:     if ($value =~ /^__FROZEN__/) {
                   8693: 	substr($value,0,10,undef);
                   8694: 	$value=&unescape($value);
                   8695: 	return &thaw($value);
                   8696:     }
                   8697:     return &unescape($value);
                   8698: }
                   8699: 
1.436     albertel 8700: sub correct_line_ends {
                   8701:     my ($result)=@_;
                   8702:     $$result =~s/\r\n/\n/mg;
                   8703:     $$result =~s/\r/\n/mg;
1.415     albertel 8704: }
1.1       albertel 8705: # ================================================================ Main Program
                   8706: 
1.184     www      8707: sub goodbye {
1.204     albertel 8708:    &logthis("Starting Shut down");
1.443     albertel 8709: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8710:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8711: #converted
1.599     albertel 8712: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8713:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8714: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8715: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8716: #1.1 only
1.870     albertel 8717: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8718: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8719: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8720: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8721:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8722:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8723:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8724:    &flushcourselogs();
                   8725:    &logthis("Shutting down");
                   8726: }
                   8727: 
1.852     albertel 8728: sub get_dns {
1.869     albertel 8729:     my ($url,$func,$ignore_cache) = @_;
                   8730:     if (!$ignore_cache) {
                   8731: 	my ($content,$cached)=
                   8732: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8733: 	if ($cached) {
                   8734: 	    &$func($content);
                   8735: 	    return;
                   8736: 	}
                   8737:     }
                   8738: 
                   8739:     my %alldns;
1.852     albertel 8740:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8741:     foreach my $dns (<$config>) {
                   8742: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8743:         my $line = $1;
                   8744:         my ($host,$protocol) = split(/:/,$line);
                   8745:         if ($protocol ne 'https') {
                   8746:             $protocol = 'http';
                   8747:         }
                   8748: 	$alldns{$host} = $protocol;
1.869     albertel 8749:     }
                   8750:     while (%alldns) {
                   8751: 	my ($dns) = keys(%alldns);
1.852     albertel 8752: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8753: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8754: 	my $response=$ua->request($request);
1.979     raeburn  8755:         delete($alldns{$dns});
1.852     albertel 8756: 	next if ($response->is_error());
                   8757: 	my @content = split("\n",$response->content);
1.869     albertel 8758: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8759: 	&$func(\@content);
1.869     albertel 8760: 	return;
1.852     albertel 8761:     }
                   8762:     close($config);
1.871     albertel 8763:     my $which = (split('/',$url))[3];
                   8764:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8765:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8766:     my @content = <$config>;
                   8767:     &$func(\@content);
                   8768:     return;
1.852     albertel 8769: }
1.327     albertel 8770: # ------------------------------------------------------------ Read domain file
                   8771: {
1.852     albertel 8772:     my $loaded;
1.846     albertel 8773:     my %domain;
                   8774: 
1.852     albertel 8775:     sub parse_domain_tab {
                   8776: 	my ($lines) = @_;
                   8777: 	foreach my $line (@$lines) {
                   8778: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8779: 
1.846     albertel 8780: 	    chomp($line);
1.852     albertel 8781: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8782: 	    my %this_domain;
                   8783: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8784: 			       'lang_def', 'city', 'longi', 'lati',
                   8785: 			       'primary') {
                   8786: 		$this_domain{$field} = shift(@elements);
                   8787: 	    }
                   8788: 	    $domain{$name} = \%this_domain;
1.852     albertel 8789: 	}
                   8790:     }
1.864     albertel 8791: 
                   8792:     sub reset_domain_info {
                   8793: 	undef($loaded);
                   8794: 	undef(%domain);
                   8795:     }
                   8796: 
1.852     albertel 8797:     sub load_domain_tab {
1.869     albertel 8798: 	my ($ignore_cache) = @_;
                   8799: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8800: 	my $fh;
                   8801: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8802: 	    my @lines = <$fh>;
                   8803: 	    &parse_domain_tab(\@lines);
1.448     albertel 8804: 	}
1.852     albertel 8805: 	close($fh);
                   8806: 	$loaded = 1;
1.327     albertel 8807:     }
1.846     albertel 8808: 
                   8809:     sub domain {
1.852     albertel 8810: 	&load_domain_tab() if (!$loaded);
                   8811: 
1.846     albertel 8812: 	my ($name,$what) = @_;
                   8813: 	return if ( !exists($domain{$name}) );
                   8814: 
                   8815: 	if (!$what) {
                   8816: 	    return $domain{$name}{'description'};
                   8817: 	}
                   8818: 	return $domain{$name}{$what};
                   8819:     }
1.974     raeburn  8820: 
                   8821:     sub domain_info {
                   8822:         &load_domain_tab() if (!$loaded);
                   8823:         return %domain;
                   8824:     }
                   8825: 
1.327     albertel 8826: }
                   8827: 
                   8828: 
1.1       albertel 8829: # ------------------------------------------------------------- Read hosts file
                   8830: {
1.838     albertel 8831:     my %hostname;
1.844     albertel 8832:     my %hostdom;
1.845     albertel 8833:     my %libserv;
1.852     albertel 8834:     my $loaded;
1.888     albertel 8835:     my %name_to_host;
1.852     albertel 8836: 
                   8837:     sub parse_hosts_tab {
                   8838: 	my ($file) = @_;
                   8839: 	foreach my $configline (@$file) {
                   8840: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8841: 	    next if ($configline =~ /^\^/);
                   8842: 	    chomp($configline);
1.968     raeburn  8843: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8844: 	    $name=~s/\s//g;
                   8845: 	    if ($id && $domain && $role && $name) {
                   8846: 		$hostname{$id}=$name;
1.888     albertel 8847: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8848: 		$hostdom{$id}=$domain;
                   8849: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8850:                 if (defined($protocol)) {
                   8851:                     if ($protocol eq 'https') {
                   8852:                         $protocol{$id} = $protocol;
                   8853:                     } else {
                   8854:                         $protocol{$id} = 'http'; 
                   8855:                     }
1.968     raeburn  8856:                 } else {
1.969     raeburn  8857:                     $protocol{$id} = 'http';
1.968     raeburn  8858:                 }
1.852     albertel 8859: 	    }
                   8860: 	}
                   8861:     }
1.864     albertel 8862:     
                   8863:     sub reset_hosts_info {
1.897     albertel 8864: 	&purge_remembered();
1.864     albertel 8865: 	&reset_domain_info();
                   8866: 	&reset_hosts_ip_info();
1.892     albertel 8867: 	undef(%name_to_host);
1.864     albertel 8868: 	undef(%hostname);
                   8869: 	undef(%hostdom);
                   8870: 	undef(%libserv);
                   8871: 	undef($loaded);
                   8872:     }
1.1       albertel 8873: 
1.852     albertel 8874:     sub load_hosts_tab {
1.869     albertel 8875: 	my ($ignore_cache) = @_;
                   8876: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8877: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8878: 	my @config = <$config>;
                   8879: 	&parse_hosts_tab(\@config);
                   8880: 	close($config);
                   8881: 	$loaded=1;
1.1       albertel 8882:     }
1.852     albertel 8883: 
1.838     albertel 8884:     sub hostname {
1.852     albertel 8885: 	&load_hosts_tab() if (!$loaded);
                   8886: 
1.838     albertel 8887: 	my ($lonid) = @_;
                   8888: 	return $hostname{$lonid};
                   8889:     }
1.845     albertel 8890: 
1.838     albertel 8891:     sub all_hostnames {
1.852     albertel 8892: 	&load_hosts_tab() if (!$loaded);
                   8893: 
1.838     albertel 8894: 	return %hostname;
                   8895:     }
1.845     albertel 8896: 
1.888     albertel 8897:     sub all_names {
                   8898: 	&load_hosts_tab() if (!$loaded);
                   8899: 
                   8900: 	return %name_to_host;
                   8901:     }
                   8902: 
1.974     raeburn  8903:     sub all_host_domain {
                   8904:         &load_hosts_tab() if (!$loaded);
                   8905:         return %hostdom;
                   8906:     }
                   8907: 
1.845     albertel 8908:     sub is_library {
1.852     albertel 8909: 	&load_hosts_tab() if (!$loaded);
                   8910: 
1.845     albertel 8911: 	return exists($libserv{$_[0]});
                   8912:     }
                   8913: 
                   8914:     sub all_library {
1.852     albertel 8915: 	&load_hosts_tab() if (!$loaded);
                   8916: 
1.845     albertel 8917: 	return %libserv;
                   8918:     }
                   8919: 
1.841     albertel 8920:     sub get_servers {
1.852     albertel 8921: 	&load_hosts_tab() if (!$loaded);
                   8922: 
1.841     albertel 8923: 	my ($domain,$type) = @_;
                   8924: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8925: 	                                          : %hostname;
                   8926: 	my %result;
1.842     albertel 8927: 	if (ref($domain) eq 'ARRAY') {
                   8928: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8929: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8930: 		    $result{$host} = $hostname;
                   8931: 		}
                   8932: 	    }
                   8933: 	} else {
                   8934: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8935: 		if ($hostdom{$host} eq $domain) {
                   8936: 		    $result{$host} = $hostname;
                   8937: 		}
1.841     albertel 8938: 	    }
                   8939: 	}
                   8940: 	return %result;
                   8941:     }
1.845     albertel 8942: 
1.844     albertel 8943:     sub host_domain {
1.852     albertel 8944: 	&load_hosts_tab() if (!$loaded);
                   8945: 
1.844     albertel 8946: 	my ($lonid) = @_;
                   8947: 	return $hostdom{$lonid};
                   8948:     }
                   8949: 
1.841     albertel 8950:     sub all_domains {
1.852     albertel 8951: 	&load_hosts_tab() if (!$loaded);
                   8952: 
1.841     albertel 8953: 	my %seen;
                   8954: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8955: 	return @uniq;
                   8956:     }
1.1       albertel 8957: }
                   8958: 
1.847     albertel 8959: { 
                   8960:     my %iphost;
1.856     albertel 8961:     my %name_to_ip;
                   8962:     my %lonid_to_ip;
1.869     albertel 8963: 
1.847     albertel 8964:     sub get_hosts_from_ip {
                   8965: 	my ($ip) = @_;
                   8966: 	my %iphosts = &get_iphost();
                   8967: 	if (ref($iphosts{$ip})) {
                   8968: 	    return @{$iphosts{$ip}};
                   8969: 	}
                   8970: 	return;
1.839     albertel 8971:     }
1.864     albertel 8972:     
                   8973:     sub reset_hosts_ip_info {
                   8974: 	undef(%iphost);
                   8975: 	undef(%name_to_ip);
                   8976: 	undef(%lonid_to_ip);
                   8977:     }
1.856     albertel 8978: 
                   8979:     sub get_host_ip {
                   8980: 	my ($lonid) = @_;
                   8981: 	if (exists($lonid_to_ip{$lonid})) {
                   8982: 	    return $lonid_to_ip{$lonid};
                   8983: 	}
                   8984: 	my $name=&hostname($lonid);
                   8985:    	my $ip = gethostbyname($name);
                   8986: 	return if (!$ip || length($ip) ne 4);
                   8987: 	$ip=inet_ntoa($ip);
                   8988: 	$name_to_ip{$name}   = $ip;
                   8989: 	$lonid_to_ip{$lonid} = $ip;
                   8990: 	return $ip;
                   8991:     }
1.847     albertel 8992:     
                   8993:     sub get_iphost {
1.869     albertel 8994: 	my ($ignore_cache) = @_;
1.894     albertel 8995: 
1.869     albertel 8996: 	if (!$ignore_cache) {
                   8997: 	    if (%iphost) {
                   8998: 		return %iphost;
                   8999: 	    }
                   9000: 	    my ($ip_info,$cached)=
                   9001: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9002: 	    if ($cached) {
                   9003: 		%iphost      = %{$ip_info->[0]};
                   9004: 		%name_to_ip  = %{$ip_info->[1]};
                   9005: 		%lonid_to_ip = %{$ip_info->[2]};
                   9006: 		return %iphost;
                   9007: 	    }
                   9008: 	}
1.894     albertel 9009: 
                   9010: 	# get yesterday's info for fallback
                   9011: 	my %old_name_to_ip;
                   9012: 	my ($ip_info,$cached)=
                   9013: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9014: 	if ($cached) {
                   9015: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9016: 	}
                   9017: 
1.888     albertel 9018: 	my %name_to_host = &all_names();
                   9019: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9020: 	    my $ip;
                   9021: 	    if (!exists($name_to_ip{$name})) {
                   9022: 		$ip = gethostbyname($name);
                   9023: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9024: 		    if (defined($old_name_to_ip{$name})) {
                   9025: 			$ip = $old_name_to_ip{$name};
                   9026: 			&logthis("Can't find $name defaulting to old $ip");
                   9027: 		    } else {
                   9028: 			&logthis("Name $name no IP found");
                   9029: 			next;
                   9030: 		    }
                   9031: 		} else {
                   9032: 		    $ip=inet_ntoa($ip);
1.847     albertel 9033: 		}
                   9034: 		$name_to_ip{$name} = $ip;
                   9035: 	    } else {
                   9036: 		$ip = $name_to_ip{$name};
1.653     albertel 9037: 	    }
1.888     albertel 9038: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9039: 		$lonid_to_ip{$id} = $ip;
                   9040: 	    }
                   9041: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9042: 	}
1.869     albertel 9043: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9044: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9045: 				      48*60*60);
1.869     albertel 9046: 
1.847     albertel 9047: 	return %iphost;
1.598     albertel 9048:     }
                   9049: }
                   9050: 
1.986     foxr     9051: #
                   9052: #  Given a DNS returns the loncapa host name for that DNS 
                   9053: # 
                   9054: sub host_from_dns {
                   9055:     my ($dns) = @_;
                   9056:     my @hosts;
                   9057:     my $ip;
                   9058: 
                   9059:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
                   9060:     if (length($ip) == 4) { 
                   9061: 	$ip   = &IO::Socket::inet_ntoa($ip);
                   9062: 	@hosts = get_hosts_from_ip($ip);
                   9063: 	return $hosts[0];
                   9064:     }
                   9065:     return undef;
                   9066: }
                   9067: 
1.862     albertel 9068: BEGIN {
                   9069: 
                   9070: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9071:     unless ($readit) {
                   9072: {
                   9073:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9074:     %perlvar = (%perlvar,%{$configvars});
                   9075: }
                   9076: 
                   9077: 
1.1       albertel 9078: # ------------------------------------------------------ Read spare server file
                   9079: {
1.448     albertel 9080:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9081: 
                   9082:     while (my $configline=<$config>) {
                   9083:        chomp($configline);
1.284     matthew  9084:        if ($configline) {
1.784     albertel 9085: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9086: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9087: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9088:        }
                   9089:     }
1.448     albertel 9090:     close($config);
1.1       albertel 9091: }
1.11      www      9092: # ------------------------------------------------------------ Read permissions
                   9093: {
1.448     albertel 9094:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9095: 
                   9096:     while (my $configline=<$config>) {
1.448     albertel 9097: 	chomp($configline);
                   9098: 	if ($configline) {
                   9099: 	    my ($role,$perm)=split(/ /,$configline);
                   9100: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9101: 	}
1.11      www      9102:     }
1.448     albertel 9103:     close($config);
1.11      www      9104: }
                   9105: 
                   9106: # -------------------------------------------- Read plain texts for permissions
                   9107: {
1.448     albertel 9108:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9109: 
                   9110:     while (my $configline=<$config>) {
1.448     albertel 9111: 	chomp($configline);
                   9112: 	if ($configline) {
1.742     raeburn  9113: 	    my ($short,@plain)=split(/:/,$configline);
                   9114:             %{$prp{$short}} = ();
                   9115: 	    if (@plain > 0) {
                   9116:                 $prp{$short}{'std'} = $plain[0];
                   9117:                 for (my $i=1; $i<@plain; $i++) {
                   9118:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9119:                 }
                   9120:             }
1.448     albertel 9121: 	}
1.135     www      9122:     }
1.448     albertel 9123:     close($config);
1.135     www      9124: }
                   9125: 
                   9126: # ---------------------------------------------------------- Read package table
                   9127: {
1.448     albertel 9128:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9129: 
                   9130:     while (my $configline=<$config>) {
1.483     albertel 9131: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9132: 	chomp($configline);
                   9133: 	my ($short,$plain)=split(/:/,$configline);
                   9134: 	my ($pack,$name)=split(/\&/,$short);
                   9135: 	if ($plain ne '') {
                   9136: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9137: 	    $packagetab{$short}=$plain; 
                   9138: 	}
1.11      www      9139:     }
1.448     albertel 9140:     close($config);
1.329     matthew  9141: }
                   9142: 
                   9143: # ------------- set up temporary directory
                   9144: {
                   9145:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9146: 
1.11      www      9147: }
                   9148: 
1.794     albertel 9149: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9150: 				'compress_threshold'=> 20_000,
                   9151:  			        });
1.185     www      9152: 
1.281     www      9153: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9154: $dumpcount=0;
1.958     www      9155: $locknum=0;
1.22      www      9156: 
1.163     harris41 9157: &logtouch();
1.672     albertel 9158: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9159: $readit=1;
1.564     albertel 9160:     {
                   9161: 	use integer;
                   9162: 	my $test=(2**32)+1;
1.568     albertel 9163: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9164: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9165:     }
1.195     www      9166: }
1.1       albertel 9167: }
1.179     www      9168: 
1.1       albertel 9169: 1;
1.191     harris41 9170: __END__
                   9171: 
1.243     albertel 9172: =pod
                   9173: 
1.191     harris41 9174: =head1 NAME
                   9175: 
1.243     albertel 9176: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9177: 
                   9178: =head1 SYNOPSIS
                   9179: 
1.243     albertel 9180: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9181: 
                   9182:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9183: 
1.243     albertel 9184: Common parameters:
                   9185: 
                   9186: =over 4
                   9187: 
                   9188: =item *
                   9189: 
                   9190: $uname : an internal username (if $cname expecting a course Id specifically)
                   9191: 
                   9192: =item *
                   9193: 
                   9194: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9195: 
                   9196: =item *
                   9197: 
                   9198: $symb : a resource instance identifier
                   9199: 
                   9200: =item *
                   9201: 
                   9202: $namespace : the name of a .db file that contains the data needed or
                   9203: being set.
                   9204: 
                   9205: =back
                   9206: 
1.394     bowersj2 9207: =head1 OVERVIEW
1.191     harris41 9208: 
1.394     bowersj2 9209: lonnet provides subroutines which interact with the
                   9210: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9211: about classes, users, and resources.
1.243     albertel 9212: 
                   9213: For many of these objects you can also use this to store data about
                   9214: them or modify them in various ways.
1.191     harris41 9215: 
1.394     bowersj2 9216: =head2 Symbs
1.191     harris41 9217: 
1.394     bowersj2 9218: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9219: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9220: map, the resource number of the resource in the map, and the URL of
                   9221: the resource itself. The latter is somewhat redundant, but might help
                   9222: if maps change.
                   9223: 
                   9224: An example is
                   9225: 
                   9226:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9227: 
                   9228: The respective map entry is
                   9229: 
                   9230:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9231:   title="Problem 2">
                   9232:  </resource>
                   9233: 
                   9234: Symbs are used by the random number generator, as well as to store and
                   9235: restore data specific to a certain instance of for example a problem.
                   9236: 
                   9237: =head2 Storing And Retrieving Data
                   9238: 
                   9239: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9240: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9241: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9242: is is the non-critical message twin of cstore. These functions are for
                   9243: handlers to store a perl hash to a user's permanent data space in an
                   9244: easy manner, and to retrieve it again on another call. It is expected
                   9245: that a handler would use this once at the beginning to retrieve data,
                   9246: and then again once at the end to send only the new data back.
                   9247: 
                   9248: The data is stored in the user's data directory on the user's
                   9249: homeserver under the ID of the course.
                   9250: 
                   9251: The hash that is returned by restore will have all of the previous
                   9252: value for all of the elements of the hash.
                   9253: 
                   9254: Example:
                   9255: 
                   9256:  #creating a hash
                   9257:  my %hash;
                   9258:  $hash{'foo'}='bar';
                   9259: 
                   9260:  #storing it
                   9261:  &Apache::lonnet::cstore(\%hash);
                   9262: 
                   9263:  #changing a value
                   9264:  $hash{'foo'}='notbar';
                   9265: 
                   9266:  #adding a new value
                   9267:  $hash{'bar'}='foo';
                   9268:  &Apache::lonnet::cstore(\%hash);
                   9269: 
                   9270:  #retrieving the hash
                   9271:  my %history=&Apache::lonnet::restore();
                   9272: 
                   9273:  #print the hash
                   9274:  foreach my $key (sort(keys(%history))) {
                   9275:    print("\%history{$key} = $history{$key}");
                   9276:  }
                   9277: 
                   9278: Will print out:
1.191     harris41 9279: 
1.394     bowersj2 9280:  %history{1:foo} = bar
                   9281:  %history{1:keys} = foo:timestamp
                   9282:  %history{1:timestamp} = 990455579
                   9283:  %history{2:bar} = foo
                   9284:  %history{2:foo} = notbar
                   9285:  %history{2:keys} = foo:bar:timestamp
                   9286:  %history{2:timestamp} = 990455580
                   9287:  %history{bar} = foo
                   9288:  %history{foo} = notbar
                   9289:  %history{timestamp} = 990455580
                   9290:  %history{version} = 2
                   9291: 
                   9292: Note that the special hash entries C<keys>, C<version> and
                   9293: C<timestamp> were added to the hash. C<version> will be equal to the
                   9294: total number of versions of the data that have been stored. The
                   9295: C<timestamp> attribute will be the UNIX time the hash was
                   9296: stored. C<keys> is available in every historical section to list which
                   9297: keys were added or changed at a specific historical revision of a
                   9298: hash.
                   9299: 
                   9300: B<Warning>: do not store the hash that restore returns directly. This
                   9301: will cause a mess since it will restore the historical keys as if the
                   9302: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9303: 
1.394     bowersj2 9304: Calling convention:
1.191     harris41 9305: 
1.394     bowersj2 9306:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9307:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9308: 
1.394     bowersj2 9309: For more detailed information, see lonnet specific documentation.
1.191     harris41 9310: 
1.394     bowersj2 9311: =head1 RETURN MESSAGES
1.191     harris41 9312: 
1.394     bowersj2 9313: =over 4
1.191     harris41 9314: 
1.394     bowersj2 9315: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9316: 
1.394     bowersj2 9317: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9318: when the connection is brought back up
1.191     harris41 9319: 
1.394     bowersj2 9320: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9321: for later delivery
1.191     harris41 9322: 
1.967     bisitz   9323: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9324: 
1.394     bowersj2 9325: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9326: that was requested
1.191     harris41 9327: 
1.243     albertel 9328: =back
1.191     harris41 9329: 
1.243     albertel 9330: =head1 PUBLIC SUBROUTINES
1.191     harris41 9331: 
1.243     albertel 9332: =head2 Session Environment Functions
1.191     harris41 9333: 
1.243     albertel 9334: =over 4
1.191     harris41 9335: 
1.394     bowersj2 9336: =item * 
                   9337: X<appenv()>
1.949     raeburn  9338: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9339: the user envirnoment file, and will be restored for each access this
1.620     albertel 9340: user makes during this session, also modifies the %env for the current
1.949     raeburn  9341: process. Optional rolesarrayref - if defined contains a reference to an array
                   9342: of roles which are exempt from the restriction on modifying user.role entries 
                   9343: in the user's environment.db and in %env.    
1.191     harris41 9344: 
                   9345: =item *
1.394     bowersj2 9346: X<delenv()>
1.987     raeburn  9347: B<delenv($delthis,$regexp)>: removes all items from the session
                   9348: environment file that begin with $delthis. If the 
                   9349: optional second arg - $regexp - is true, $delthis is treated as a 
                   9350: regular expression, otherwise \Q$delthis\E is used. 
                   9351: The values are also deleted from the current processes %env.
1.191     harris41 9352: 
1.795     albertel 9353: =item * get_env_multiple($name) 
                   9354: 
                   9355: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9356: values may be defined and end up as an array ref.
                   9357: 
                   9358: returns an array of values
                   9359: 
1.243     albertel 9360: =back
                   9361: 
                   9362: =head2 User Information
1.191     harris41 9363: 
1.243     albertel 9364: =over 4
1.191     harris41 9365: 
                   9366: =item *
1.394     bowersj2 9367: X<queryauthenticate()>
                   9368: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9369: authentication scheme
                   9370: 
                   9371: =item *
1.394     bowersj2 9372: X<authenticate()>
                   9373: B<authenticate($uname,$upass,$udom)>: try to
                   9374: authenticate user from domain's lib servers (first use the current
                   9375: one). C<$upass> should be the users password.
1.191     harris41 9376: 
                   9377: =item *
1.394     bowersj2 9378: X<homeserver()>
                   9379: B<homeserver($uname,$udom)>: find the server which has
                   9380: the user's directory and files (there must be only one), this caches
                   9381: the answer, and also caches if there is a borken connection.
1.191     harris41 9382: 
                   9383: =item *
1.394     bowersj2 9384: X<idget()>
                   9385: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9386: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9387: username, and only 1 username per ID in a specific domain) (returns
                   9388: hash: id=>name,id=>name)
1.191     harris41 9389: 
                   9390: =item *
1.394     bowersj2 9391: X<idrget()>
                   9392: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9393: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9394: 
                   9395: =item *
1.394     bowersj2 9396: X<idput()>
                   9397: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9398: 
                   9399: =item *
1.394     bowersj2 9400: X<rolesinit()>
                   9401: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9402: 
                   9403: =item *
1.551     albertel 9404: X<getsection()>
                   9405: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9406: course $cname, return section name/number or '' for "not in course"
                   9407: and '-1' for "no section"
                   9408: 
                   9409: =item *
1.394     bowersj2 9410: X<userenvironment()>
                   9411: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9412: passed in @what from the requested user's environment, returns a hash
                   9413: 
1.858     raeburn  9414: =item * 
                   9415: X<userlog_query()>
1.859     albertel 9416: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9417: activity.log file. %filters defines filters applied when parsing the
                   9418: log file. These can be start or end timestamps, or the type of action
                   9419: - log to look for Login or Logout events, check for Checkin or
                   9420: Checkout, role for role selection. The response is in the form
                   9421: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9422: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9423: 
1.243     albertel 9424: =back
                   9425: 
                   9426: =head2 User Roles
                   9427: 
                   9428: =over 4
                   9429: 
                   9430: =item *
                   9431: 
1.810     raeburn  9432: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9433:  F: full access
                   9434:  U,I,K: authentication modes (cxx only)
                   9435:  '': forbidden
                   9436:  1: user needs to choose course
                   9437:  2: browse allowed
1.766     albertel 9438:  A: passphrase authentication needed
1.243     albertel 9439: 
                   9440: =item *
                   9441: 
                   9442: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9443: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9444: and course level
                   9445: 
                   9446: =item *
                   9447: 
1.988     raeburn  9448: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9449: (rolesplain.tab); plain text explanation of a user role term.
                   9450: $type is Course (default) or Group.
                   9451: If $forcedefault evaluates to true, text returned will be default 
                   9452: text for $type. Otherwise, if this is a course, the text returned 
                   9453: will be a custom name for the role (if defined in the course's 
                   9454: environment).  If no custom name is defined the default is returned.
                   9455:    
1.832     raeburn  9456: =item *
                   9457: 
1.935     raeburn  9458: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9459: All arguments are optional. Returns a hash of a roles, either for
                   9460: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9461: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9462: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9463: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9464: For each key, value is set to colon-separated start and end times for
                   9465: the role.  If no username and domain are specified, will default to
1.934     raeburn  9466: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9467: of role statuses (active, future or previous), roles 
                   9468: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9469: to restrict the list of roles reported. If no array ref is 
                   9470: provided for types, will default to return only active roles.
1.834     albertel 9471: 
1.243     albertel 9472: =back
                   9473: 
                   9474: =head2 User Modification
                   9475: 
                   9476: =over 4
                   9477: 
                   9478: =item *
                   9479: 
1.957     raeburn  9480: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9481: user for the level given by URL.  Optional start and end dates (leave empty
                   9482: string or zero for "no date")
1.191     harris41 9483: 
                   9484: =item *
                   9485: 
1.243     albertel 9486: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9487: change a users, password, possible return values are: ok,
                   9488: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9489: refused
1.191     harris41 9490: 
                   9491: =item *
                   9492: 
1.243     albertel 9493: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9494: 
                   9495: =item *
                   9496: 
1.963     raeburn  9497: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9498:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9499: modify user
1.191     harris41 9500: 
                   9501: =item *
                   9502: 
1.286     matthew  9503: modifystudent
                   9504: 
1.957     raeburn  9505: modify a student's enrollment and identification information.
1.286     matthew  9506: The course id is resolved based on the current users environment.  
                   9507: This means the envoking user must be a course coordinator or otherwise
                   9508: associated with a course.
                   9509: 
1.297     matthew  9510: This call is essentially a wrapper for lonnet::modifyuser and
                   9511: lonnet::modify_student_enrollment
1.286     matthew  9512: 
                   9513: Inputs: 
                   9514: 
                   9515: =over 4
                   9516: 
1.957     raeburn  9517: =item B<$udom> Student's loncapa domain
1.286     matthew  9518: 
1.957     raeburn  9519: =item B<$uname> Student's loncapa login name
1.286     matthew  9520: 
1.964     bisitz   9521: =item B<$uid> Student/Employee ID
1.286     matthew  9522: 
1.957     raeburn  9523: =item B<$umode> Student's authentication mode
1.286     matthew  9524: 
1.957     raeburn  9525: =item B<$upass> Student's password
1.286     matthew  9526: 
1.957     raeburn  9527: =item B<$first> Student's first name
1.286     matthew  9528: 
1.957     raeburn  9529: =item B<$middle> Student's middle name
1.286     matthew  9530: 
1.957     raeburn  9531: =item B<$last> Student's last name
1.286     matthew  9532: 
1.957     raeburn  9533: =item B<$gene> Student's generation
1.286     matthew  9534: 
1.957     raeburn  9535: =item B<$usec> Student's section in course
1.286     matthew  9536: 
                   9537: =item B<$end> Unix time of the roles expiration
                   9538: 
                   9539: =item B<$start> Unix time of the roles start date
                   9540: 
                   9541: =item B<$forceid> If defined, allow $uid to be changed
                   9542: 
                   9543: =item B<$desiredhome> server to use as home server for student
                   9544: 
1.957     raeburn  9545: =item B<$email> Student's permanent e-mail address
                   9546: 
                   9547: =item B<$type> Type of enrollment (auto or manual)
                   9548: 
1.963     raeburn  9549: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9550: 
                   9551: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9552: 
1.963     raeburn  9553: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9554: 
1.963     raeburn  9555: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9556: 
1.963     raeburn  9557: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9558: 
1.286     matthew  9559: =back
1.297     matthew  9560: 
                   9561: =item *
                   9562: 
                   9563: modify_student_enrollment
                   9564: 
                   9565: Change a students enrollment status in a class.  The environment variable
                   9566: 'role.request.course' must be defined for this function to proceed.
                   9567: 
                   9568: Inputs:
                   9569: 
                   9570: =over 4
                   9571: 
                   9572: =item $udom, students domain
                   9573: 
                   9574: =item $uname, students name
                   9575: 
                   9576: =item $uid, students user id
                   9577: 
                   9578: =item $first, students first name
                   9579: 
                   9580: =item $middle
                   9581: 
                   9582: =item $last
                   9583: 
                   9584: =item $gene
                   9585: 
                   9586: =item $usec
                   9587: 
                   9588: =item $end
                   9589: 
                   9590: =item $start
                   9591: 
1.957     raeburn  9592: =item $type
                   9593: 
                   9594: =item $locktype
                   9595: 
                   9596: =item $cid
                   9597: 
                   9598: =item $selfenroll
                   9599: 
                   9600: =item $context
                   9601: 
1.297     matthew  9602: =back
                   9603: 
1.191     harris41 9604: 
                   9605: =item *
                   9606: 
1.243     albertel 9607: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9608: custom role; give a custom role to a user for the level given by URL.  Specify
                   9609: name and domain of role author, and role name
1.191     harris41 9610: 
                   9611: =item *
                   9612: 
1.243     albertel 9613: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9614: 
                   9615: =item *
                   9616: 
1.243     albertel 9617: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9618: 
                   9619: =back
                   9620: 
                   9621: =head2 Course Infomation
                   9622: 
                   9623: =over 4
1.191     harris41 9624: 
                   9625: =item *
                   9626: 
1.631     albertel 9627: coursedescription($courseid) : returns a hash of information about the
                   9628: specified course id, including all environment settings for the
                   9629: course, the description of the course will be in the hash under the
                   9630: key 'description'
1.191     harris41 9631: 
                   9632: =item *
                   9633: 
1.624     albertel 9634: resdata($name,$domain,$type,@which) : request for current parameter
                   9635: setting for a specific $type, where $type is either 'course' or 'user',
                   9636: @what should be a list of parameters to ask about. This routine caches
                   9637: answers for 5 minutes.
1.243     albertel 9638: 
1.877     foxr     9639: =item *
                   9640: 
                   9641: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9642: data base, returning a hash that is keyed by the resource name and has
                   9643: values that are the resource value.  I believe that the timestamps and
                   9644: versions are also returned.
                   9645: 
                   9646: 
1.243     albertel 9647: =back
                   9648: 
                   9649: =head2 Course Modification
                   9650: 
                   9651: =over 4
1.191     harris41 9652: 
                   9653: =item *
                   9654: 
1.243     albertel 9655: writecoursepref($courseid,%prefs) : write preferences (environment
                   9656: database) for a course
1.191     harris41 9657: 
                   9658: =item *
                   9659: 
1.243     albertel 9660: createcourse($udom,$description,$url) : make/modify course
                   9661: 
                   9662: =back
                   9663: 
                   9664: =head2 Resource Subroutines
                   9665: 
                   9666: =over 4
1.191     harris41 9667: 
                   9668: =item *
                   9669: 
1.243     albertel 9670: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9671: 
                   9672: =item *
                   9673: 
1.243     albertel 9674: repcopy($filename) : subscribes to the requested file, and attempts to
                   9675: replicate from the owning library server, Might return
1.607     raeburn  9676: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9677: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9678: resource. Expects the local filesystem pathname
                   9679: (/home/httpd/html/res/....)
                   9680: 
                   9681: =back
                   9682: 
                   9683: =head2 Resource Information
                   9684: 
                   9685: =over 4
1.191     harris41 9686: 
                   9687: =item *
                   9688: 
1.243     albertel 9689: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9690: a vairety of different possible values, $varname should be a request
                   9691: string, and the other parameters can be used to specify who and what
                   9692: one is asking about.
                   9693: 
                   9694: Possible values for $varname are environment.lastname (or other item
                   9695: from the envirnment hash), user.name (or someother aspect about the
                   9696: user), resource.0.maxtries (or some other part and parameter of a
                   9697: resource)
1.204     albertel 9698: 
                   9699: =item *
                   9700: 
1.243     albertel 9701: directcondval($number) : get current value of a condition; reads from a state
                   9702: string
1.204     albertel 9703: 
                   9704: =item *
                   9705: 
1.243     albertel 9706: condval($condidx) : value of condition index based on state
1.204     albertel 9707: 
                   9708: =item *
                   9709: 
1.243     albertel 9710: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9711: resource's metadata, $what should be either a specific key, or either
                   9712: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9713: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9714: 
                   9715: this function automatically caches all requests
1.191     harris41 9716: 
                   9717: =item *
                   9718: 
1.243     albertel 9719: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9720: network of library servers; returns file handle of where SQL and regex results
                   9721: will be stored for query
1.191     harris41 9722: 
                   9723: =item *
                   9724: 
1.243     albertel 9725: symbread($filename) : return symbolic list entry (filename argument optional);
                   9726: returns the data handle
1.191     harris41 9727: 
                   9728: =item *
                   9729: 
1.243     albertel 9730: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9731: a possible symb for the URL in $thisfn, and if is an encryypted
                   9732: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9733: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9734: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9735: 
1.191     harris41 9736: 
                   9737: =item *
                   9738: 
1.243     albertel 9739: symbclean($symb) : removes versions numbers from a symb, returns the
                   9740: cleaned symb
1.191     harris41 9741: 
                   9742: =item *
                   9743: 
1.243     albertel 9744: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9745: course map, user must be in a course for it to work.
1.191     harris41 9746: 
                   9747: =item *
                   9748: 
1.243     albertel 9749: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9750: 
                   9751: =item *
                   9752: 
1.243     albertel 9753: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9754: a random seed, all arguments are optional, if they aren't sent it uses the
                   9755: environment to derive them. Note: if symb isn't sent and it can't get one
                   9756: from &symbread it will use the current time as its return value
1.191     harris41 9757: 
                   9758: =item *
                   9759: 
1.243     albertel 9760: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9761: unfakeable, receipt
1.191     harris41 9762: 
                   9763: =item *
                   9764: 
1.620     albertel 9765: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9766: 
                   9767: =item *
                   9768: 
1.243     albertel 9769: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9770: 
                   9771: =item *
                   9772: 
1.243     albertel 9773: 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 9774: 
                   9775: =item *
                   9776: 
1.243     albertel 9777: 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 9778: 
                   9779: =item *
                   9780: 
1.243     albertel 9781: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9782: 
                   9783: =item *
                   9784: 
1.243     albertel 9785: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9786: forcing spreadsheet to reevaluate the resource scores next time.
                   9787: 
                   9788: =back
                   9789: 
                   9790: =head2 Storing/Retreiving Data
                   9791: 
                   9792: =over 4
1.191     harris41 9793: 
                   9794: =item *
                   9795: 
1.243     albertel 9796: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9797: for this url; hashref needs to be given and should be a \%hashname; the
                   9798: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9799: be derived from the env
1.191     harris41 9800: 
                   9801: =item *
                   9802: 
1.243     albertel 9803: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9804: uses critical subroutine
1.191     harris41 9805: 
                   9806: =item *
                   9807: 
1.243     albertel 9808: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9809: all args are optional
1.191     harris41 9810: 
                   9811: =item *
                   9812: 
1.717     albertel 9813: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9814: dumps the complete (or key matching regexp) namespace into a hash
                   9815: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9816: normally &store()ed into
                   9817: 
                   9818: $range should be either an integer '100' (give me the first 100
                   9819:                                            matching records)
                   9820:               or be  two integers sperated by a - with no spaces
                   9821:                  '30-50' (give me the 30th through the 50th matching
                   9822:                           records)
                   9823: 
                   9824: 
                   9825: =item *
                   9826: 
                   9827: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9828: replaces a &store() version of data with a replacement set of data
                   9829: for a particular resource in a namespace passed in the $storehash hash 
                   9830: reference
                   9831: 
                   9832: =item *
                   9833: 
1.243     albertel 9834: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9835: works very similar to store/cstore, but all data is stored in a
                   9836: temporary location and can be reset using tmpreset, $storehash should
                   9837: be a hash reference, returns nothing on success
1.191     harris41 9838: 
                   9839: =item *
                   9840: 
1.243     albertel 9841: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9842: similar to restore, but all data is stored in a temporary location and
                   9843: can be reset using tmpreset. Returns a hash of values on success,
                   9844: error string otherwise.
1.191     harris41 9845: 
                   9846: =item *
                   9847: 
1.243     albertel 9848: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9849: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9850: 
                   9851: =item *
                   9852: 
1.243     albertel 9853: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9854: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9855: 
                   9856: =item *
                   9857: 
1.243     albertel 9858: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9859: namesp ($udom and $uname are optional)
1.191     harris41 9860: 
                   9861: =item *
                   9862: 
1.702     albertel 9863: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9864: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9865: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9866: 
1.702     albertel 9867: $range should be either an integer '100' (give me the first 100
                   9868:                                            matching records)
                   9869:               or be  two integers sperated by a - with no spaces
                   9870:                  '30-50' (give me the 30th through the 50th matching
                   9871:                           records)
1.449     matthew  9872: =item *
                   9873: 
                   9874: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9875: $store can be a scalar, an array reference, or if the amount to be 
                   9876: incremented is > 1, a hash reference.
                   9877: 
                   9878: ($udom and $uname are optional)
1.191     harris41 9879: 
                   9880: =item *
                   9881: 
1.243     albertel 9882: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9883: ($udom and $uname are optional)
1.191     harris41 9884: 
                   9885: =item *
                   9886: 
1.243     albertel 9887: cput($namespace,$storehash,$udom,$uname) : critical put
                   9888: ($udom and $uname are optional)
1.191     harris41 9889: 
                   9890: =item *
                   9891: 
1.748     albertel 9892: newput($namespace,$storehash,$udom,$uname) :
                   9893: 
                   9894: Attempts to store the items in the $storehash, but only if they don't
                   9895: currently exist, if this succeeds you can be certain that you have 
                   9896: successfully created a new key value pair in the $namespace db.
                   9897: 
                   9898: 
                   9899: Args:
                   9900:  $namespace: name of database to store values to
                   9901:  $storehash: hashref to store to the db
                   9902:  $udom: (optional) domain of user containing the db
                   9903:  $uname: (optional) name of user caontaining the db
                   9904: 
                   9905: Returns:
                   9906:  'ok' -> succeeded in storing all keys of $storehash
                   9907:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9908:                         least <key> already existed in the db (other
                   9909:                         requested keys may also already exist)
1.967     bisitz   9910:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9911:  'con_lost' -> unable to contact request server
                   9912:  'refused' -> action was not allowed by remote machine
                   9913: 
                   9914: 
                   9915: =item *
                   9916: 
1.243     albertel 9917: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9918: reference filled in from namesp (encrypts the return communication)
                   9919: ($udom and $uname are optional)
1.191     harris41 9920: 
                   9921: =item *
                   9922: 
1.243     albertel 9923: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9924: critical subroutine
                   9925: 
1.806     raeburn  9926: =item *
                   9927: 
1.860     raeburn  9928: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9929: array reference filled in from namespace found in domain level on either
                   9930: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9931: 
                   9932: =item *
                   9933: 
1.860     raeburn  9934: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9935: domain level either on specified domain server ($uhome) or primary domain 
                   9936: server ($udom and $uhome are optional)
1.806     raeburn  9937: 
1.943     raeburn  9938: =item * 
                   9939: 
                   9940: get_domain_defaults($target_domain) : returns hash with defaults for
                   9941: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9942: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9943: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9944: Values are retrieved from cache (if current), or from domain's configuration.db
                   9945: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9946: or lonTabs/domain.tab. 
                   9947: 
                   9948: %domdefaults = &get_auth_defaults($target_domain);
                   9949: 
1.243     albertel 9950: =back
                   9951: 
                   9952: =head2 Network Status Functions
                   9953: 
                   9954: =over 4
1.191     harris41 9955: 
                   9956: =item *
                   9957: 
                   9958: dirlist($uri) : return directory list based on URI
                   9959: 
                   9960: =item *
                   9961: 
1.243     albertel 9962: spareserver() : find server with least workload from spare.tab
                   9963: 
1.986     foxr     9964: 
                   9965: =item *
                   9966: 
                   9967: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   9968: if there is no corresponding loncapa host.
                   9969: 
1.243     albertel 9970: =back
                   9971: 
1.986     foxr     9972: 
1.243     albertel 9973: =head2 Apache Request
                   9974: 
                   9975: =over 4
1.191     harris41 9976: 
                   9977: =item *
                   9978: 
1.243     albertel 9979: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9980: localhost, posts hash
                   9981: 
                   9982: =back
                   9983: 
                   9984: =head2 Data to String to Data
                   9985: 
                   9986: =over 4
1.191     harris41 9987: 
                   9988: =item *
                   9989: 
1.243     albertel 9990: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9991: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9992: 
                   9993: =item *
                   9994: 
1.243     albertel 9995: hashref2str($hashref) : convert a hashref into a string complete with
                   9996: escaping and '=' and '&' separators, supports elements that are
                   9997: arrayrefs and hashrefs
1.191     harris41 9998: 
                   9999: =item *
                   10000: 
1.243     albertel 10001: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10002: with escaping and '&' separators, supports elements that are arrayrefs
                   10003: and hashrefs
1.191     harris41 10004: 
                   10005: =item *
                   10006: 
1.243     albertel 10007: str2hash($string) : convert string to hash using unescaping and
                   10008: splitting on '=' and '&', supports elements that are arrayrefs and
                   10009: hashrefs
1.191     harris41 10010: 
                   10011: =item *
                   10012: 
1.243     albertel 10013: str2array($string) : convert string to hash using unescaping and
                   10014: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10015: 
                   10016: =back
                   10017: 
                   10018: =head2 Logging Routines
                   10019: 
                   10020: =over 4
                   10021: 
                   10022: These routines allow one to make log messages in the lonnet.log and
                   10023: lonnet.perm logfiles.
1.191     harris41 10024: 
                   10025: =item *
                   10026: 
1.243     albertel 10027: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10028: 
                   10029: =item *
                   10030: 
1.243     albertel 10031: logthis() : append message to the normal lonnet.log file, it gets
                   10032: preiodically rolled over and deleted.
1.191     harris41 10033: 
                   10034: =item *
                   10035: 
1.243     albertel 10036: logperm() : append a permanent message to lonnet.perm.log, this log
                   10037: file never gets deleted by any automated portion of the system, only
                   10038: messages of critical importance should go in here.
                   10039: 
                   10040: =back
                   10041: 
                   10042: =head2 General File Helper Routines
                   10043: 
                   10044: =over 4
1.191     harris41 10045: 
                   10046: =item *
                   10047: 
1.481     raeburn  10048: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10049: (a) files in /uploaded
                   10050:   (i) If a local copy of the file exists - 
                   10051:       compares modification date of local copy with last-modified date for 
                   10052:       definitive version stored on home server for course. If local copy is 
                   10053:       stale, requests a new version from the home server and stores it. 
                   10054:       If the original has been removed from the home server, then local copy 
                   10055:       is unlinked.
                   10056:   (ii) If local copy does not exist -
                   10057:       requests the file from the home server and stores it. 
                   10058:   
                   10059:   If $caller is 'uploadrep':  
                   10060:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10061:     for request for files originally uploaded via DOCS. 
                   10062:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10063:   
                   10064:   Otherwise:
                   10065:      This indicates a call from the content generation phase of the request.
                   10066:      -  returns the entire contents of the file or -1.
                   10067:      
                   10068: (b) files in /res
                   10069:    - returns the entire contents of a file or -1; 
                   10070:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10071: 
1.712     albertel 10072: 
                   10073: =item *
                   10074: 
                   10075: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10076:                   reference
                   10077: 
                   10078: returns either a stat() list of data about the file or an empty list
                   10079: if the file doesn't exist or couldn't find out about it (connection
                   10080: problems or user unknown)
                   10081: 
1.191     harris41 10082: =item *
                   10083: 
1.243     albertel 10084: filelocation($dir,$file) : returns file system location of a file
                   10085: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10086: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10087: and a file of ../bob will become /a/bob)
1.191     harris41 10088: 
                   10089: =item *
                   10090: 
                   10091: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10092: filelocation except for hrefs
                   10093: 
                   10094: =item *
                   10095: 
                   10096: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10097: 
1.243     albertel 10098: =back
                   10099: 
1.608     albertel 10100: =head2 Usererfile file routines (/uploaded*)
                   10101: 
                   10102: =over 4
                   10103: 
                   10104: =item *
                   10105: 
                   10106: userfileupload(): main rotine for putting a file in a user or course's
                   10107:                   filespace, arguments are,
                   10108: 
1.620     albertel 10109:  formname - required - this is the name of the element in $env where the
1.608     albertel 10110:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10111:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10112:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10113:  coursedoc - if true, store the file in the course of the active role
                   10114:              of the current user
                   10115:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10116:          if undefined, it will be placed in "unknown"
                   10117: 
                   10118:  (This routine calls clean_filename() to remove any dangerous
                   10119:  characters from the filename, and then calls finuserfileupload() to
                   10120:  complete the transaction)
                   10121: 
                   10122:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10123:  and /adm/notfound.html if unsuccessful
                   10124: 
                   10125: =item *
                   10126: 
                   10127: clean_filename(): routine for cleaing a filename up for storage in
                   10128:                  userfile space, argument is:
                   10129: 
                   10130:  filename - proposed filename
                   10131: 
                   10132: returns: the new clean filename
                   10133: 
                   10134: =item *
                   10135: 
                   10136: finishuserfileupload(): routine that creaes and sends the file to
                   10137: userspace, probably shouldn't be called directly
                   10138: 
                   10139:   docuname: username or courseid of destination for the file
                   10140:   docudom: domain of user/course of destination for the file
                   10141:   formname: same as for userfileupload()
                   10142:   fname: filename (inculding subdirectories) for the file
                   10143: 
                   10144:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10145:  and /adm/notfound.html if unsuccessful
                   10146: 
                   10147: =item *
                   10148: 
                   10149: renameuserfile(): renames an existing userfile to a new name
                   10150: 
                   10151:   Args:
                   10152:    docuname: username or courseid of destination for the file
                   10153:    docudom: domain of user/course of destination for the file
                   10154:    old: current file name (including any subdirs under userfiles)
                   10155:    new: desired file name (including any subdirs under userfiles)
                   10156: 
                   10157: =item *
                   10158: 
                   10159: mkdiruserfile(): creates a directory is a userfiles dir
                   10160: 
                   10161:   Args:
                   10162:    docuname: username or courseid of destination for the file
                   10163:    docudom: domain of user/course of destination for the file
                   10164:    dir: dir to create (including any subdirs under userfiles)
                   10165: 
                   10166: =item *
                   10167: 
                   10168: removeuserfile(): removes a file that exists in userfiles
                   10169: 
                   10170:   Args:
                   10171:    docuname: username or courseid of destination for the file
                   10172:    docudom: domain of user/course of destination for the file
                   10173:    fname: filname to delete (including any subdirs under userfiles)
                   10174: 
                   10175: =item *
                   10176: 
                   10177: removeuploadedurl(): convience function for removeuserfile()
                   10178: 
                   10179:   Args:
                   10180:    url:  a full /uploaded/... url to delete
                   10181: 
1.747     albertel 10182: =item * 
                   10183: 
                   10184: get_portfile_permissions():
                   10185:   Args:
                   10186:     domain: domain of user or course contain the portfolio files
                   10187:     user: name of user or num of course contain the portfolio files
                   10188:   Returns:
                   10189:     hashref of a dump of the proper file_permissions.db
                   10190:    
                   10191: 
                   10192: =item * 
                   10193: 
                   10194: get_access_controls():
                   10195: 
                   10196: Args:
                   10197:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10198:   group: (optional) the group you want the files associated with
                   10199:   file: (optional) the file you want access info on
                   10200: 
                   10201: Returns:
1.749     raeburn  10202:     a hash (keys are file names) of hashes containing
                   10203:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10204:         values are XML containing access control settings (see below) 
1.747     albertel 10205: 
                   10206: Internal notes:
                   10207: 
1.749     raeburn  10208:  access controls are stored in file_permissions.db as key=value pairs.
                   10209:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10210:         where scope -> public,guest,course,group,domains or users.
                   10211:               end -> UNIX time for end of access (0 -> no end date)
                   10212:               start -> UNIX time for start of access
                   10213: 
                   10214:     value -> XML description of access control
                   10215:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10216:             <start></start>
                   10217:             <end></end>
                   10218: 
                   10219:             <password></password>  for scope type = guest
                   10220: 
                   10221:             <domain></domain>     for scope type = course or group
                   10222:             <number></number>
                   10223:             <roles id="">
                   10224:              <role></role>
                   10225:              <access></access>
                   10226:              <section></section>
                   10227:              <group></group>
                   10228:             </roles>
                   10229: 
                   10230:             <dom></dom>         for scope type = domains
                   10231: 
                   10232:             <users>             for scope type = users
                   10233:              <user>
                   10234:               <uname></uname>
                   10235:               <udom></udom>
                   10236:              </user>
                   10237:             </users>
                   10238:            </scope> 
                   10239:               
                   10240:  Access data is also aggregated for each file in an additional key=value pair:
                   10241:  key -> path to file/file_name\0accesscontrol 
                   10242:  value -> reference to hash
                   10243:           hash contains key = value pairs
                   10244:           where key = uniqueID:scope_end_start
                   10245:                 value = UNIX time record was last updated
                   10246: 
                   10247:           Used to improve speed of look-ups of access controls for each file.  
                   10248:  
                   10249:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10250: 
                   10251: modify_access_controls():
                   10252: 
                   10253: Modifies access controls for a portfolio file
                   10254: Args
                   10255: 1. file name
                   10256: 2. reference to hash of required changes,
                   10257: 3. domain
                   10258: 4. username
                   10259:   where domain,username are the domain of the portfolio owner 
                   10260:   (either a user or a course) 
                   10261: 
                   10262: Returns:
                   10263: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10264: 2. result of deletions ('ok' or 'error', with error message).
                   10265: 3. reference to hash of any new or updated access controls.
                   10266: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10267:    key = integer (inbound ID)
                   10268:    value = uniqueID  
1.747     albertel 10269: 
1.608     albertel 10270: =back
                   10271: 
1.243     albertel 10272: =head2 HTTP Helper Routines
                   10273: 
                   10274: =over 4
                   10275: 
1.191     harris41 10276: =item *
                   10277: 
                   10278: escape() : unpack non-word characters into CGI-compatible hex codes
                   10279: 
                   10280: =item *
                   10281: 
                   10282: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10283: 
1.243     albertel 10284: =back
                   10285: 
                   10286: =head1 PRIVATE SUBROUTINES
                   10287: 
                   10288: =head2 Underlying communication routines (Shouldn't call)
                   10289: 
                   10290: =over 4
                   10291: 
                   10292: =item *
                   10293: 
                   10294: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10295: 
                   10296: =item *
                   10297: 
                   10298: reply() : uses subreply to send a message to remote machine, logs all failures
                   10299: 
                   10300: =item *
                   10301: 
                   10302: critical() : passes a critical message to another server; if cannot
                   10303: get through then place message in connection buffer directory and
                   10304: returns con_delayed, if incapable of saving message, returns
                   10305: con_failed
                   10306: 
                   10307: =item *
                   10308: 
                   10309: reconlonc() : tries to reconnect lonc client processes.
                   10310: 
                   10311: =back
                   10312: 
                   10313: =head2 Resource Access Logging
                   10314: 
                   10315: =over 4
                   10316: 
                   10317: =item *
                   10318: 
                   10319: flushcourselogs() : flush (save) buffer logs and access logs
                   10320: 
                   10321: =item *
                   10322: 
                   10323: courselog($what) : save message for course in hash
                   10324: 
                   10325: =item *
                   10326: 
                   10327: courseacclog($what) : save message for course using &courselog().  Perform
                   10328: special processing for specific resource types (problems, exams, quizzes, etc).
                   10329: 
1.191     harris41 10330: =item *
                   10331: 
                   10332: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10333: as a PerlChildExitHandler
1.243     albertel 10334: 
                   10335: =back
                   10336: 
                   10337: =head2 Other
                   10338: 
                   10339: =over 4
                   10340: 
                   10341: =item *
                   10342: 
                   10343: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10344: 
                   10345: =back
                   10346: 
                   10347: =cut
1.877     foxr     10348: 

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