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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976.4.2! raeburn     4: # $Id: lonnet.pm,v 1.976.4.1 2009/09/16 20:02:48 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;
                     76: # use Date::Parse;
1.871     albertel   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    78:             $_64bit %env %protocol);
1.871     albertel   79: 
                     80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        83:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        84: 
1.1       albertel   85: use IO::Socket;
1.31      www        86: use GDBM_File;
1.208     albertel   87: use HTML::LCParser;
1.88      www        88: use Fcntl qw(:flock);
1.870     albertel   89: use Storable qw(thaw nfreeze);
1.539     albertel   90: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   91: use Cache::Memcached;
1.676     albertel   92: use Digest::MD5;
1.790     albertel   93: use Math::Random;
1.807     albertel   94: use LONCAPA qw(:DEFAULT :match);
1.740     www        95: use LONCAPA::Configuration;
1.676     albertel   96: 
1.195     www        97: my $readit;
1.550     foxr       98: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   99: 
1.619     albertel  100: require Exporter;
                    101: 
                    102: our @ISA = qw (Exporter);
                    103: our @EXPORT = qw(%env);
                    104: 
1.449     matthew   105: 
1.1       albertel  106: # --------------------------------------------------------------------- Logging
1.729     www       107: {
                    108:     my $logid;
                    109:     sub instructor_log {
1.957     raeburn   110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    111:         if (($cnum eq '') || ($cdom eq '')) {
                    112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    114:         }
1.729     www       115: 	$logid++;
1.957     raeburn   116:         my $now = time();
                    117: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       119: 				    { $id => {
                    120: 					'exe_uname' => $env{'user.name'},
                    121: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   122: 					'exe_time'  => $now,
1.730     www       123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    124: 					'delflag'   => $delflag,
                    125: 					'logentry'  => $storehash,
                    126: 					'uname'     => $uname,
                    127: 					'udom'      => $udom,
                    128: 				    }
1.957     raeburn   129: 				  },$cdom,$cnum);
1.729     www       130:     }
                    131: }
1.1       albertel  132: 
1.163     harris41  133: sub logtouch {
                    134:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  135:     unless (-e "$execdir/logs/lonnet.log") {	
                    136: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  137: 	close $fh;
                    138:     }
                    139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    141: }
                    142: 
1.1       albertel  143: sub logthis {
                    144:     my $message=shift;
                    145:     my $execdir=$perlvar{'lonDaemons'};
                    146:     my $now=time;
                    147:     my $local=localtime($now);
1.448     albertel  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    149: 	print $fh "$local ($$): $message\n";
                    150: 	close($fh);
                    151:     }
1.1       albertel  152:     return 1;
                    153: }
                    154: 
                    155: sub logperm {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.448     albertel  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    161: 	print $fh "$now:$message:$local\n";
                    162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
1.850     albertel  167: sub create_connection {
1.853     albertel  168:     my ($hostname,$lonid) = @_;
1.851     albertel  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  170: 				     Type    => SOCK_STREAM,
                    171: 				     Timeout => 10);
                    172:     return 0 if (!$client);
1.890     albertel  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  174:     my $result = <$client>;
                    175:     chomp($result);
                    176:     return 1 if ($result eq 'done');
                    177:     return 0;
                    178: }
                    179: 
1.976.4.1  raeburn   180: sub get_server_timezone {
                    181:     my ($cnum,$cdom) = @_;
                    182:     my $home=&homeserver($cnum,$cdom);
                    183:     if ($home ne 'no_host') {
                    184:         my $cachetime = 24*3600;
                    185:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    186:         if (defined($cached)) {
                    187:             return $timezone;
                    188:         } else {
                    189:             my $timezone = &reply('servertimezone',$home);
                    190:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    191:         }
                    192:     }
                    193: }
1.850     albertel  194: 
1.1       albertel  195: # -------------------------------------------------- Non-critical communication
                    196: sub subreply {
                    197:     my ($cmd,$server)=@_;
1.838     albertel  198:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      199:     #
                    200:     #  With loncnew process trimming, there's a timing hole between lonc server
                    201:     #  process exit and the master server picking up the listen on the AF_UNIX
                    202:     #  socket.  In that time interval, a lock file will exist:
                    203: 
                    204:     my $lockfile=$peerfile.".lock";
                    205:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    206: 	sleep(1);
                    207:     }
                    208:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      209:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      210:     #
1.550     foxr      211:     #   We'll give the connection a few tries before abandoning it.  If
                    212:     #   connection is not possible, we'll con_lost back to the client.
                    213:     #   
                    214:     my $client;
                    215:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    216: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    217: 				      Type    => SOCK_STREAM,
                    218: 				      Timeout => 10);
1.869     albertel  219: 	if ($client) {
1.550     foxr      220: 	    last;		# Connected!
1.850     albertel  221: 	} else {
1.853     albertel  222: 	    &create_connection(&hostname($server),$server);
1.550     foxr      223: 	}
1.850     albertel  224:         sleep(1);		# Try again later if failed connection.
1.550     foxr      225:     }
                    226:     my $answer;
                    227:     if ($client) {
1.704     albertel  228: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      229: 	$answer=<$client>;
                    230: 	if (!$answer) { $answer="con_lost"; }
                    231: 	chomp($answer);
                    232:     } else {
                    233: 	$answer = 'con_lost';	# Failed connection.
                    234:     }
1.1       albertel  235:     return $answer;
                    236: }
                    237: 
                    238: sub reply {
                    239:     my ($cmd,$server)=@_;
1.838     albertel  240:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  241:     my $answer=subreply($cmd,$server);
1.65      www       242:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  243:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       244:                 " $cmd to $server returned $answer</font>");
                    245:     }
1.1       albertel  246:     return $answer;
                    247: }
                    248: 
                    249: # ----------------------------------------------------------- Send USR1 to lonc
                    250: 
                    251: sub reconlonc {
1.891     albertel  252:     my ($lonid) = @_;
                    253:     my $hostname = &hostname($lonid);
                    254:     if ($lonid) {
                    255: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    256: 	if ($hostname && -e $peerfile) {
                    257: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    258: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    259: 					     Type    => SOCK_STREAM,
                    260: 					     Timeout => 10);
                    261: 	    if ($client) {
                    262: 		print $client ("reset_retries\n");
                    263: 		my $answer=<$client>;
                    264: 		#reset just this one.
                    265: 	    }
                    266: 	}
                    267: 	return;
                    268:     }
                    269: 
1.836     www       270:     &logthis("Trying to reconnect lonc");
1.1       albertel  271:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  272:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  273: 	my $loncpid=<$fh>;
                    274:         chomp($loncpid);
                    275:         if (kill 0 => $loncpid) {
                    276: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    277:             kill USR1 => $loncpid;
                    278:             sleep 1;
1.836     www       279:          } else {
1.12      www       280: 	    &logthis(
1.672     albertel  281:                "<font color=\"blue\">WARNING:".
1.12      www       282:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  283:         }
                    284:     } else {
1.836     www       285: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  286:     }
                    287: }
                    288: 
                    289: # ------------------------------------------------------ Critical communication
1.12      www       290: 
1.1       albertel  291: sub critical {
                    292:     my ($cmd,$server)=@_;
1.838     albertel  293:     unless (&hostname($server)) {
1.672     albertel  294:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       295:                " Critical message to unknown server ($server)</font>");
                    296:         return 'no_such_host';
                    297:     }
1.1       albertel  298:     my $answer=reply($cmd,$server);
                    299:     if ($answer eq 'con_lost') {
                    300: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  301: 	my $answer=reply($cmd,$server);
1.1       albertel  302:         if ($answer eq 'con_lost') {
                    303:             my $now=time;
                    304:             my $middlename=$cmd;
1.5       www       305:             $middlename=substr($middlename,0,16);
1.1       albertel  306:             $middlename=~s/\W//g;
                    307:             my $dfilename=
1.305     www       308:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    309:             $dumpcount++;
1.1       albertel  310:             {
1.448     albertel  311: 		my $dfh;
                    312: 		if (open($dfh,">$dfilename")) {
                    313: 		    print $dfh "$cmd\n"; 
                    314: 		    close($dfh);
                    315: 		}
1.1       albertel  316:             }
                    317:             sleep 2;
                    318:             my $wcmd='';
                    319:             {
1.448     albertel  320: 		my $dfh;
                    321: 		if (open($dfh,"<$dfilename")) {
                    322: 		    $wcmd=<$dfh>; 
                    323: 		    close($dfh);
                    324: 		}
1.1       albertel  325:             }
                    326:             chomp($wcmd);
1.7       www       327:             if ($wcmd eq $cmd) {
1.672     albertel  328: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       329:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  330:                 &logperm("D:$server:$cmd");
                    331: 	        return 'con_delayed';
                    332:             } else {
1.672     albertel  333:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       334:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  335:                 &logperm("F:$server:$cmd");
                    336:                 return 'con_failed';
                    337:             }
                    338:         }
                    339:     }
                    340:     return $answer;
1.405     albertel  341: }
                    342: 
1.755     albertel  343: # ------------------------------------------- check if return value is an error
                    344: 
                    345: sub error {
                    346:     my ($result) = @_;
1.756     albertel  347:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  348: 	if ($2 == 2) { return undef; }
                    349: 	return $1;
                    350:     }
                    351:     return undef;
                    352: }
                    353: 
1.783     albertel  354: sub convert_and_load_session_env {
                    355:     my ($lonidsdir,$handle)=@_;
                    356:     my @profile;
                    357:     {
1.917     albertel  358: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    359: 	if (!$opened) {
1.915     albertel  360: 	    return 0;
                    361: 	}
1.783     albertel  362: 	flock($idf,LOCK_SH);
                    363: 	@profile=<$idf>;
                    364: 	close($idf);
                    365:     }
                    366:     my %temp_env;
                    367:     foreach my $line (@profile) {
1.786     albertel  368: 	if ($line !~ m/=/) {
                    369: 	    return 0;
                    370: 	}
1.783     albertel  371: 	chomp($line);
                    372: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    373: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    374:     }
                    375:     unlink("$lonidsdir/$handle.id");
                    376:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    377: 	    0640)) {
                    378: 	%disk_env = %temp_env;
                    379: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    380: 	untie(%disk_env);
                    381:     }
1.786     albertel  382:     return 1;
1.783     albertel  383: }
                    384: 
1.374     www       385: # ------------------------------------------- Transfer profile into environment
1.780     albertel  386: my $env_loaded;
                    387: sub transfer_profile_to_env {
1.788     albertel  388:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    389:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       390: 
1.720     albertel  391:     if (!defined($lonidsdir)) {
                    392: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    393:     }
                    394:     if (!defined($handle)) {
                    395:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    396:     }
                    397: 
1.786     albertel  398:     my $convert;
                    399:     {
1.917     albertel  400:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    401: 	if (!$opened) {
1.915     albertel  402: 	    return;
                    403: 	}
1.786     albertel  404: 	flock($idf,LOCK_SH);
                    405: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    406: 		&GDBM_READER(),0640)) {
                    407: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    408: 	    untie(%disk_env);
                    409: 	} else {
                    410: 	    $convert = 1;
                    411: 	}
                    412:     }
                    413:     if ($convert) {
                    414: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    415: 	    &logthis("Failed to load session, or convert session.");
                    416: 	}
1.374     www       417:     }
1.783     albertel  418: 
1.786     albertel  419:     my %remove;
1.783     albertel  420:     while ( my $envname = each(%env) ) {
1.433     matthew   421:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    422:             if ($time < time-300) {
1.783     albertel  423:                 $remove{$key}++;
1.433     matthew   424:             }
                    425:         }
                    426:     }
1.783     albertel  427: 
1.619     albertel  428:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  429:     $env_loaded=1;
1.783     albertel  430:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   431:         &delenv($expired_key);
1.374     www       432:     }
1.1       albertel  433: }
                    434: 
1.916     albertel  435: # ---------------------------------------------------- Check for valid session 
                    436: sub check_for_valid_session {
                    437:     my ($r) = @_;
                    438:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    439:     my $lonid=$cookies{'lonID'};
                    440:     return undef if (!$lonid);
                    441: 
                    442:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    443:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    444:     return undef if (!-e "$lonidsdir/$handle.id");
                    445: 
1.917     albertel  446:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    447:     return undef if (!$opened);
1.916     albertel  448: 
                    449:     flock($idf,LOCK_SH);
                    450:     my %disk_env;
                    451:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    452: 	    &GDBM_READER(),0640)) {
                    453: 	return undef;	
                    454:     }
                    455: 
                    456:     if (!defined($disk_env{'user.name'})
                    457: 	|| !defined($disk_env{'user.domain'})) {
                    458: 	return undef;
                    459:     }
                    460:     return $handle;
                    461: }
                    462: 
1.830     albertel  463: sub timed_flock {
                    464:     my ($file,$lock_type) = @_;
                    465:     my $failed=0;
                    466:     eval {
                    467: 	local $SIG{__DIE__}='DEFAULT';
                    468: 	local $SIG{ALRM}=sub {
                    469: 	    $failed=1;
                    470: 	    die("failed lock");
                    471: 	};
                    472: 	alarm(13);
                    473: 	flock($file,$lock_type);
                    474: 	alarm(0);
                    475:     };
                    476:     if ($failed) {
                    477: 	return undef;
                    478:     } else {
                    479: 	return 1;
                    480:     }
                    481: }
                    482: 
1.5       www       483: # ---------------------------------------------------------- Append Environment
                    484: 
                    485: sub appenv {
1.949     raeburn   486:     my ($newenv,$roles) = @_;
                    487:     if (ref($newenv) eq 'HASH') {
                    488:         foreach my $key (keys(%{$newenv})) {
                    489:             my $refused = 0;
                    490: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    491:                 $refused = 1;
                    492:                 if (ref($roles) eq 'ARRAY') {
                    493:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    494:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    495:                         $refused = 0;
                    496:                     }
                    497:                 }
                    498:             }
                    499:             if ($refused) {
                    500:                 &logthis("<font color=\"blue\">WARNING: ".
                    501:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    502:                          .'</font>');
                    503: 	        delete($newenv->{$key});
                    504:             } else {
                    505:                 $env{$key}=$newenv->{$key};
                    506:             }
                    507:         }
                    508:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    509:         if ($opened
                    510: 	    && &timed_flock($env_file,LOCK_EX)
                    511: 	    &&
                    512: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    513: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    514: 	    while (my ($key,$value) = each(%{$newenv})) {
                    515: 	        $disk_env{$key} = $value;
                    516: 	    }
                    517: 	    untie(%disk_env);
1.35      www       518:         }
1.191     harris41  519:     }
1.56      www       520:     return 'ok';
                    521: }
                    522: # ----------------------------------------------------- Delete from Environment
                    523: 
                    524: sub delenv {
1.976.4.1  raeburn   525:     my ($delthis,$regexp) = @_;
1.56      www       526:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  527:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       528:                 "Attempt to delete from environment ".$delthis);
                    529:         return 'error';
                    530:     }
1.917     albertel  531:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    532:     if ($opened
1.915     albertel  533: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  534: 	&&
                    535: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    536: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  537: 	foreach my $key (keys(%disk_env)) {
1.976.4.1  raeburn   538:             if ($regexp) {
                    539:                 if ($key=~/^$delthis/) {
                    540:                     delete($env{$key});
                    541:                     delete($disk_env{$key});
                    542:                 }
                    543:             } else {
                    544:                 if ($key=~/^\Q$delthis\E/) {
                    545:                     delete($env{$key});
                    546:                     delete($disk_env{$key});
                    547:                 }
                    548:             }
1.448     albertel  549: 	}
1.783     albertel  550: 	untie(%disk_env);
1.5       www       551:     }
                    552:     return 'ok';
1.369     albertel  553: }
                    554: 
1.790     albertel  555: sub get_env_multiple {
                    556:     my ($name) = @_;
                    557:     my @values;
                    558:     if (defined($env{$name})) {
                    559:         # exists is it an array
                    560:         if (ref($env{$name})) {
                    561:             @values=@{ $env{$name} };
                    562:         } else {
                    563:             $values[0]=$env{$name};
                    564:         }
                    565:     }
                    566:     return(@values);
                    567: }
                    568: 
1.958     www       569: # ------------------------------------------------------------------- Locking
                    570: 
                    571: sub set_lock {
                    572:     my ($text)=@_;
                    573:     $locknum++;
                    574:     my $id=$$.'-'.$locknum;
                    575:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    576:              'session.lock.'.$id => $text});
                    577:     return $id;
                    578: }
                    579: 
                    580: sub get_locks {
                    581:     my $num=0;
                    582:     my %texts=();
                    583:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    584:        if ($lock=~/\w/) {
                    585:           $num++;
                    586:           $texts{$lock}=$env{'session.lock.'.$lock};
                    587:        }
                    588:    }
                    589:    return ($num,%texts);
                    590: }
                    591: 
                    592: sub remove_lock {
                    593:     my ($id)=@_;
                    594:     my $newlocks='';
                    595:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    596:        if (($lock=~/\w/) && ($lock ne $id)) {
                    597:           $newlocks.=','.$lock;
                    598:        }
                    599:     }
                    600:     &appenv({'session.locks' => $newlocks});
                    601:     &delenv('session.lock.'.$id);
                    602: }
                    603: 
                    604: sub remove_all_locks {
                    605:     my $activelocks=$env{'session.locks'};
                    606:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    607:        if ($lock=~/\w/) {
                    608:           &remove_lock($lock);
                    609:        }
                    610:     }
                    611: }
                    612: 
                    613: 
1.369     albertel  614: # ------------------------------------------ Find out current server userload
                    615: sub userload {
                    616:     my $numusers=0;
                    617:     {
                    618: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    619: 	my $filename;
                    620: 	my $curtime=time;
                    621: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  622: 	    next if ($filename eq '.' || $filename eq '..');
                    623: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  624: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  625: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  626: 	}
                    627: 	closedir(LONIDS);
                    628:     }
                    629:     my $userloadpercent=0;
                    630:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    631:     if ($maxuserload) {
1.371     albertel  632: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  633:     }
1.372     albertel  634:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  635:     return $userloadpercent;
1.283     www       636: }
                    637: 
                    638: # ------------------------------------------ Fight off request when overloaded
                    639: 
                    640: sub overloaderror {
                    641:     my ($r,$checkserver)=@_;
                    642:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    643:     my $loadavg;
                    644:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  645:        open(my $loadfile,'/proc/loadavg');
1.283     www       646:        $loadavg=<$loadfile>;
                    647:        $loadavg =~ s/\s.*//g;
1.285     matthew   648:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  649:        close($loadfile);
1.283     www       650:     } else {
                    651:        $loadavg=&reply('load',$checkserver);
                    652:     }
1.285     matthew   653:     my $overload=$loadavg-100;
1.283     www       654:     if ($overload>0) {
1.285     matthew   655: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       656:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       657:         return 413;
1.283     www       658:     }    
                    659:     return '';
1.5       www       660: }
1.1       albertel  661: 
                    662: # ------------------------------ Find server with least workload from spare.tab
1.11      www       663: 
1.1       albertel  664: sub spareserver {
1.670     albertel  665:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  666:     my $spare_server;
1.370     albertel  667:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  668:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    669:                                                      :  $userloadpercent;
                    670:     
                    671:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    672: 	($spare_server, $lowest_load) =
                    673: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    674:     }
                    675: 
                    676:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    677: 
                    678:     if (!$found_server) {
                    679: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    680: 	    ($spare_server, $lowest_load) =
                    681: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    682: 	}
                    683:     }
                    684: 
                    685:     if (!$want_server_name) {
1.968     raeburn   686:         my $protocol = 'http';
                    687:         if ($protocol{$spare_server} eq 'https') {
                    688:             $protocol = $protocol{$spare_server};
                    689:         }
                    690: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  691:     }
                    692:     return $spare_server;
                    693: }
                    694: 
                    695: sub compare_server_load {
                    696:     my ($try_server, $spare_server, $lowest_load) = @_;
                    697: 
                    698:     my $loadans     = &reply('load',    $try_server);
                    699:     my $userloadans = &reply('userload',$try_server);
                    700: 
                    701:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    702: 	next; #didn't get a number from the server
                    703:     }
                    704: 
                    705:     my $load;
                    706:     if ($loadans =~ /\d/) {
                    707: 	if ($userloadans =~ /\d/) {
                    708: 	    #both are numbers, pick the bigger one
                    709: 	    $load = ($loadans > $userloadans) ? $loadans 
                    710: 		                              : $userloadans;
1.411     albertel  711: 	} else {
1.784     albertel  712: 	    $load = $loadans;
1.411     albertel  713: 	}
1.784     albertel  714:     } else {
                    715: 	$load = $userloadans;
                    716:     }
                    717: 
                    718:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    719: 	$spare_server = $try_server;
                    720: 	$lowest_load  = $load;
1.370     albertel  721:     }
1.784     albertel  722:     return ($spare_server,$lowest_load);
1.202     matthew   723: }
1.914     albertel  724: 
                    725: # --------------------------- ask offload servers if user already has a session
                    726: sub find_existing_session {
                    727:     my ($udom,$uname) = @_;
                    728:     foreach my $try_server (@{ $spareid{'primary'} },
                    729: 			    @{ $spareid{'default'} }) {
                    730: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    731:     }
                    732:     return;
                    733: }
                    734: 
                    735: # -------------------------------- ask if server already has a session for user
                    736: sub has_user_session {
                    737:     my ($lonid,$udom,$uname) = @_;
                    738:     my $result = &reply(join(':','userhassession',
                    739: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    740:     return 1 if ($result eq 'ok');
                    741: 
                    742:     return 0;
                    743: }
                    744: 
1.202     matthew   745: # --------------------------------------------- Try to change a user's password
                    746: 
                    747: sub changepass {
1.799     raeburn   748:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   749:     $currentpass = &escape($currentpass);
                    750:     $newpass     = &escape($newpass);
1.799     raeburn   751:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   752: 		       $server);
                    753:     if (! $answer) {
                    754: 	&logthis("No reply on password change request to $server ".
                    755: 		 "by $uname in domain $udom.");
                    756:     } elsif ($answer =~ "^ok") {
                    757:         &logthis("$uname in $udom successfully changed their password ".
                    758: 		 "on $server.");
                    759:     } elsif ($answer =~ "^pwchange_failure") {
                    760: 	&logthis("$uname in $udom was unable to change their password ".
                    761: 		 "on $server.  The action was blocked by either lcpasswd ".
                    762: 		 "or pwchange");
                    763:     } elsif ($answer =~ "^non_authorized") {
                    764:         &logthis("$uname in $udom did not get their password correct when ".
                    765: 		 "attempting to change it on $server.");
                    766:     } elsif ($answer =~ "^auth_mode_error") {
                    767:         &logthis("$uname in $udom attempted to change their password despite ".
                    768: 		 "not being locally or internally authenticated on $server.");
                    769:     } elsif ($answer =~ "^unknown_user") {
                    770:         &logthis("$uname in $udom attempted to change their password ".
                    771: 		 "on $server but were unable to because $server is not ".
                    772: 		 "their home server.");
                    773:     } elsif ($answer =~ "^refused") {
                    774: 	&logthis("$server refused to change $uname in $udom password because ".
                    775: 		 "it was sent an unencrypted request to change the password.");
                    776:     }
                    777:     return $answer;
1.1       albertel  778: }
                    779: 
1.169     harris41  780: # ----------------------- Try to determine user's current authentication scheme
                    781: 
                    782: sub queryauthenticate {
                    783:     my ($uname,$udom)=@_;
1.456     albertel  784:     my $uhome=&homeserver($uname,$udom);
                    785:     if (!$uhome) {
                    786: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    787: 	return 'no_host';
                    788:     }
                    789:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    790:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    791: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  792:     }
1.456     albertel  793:     return $answer;
1.169     harris41  794: }
                    795: 
1.1       albertel  796: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       797: 
1.1       albertel  798: sub authenticate {
1.952     raeburn   799:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  800:     $upass=&escape($upass);
                    801:     $uname= &LONCAPA::clean_username($uname);
1.836     www       802:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   803:     my $newhome;
1.836     www       804:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    805: # Maybe the machine was offline and only re-appeared again recently?
                    806:         &reconlonc();
                    807: # One more
1.952     raeburn   808: 	$uhome=&homeserver($uname,$udom,1);
                    809:         if (($uhome eq 'no_host') && $checkdefauth) {
                    810:             if (defined(&domain($udom,'primary'))) {
                    811:                 $newhome=&domain($udom,'primary');
                    812:             }
                    813:             if ($newhome ne '') {
                    814:                 $uhome = $newhome;
                    815:             }
                    816:         }
1.836     www       817: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    818: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   819: 	    return 'no_host';
                    820:         }
1.1       albertel  821:     }
1.952     raeburn   822:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  823:     if ($answer eq 'authorized') {
1.952     raeburn   824:         if ($newhome) {
                    825:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    826:             return 'no_account_on_host'; 
                    827:         } else {
                    828:             &logthis("User $uname at $udom authorized by $uhome");
                    829:             return $uhome;
                    830:         }
1.471     albertel  831:     }
                    832:     if ($answer eq 'non_authorized') {
                    833: 	&logthis("User $uname at $udom rejected by $uhome");
                    834: 	return 'no_host'; 
1.9       www       835:     }
1.471     albertel  836:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  837:     return 'no_host';
                    838: }
                    839: 
                    840: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       841: 
1.599     albertel  842: my %homecache;
1.1       albertel  843: sub homeserver {
1.230     stredwic  844:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  845:     my $index="$uname:$udom";
1.426     albertel  846: 
1.599     albertel  847:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  848: 
                    849:     my %servers = &get_servers($udom,'library');
                    850:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  851:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  852: 		 exists($badServerCache{$tryserver}));
1.841     albertel  853: 
                    854: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    855: 	if ($answer eq 'found') {
                    856: 	    delete($badServerCache{$tryserver}); 
                    857: 	    return $homecache{$index}=$tryserver;
                    858: 	} elsif ($answer eq 'no_host') {
                    859: 	    $badServerCache{$tryserver}=1;
                    860: 	}
1.1       albertel  861:     }    
                    862:     return 'no_host';
1.70      www       863: }
                    864: 
                    865: # ------------------------------------- Find the usernames behind a list of IDs
                    866: 
                    867: sub idget {
                    868:     my ($udom,@ids)=@_;
                    869:     my %returnhash=();
                    870:     
1.841     albertel  871:     my %servers = &get_servers($udom,'library');
                    872:     foreach my $tryserver (keys(%servers)) {
                    873: 	my $idlist=join('&',@ids);
                    874: 	$idlist=~tr/A-Z/a-z/; 
                    875: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    876: 	my @answer=();
                    877: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    878: 	    @answer=split(/\&/,$reply);
                    879: 	}                    ;
                    880: 	my $i;
                    881: 	for ($i=0;$i<=$#ids;$i++) {
                    882: 	    if ($answer[$i]) {
                    883: 		$returnhash{$ids[$i]}=$answer[$i];
                    884: 	    } 
                    885: 	}
                    886:     } 
1.70      www       887:     return %returnhash;
                    888: }
                    889: 
                    890: # ------------------------------------- Find the IDs behind a list of usernames
                    891: 
                    892: sub idrget {
                    893:     my ($udom,@unames)=@_;
                    894:     my %returnhash=();
1.800     albertel  895:     foreach my $uname (@unames) {
                    896:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  897:     }
1.70      www       898:     return %returnhash;
                    899: }
                    900: 
                    901: # ------------------------------- Store away a list of names and associated IDs
                    902: 
                    903: sub idput {
                    904:     my ($udom,%ids)=@_;
                    905:     my %servers=();
1.800     albertel  906:     foreach my $uname (keys(%ids)) {
                    907: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    908:         my $uhom=&homeserver($uname,$udom);
1.70      www       909:         if ($uhom ne 'no_host') {
1.800     albertel  910:             my $id=&escape($ids{$uname});
1.70      www       911:             $id=~tr/A-Z/a-z/;
1.800     albertel  912:             my $esc_unam=&escape($uname);
1.70      www       913: 	    if ($servers{$uhom}) {
1.800     albertel  914: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       915:             } else {
1.800     albertel  916:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       917:             }
                    918:         }
1.191     harris41  919:     }
1.800     albertel  920:     foreach my $server (keys(%servers)) {
                    921:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  922:     }
1.344     www       923: }
                    924: 
1.806     raeburn   925: # ------------------------------------------- get items from domain db files   
                    926: 
                    927: sub get_dom {
1.860     raeburn   928:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   929:     my $items='';
                    930:     foreach my $item (@$storearr) {
                    931:         $items.=&escape($item).'&';
                    932:     }
                    933:     $items=~s/\&$//;
1.860     raeburn   934:     if (!$udom) {
                    935:         $udom=$env{'user.domain'};
                    936:         if (defined(&domain($udom,'primary'))) {
                    937:             $uhome=&domain($udom,'primary');
                    938:         } else {
1.874     albertel  939:             undef($uhome);
1.860     raeburn   940:         }
                    941:     } else {
                    942:         if (!$uhome) {
                    943:             if (defined(&domain($udom,'primary'))) {
                    944:                 $uhome=&domain($udom,'primary');
                    945:             }
                    946:         }
                    947:     }
                    948:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   949:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   950:         my %returnhash;
1.875     albertel  951:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   952:             return %returnhash;
                    953:         }
1.806     raeburn   954:         my @pairs=split(/\&/,$rep);
                    955:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    956:             return @pairs;
                    957:         }
                    958:         my $i=0;
                    959:         foreach my $item (@$storearr) {
                    960:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    961:             $i++;
                    962:         }
                    963:         return %returnhash;
                    964:     } else {
1.880     banghart  965:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   966:     }
                    967: }
                    968: 
                    969: # -------------------------------------------- put items in domain db files 
                    970: 
                    971: sub put_dom {
1.860     raeburn   972:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    973:     if (!$udom) {
                    974:         $udom=$env{'user.domain'};
                    975:         if (defined(&domain($udom,'primary'))) {
                    976:             $uhome=&domain($udom,'primary');
                    977:         } else {
1.874     albertel  978:             undef($uhome);
1.860     raeburn   979:         }
                    980:     } else {
                    981:         if (!$uhome) {
                    982:             if (defined(&domain($udom,'primary'))) {
                    983:                 $uhome=&domain($udom,'primary');
                    984:             }
                    985:         }
                    986:     } 
                    987:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   988:         my $items='';
                    989:         foreach my $item (keys(%$storehash)) {
                    990:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    991:         }
                    992:         $items=~s/\&$//;
                    993:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    994:     } else {
1.860     raeburn   995:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   996:     }
                    997: }
                    998: 
1.837     raeburn   999: sub retrieve_inst_usertypes {
                   1000:     my ($udom) = @_;
                   1001:     my (%returnhash,@order);
1.846     albertel 1002:     if (defined(&domain($udom,'primary'))) {
                   1003:         my $uhome=&domain($udom,'primary');
1.837     raeburn  1004:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn  1005:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1006:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1007:             return (\%returnhash,\@order);
                   1008:         }
1.837     raeburn  1009:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1010:         my @pairs=split(/\&/,$hashitems);
                   1011:         foreach my $item (@pairs) {
                   1012:             my ($key,$value)=split(/=/,$item,2);
                   1013:             $key = &unescape($key);
                   1014:             next if ($key =~ /^error: 2 /);
                   1015:             $returnhash{$key}=&thaw_unescape($value);
                   1016:         }
                   1017:         my @esc_order = split(/\&/,$orderitems);
                   1018:         foreach my $item (@esc_order) {
                   1019:             push(@order,&unescape($item));
                   1020:         }
                   1021:     } else {
                   1022:         &logthis("get_dom failed - no primary domain server for $udom");
                   1023:     }
                   1024:     return (\%returnhash,\@order);
                   1025: }
                   1026: 
1.868     raeburn  1027: sub is_domainimage {
                   1028:     my ($url) = @_;
                   1029:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1030:         if (&domain($1) ne '') {
                   1031:             return '1';
                   1032:         }
                   1033:     }
                   1034:     return;
                   1035: }
                   1036: 
1.899     raeburn  1037: sub inst_directory_query {
                   1038:     my ($srch) = @_;
                   1039:     my $udom = $srch->{'srchdomain'};
                   1040:     my %results;
                   1041:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1042:     my $outcome;
1.899     raeburn  1043:     if ($homeserver ne '') {
1.904     albertel 1044: 	my $queryid=&reply("querysend:instdirsearch:".
                   1045: 			   &escape($srch->{'srchby'}).':'.
                   1046: 			   &escape($srch->{'srchterm'}).':'.
                   1047: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1048: 	my $host=&hostname($homeserver);
                   1049: 	if ($queryid !~/^\Q$host\E\_/) {
                   1050: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1051: 	    return;
                   1052: 	}
                   1053: 	my $response = &get_query_reply($queryid);
                   1054: 	my $maxtries = 5;
                   1055: 	my $tries = 1;
                   1056: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1057: 	    $response = &get_query_reply($queryid);
                   1058: 	    $tries ++;
                   1059: 	}
                   1060: 
                   1061:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1062:             if ($response eq 'unavailable') {
                   1063:                 $outcome = $response;
                   1064:             } else {
                   1065:                 $outcome = 'ok';
                   1066:                 my @matches = split(/\n/,$response);
                   1067:                 foreach my $match (@matches) {
                   1068:                     my ($key,$value) = split(/=/,$match);
                   1069:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1070:                 }
1.899     raeburn  1071:             }
                   1072:         }
                   1073:     }
1.909     raeburn  1074:     return ($outcome,%results);
1.899     raeburn  1075: }
                   1076: 
                   1077: sub usersearch {
                   1078:     my ($srch) = @_;
                   1079:     my $dom = $srch->{'srchdomain'};
                   1080:     my %results;
                   1081:     my %libserv = &all_library();
                   1082:     my $query = 'usersearch';
                   1083:     foreach my $tryserver (keys(%libserv)) {
                   1084:         if (&host_domain($tryserver) eq $dom) {
                   1085:             my $host=&hostname($tryserver);
                   1086:             my $queryid=
1.911     raeburn  1087:                 &reply("querysend:".&escape($query).':'.
                   1088:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1089:                        &escape($srch->{'srchtype'}).':'.
                   1090:                        &escape($srch->{'srchterm'}),$tryserver);
                   1091:             if ($queryid !~/^\Q$host\E\_/) {
                   1092:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1093:                 next;
1.899     raeburn  1094:             }
                   1095:             my $reply = &get_query_reply($queryid);
                   1096:             my $maxtries = 1;
                   1097:             my $tries = 1;
                   1098:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1099:                 $reply = &get_query_reply($queryid);
                   1100:                 $tries ++;
                   1101:             }
                   1102:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1103:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1104:             } else {
1.911     raeburn  1105:                 my @matches;
                   1106:                 if ($reply =~ /\n/) {
                   1107:                     @matches = split(/\n/,$reply);
                   1108:                 } else {
                   1109:                     @matches = split(/\&/,$reply);
                   1110:                 }
1.899     raeburn  1111:                 foreach my $match (@matches) {
                   1112:                     my ($uname,$udom,%userhash);
1.911     raeburn  1113:                     foreach my $entry (split(/:/,$match)) {
                   1114:                         my ($key,$value) =
                   1115:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1116:                         $userhash{$key} = $value;
                   1117:                         if ($key eq 'username') {
                   1118:                             $uname = $value;
                   1119:                         } elsif ($key eq 'domain') {
                   1120:                             $udom = $value;
1.911     raeburn  1121:                         }
1.899     raeburn  1122:                     }
                   1123:                     $results{$uname.':'.$udom} = \%userhash;
                   1124:                 }
                   1125:             }
                   1126:         }
                   1127:     }
                   1128:     return %results;
                   1129: }
                   1130: 
1.912     raeburn  1131: sub get_instuser {
                   1132:     my ($udom,$uname,$id) = @_;
                   1133:     my $homeserver = &domain($udom,'primary');
                   1134:     my ($outcome,%results);
                   1135:     if ($homeserver ne '') {
                   1136:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1137:                            &escape($id).':'.&escape($udom),$homeserver);
                   1138:         my $host=&hostname($homeserver);
                   1139:         if ($queryid !~/^\Q$host\E\_/) {
                   1140:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1141:             return;
                   1142:         }
                   1143:         my $response = &get_query_reply($queryid);
                   1144:         my $maxtries = 5;
                   1145:         my $tries = 1;
                   1146:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1147:             $response = &get_query_reply($queryid);
                   1148:             $tries ++;
                   1149:         }
                   1150:         if (!&error($response) && $response ne 'refused') {
                   1151:             if ($response eq 'unavailable') {
                   1152:                 $outcome = $response;
                   1153:             } else {
                   1154:                 $outcome = 'ok';
                   1155:                 my @matches = split(/\n/,$response);
                   1156:                 foreach my $match (@matches) {
                   1157:                     my ($key,$value) = split(/=/,$match);
                   1158:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1159:                 }
                   1160:             }
                   1161:         }
                   1162:     }
                   1163:     my %userinfo;
                   1164:     if (ref($results{$uname}) eq 'HASH') {
                   1165:         %userinfo = %{$results{$uname}};
                   1166:     } 
                   1167:     return ($outcome,%userinfo);
                   1168: }
                   1169: 
                   1170: sub inst_rulecheck {
1.923     raeburn  1171:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1172:     my %returnhash;
                   1173:     if ($udom ne '') {
                   1174:         if (ref($rules) eq 'ARRAY') {
                   1175:             @{$rules} = map {&escape($_);} (@{$rules});
                   1176:             my $rulestr = join(':',@{$rules});
                   1177:             my $homeserver=&domain($udom,'primary');
                   1178:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1179:                 my $response;
                   1180:                 if ($item eq 'username') {                
                   1181:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1182:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1183:                                               $homeserver));
1.923     raeburn  1184:                 } elsif ($item eq 'id') {
                   1185:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1186:                                               ':'.&escape($id).':'.$rulestr,
                   1187:                                               $homeserver));
1.945     raeburn  1188:                 } elsif ($item eq 'selfcreate') {
                   1189:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1190:                                                &escape($udom).':'.&escape($uname).
                   1191:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1192:                 }
1.912     raeburn  1193:                 if ($response ne 'refused') {
                   1194:                     my @pairs=split(/\&/,$response);
                   1195:                     foreach my $item (@pairs) {
                   1196:                         my ($key,$value)=split(/=/,$item,2);
                   1197:                         $key = &unescape($key);
                   1198:                         next if ($key =~ /^error: 2 /);
                   1199:                         $returnhash{$key}=&thaw_unescape($value);
                   1200:                     }
                   1201:                 }
                   1202:             }
                   1203:         }
                   1204:     }
                   1205:     return %returnhash;
                   1206: }
                   1207: 
                   1208: sub inst_userrules {
1.923     raeburn  1209:     my ($udom,$check) = @_;
1.912     raeburn  1210:     my (%ruleshash,@ruleorder);
                   1211:     if ($udom ne '') {
                   1212:         my $homeserver=&domain($udom,'primary');
                   1213:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1214:             my $response;
                   1215:             if ($check eq 'id') {
                   1216:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1217:                                  $homeserver);
1.943     raeburn  1218:             } elsif ($check eq 'email') {
                   1219:                 $response=&reply('instemailrules:'.&escape($udom),
                   1220:                                  $homeserver);
1.923     raeburn  1221:             } else {
                   1222:                 $response=&reply('instuserrules:'.&escape($udom),
                   1223:                                  $homeserver);
                   1224:             }
1.912     raeburn  1225:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1226:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1227:                 ($response ne 'no_such_host')) {
                   1228:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1229:                 my @pairs=split(/\&/,$hashitems);
                   1230:                 foreach my $item (@pairs) {
                   1231:                     my ($key,$value)=split(/=/,$item,2);
                   1232:                     $key = &unescape($key);
                   1233:                     next if ($key =~ /^error: 2 /);
                   1234:                     $ruleshash{$key}=&thaw_unescape($value);
                   1235:                 }
                   1236:                 my @esc_order = split(/\&/,$orderitems);
                   1237:                 foreach my $item (@esc_order) {
                   1238:                     push(@ruleorder,&unescape($item));
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return (\%ruleshash,\@ruleorder);
                   1244: }
                   1245: 
1.976     raeburn  1246: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1247: 
                   1248: sub get_domain_defaults {
                   1249:     my ($domain) = @_;
                   1250:     my $cachetime = 60*60*24;
                   1251:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1252:     if (defined($cached)) {
                   1253:         if (ref($result) eq 'HASH') {
                   1254:             return %{$result};
                   1255:         }
                   1256:     }
                   1257:     my %domdefaults;
                   1258:     my %domconfig =
1.976     raeburn  1259:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1260:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1261:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1262:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1263:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.976.4.1  raeburn  1264:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
                   1265:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1266:     } else {
                   1267:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1268:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1269:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1270:     }
1.976     raeburn  1271:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1272:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1273:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1274:         } else {
                   1275:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1276:         } 
                   1277:         my @usertools = ('aboutme','blog','portfolio');
                   1278:         foreach my $item (@usertools) {
                   1279:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1280:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1281:             }
                   1282:         }
                   1283:     }
1.943     raeburn  1284:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1285:                                   $cachetime);
                   1286:     return %domdefaults;
                   1287: }
                   1288: 
1.344     www      1289: # --------------------------------------------------- Assign a key to a student
                   1290: 
                   1291: sub assign_access_key {
1.364     www      1292: #
                   1293: # a valid key looks like uname:udom#comments
                   1294: # comments are being appended
                   1295: #
1.498     www      1296:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1297:     $kdom=
1.620     albertel 1298:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1299:     $knum=
1.620     albertel 1300:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1301:     $cdom=
1.620     albertel 1302:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1303:     $cnum=
1.620     albertel 1304:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1305:     $udom=$env{'user.name'} unless (defined($udom));
                   1306:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1307:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1308:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1309:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1310:                                                   # assigned to this person
                   1311:                                                   # - this should not happen,
1.345     www      1312:                                                   # unless something went wrong
                   1313:                                                   # the first time around
                   1314: # ready to assign
1.364     www      1315:         $logentry=$1.'; '.$logentry;
1.496     www      1316:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1317:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1318: # key now belongs to user
1.346     www      1319: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1320:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1321:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1322:                 return 'ok';
                   1323:             } else {
                   1324:                 return 
                   1325:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1326: 	    }
                   1327:         } else {
                   1328:             return 'error: Could not assign key, try again later.';
                   1329:         }
1.364     www      1330:     } elsif (!$existing{$ckey}) {
1.345     www      1331: # the key does not exist
                   1332: 	return 'error: The key does not exist';
                   1333:     } else {
                   1334: # the key is somebody else's
                   1335: 	return 'error: The key is already in use';
                   1336:     }
1.344     www      1337: }
                   1338: 
1.364     www      1339: # ------------------------------------------ put an additional comment on a key
                   1340: 
                   1341: sub comment_access_key {
                   1342: #
                   1343: # a valid key looks like uname:udom#comments
                   1344: # comments are being appended
                   1345: #
                   1346:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1347:     $cdom=
1.620     albertel 1348:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1349:     $cnum=
1.620     albertel 1350:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1351:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1352:     if ($existing{$ckey}) {
                   1353:         $existing{$ckey}.='; '.$logentry;
                   1354: # ready to assign
1.367     www      1355:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1356:                                                  $cdom,$cnum) eq 'ok') {
                   1357: 	    return 'ok';
                   1358:         } else {
                   1359: 	    return 'error: Count not store comment.';
                   1360:         }
                   1361:     } else {
                   1362: # the key does not exist
                   1363: 	return 'error: The key does not exist';
                   1364:     }
                   1365: }
                   1366: 
1.344     www      1367: # ------------------------------------------------------ Generate a set of keys
                   1368: 
                   1369: sub generate_access_keys {
1.364     www      1370:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1371:     $cdom=
1.620     albertel 1372:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1373:     $cnum=
1.620     albertel 1374:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1375:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1376:     unless (($cdom) && ($cnum)) { return 0; }
                   1377:     if ($number>10000) { return 0; }
                   1378:     sleep(2); # make sure don't get same seed twice
                   1379:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1380:     my $total=0;
                   1381:     for (my $i=1;$i<=$number;$i++) {
                   1382:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1383:                   sprintf("%lx",int(100000*rand)).'-'.
                   1384:                   sprintf("%lx",int(100000*rand));
                   1385:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1386:        $newkey=~s/0/h/g; # and also 0 and O
                   1387:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1388:        if ($existing{$newkey}) {
                   1389:            $i--;
                   1390:        } else {
1.364     www      1391: 	  if (&put('accesskeys',
                   1392:               { $newkey => '# generated '.localtime().
1.620     albertel 1393:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1394:                            '; '.$logentry },
                   1395: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1396:               $total++;
                   1397: 	  }
                   1398:        }
                   1399:     }
1.620     albertel 1400:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1401:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1402:     return $total;
                   1403: }
                   1404: 
                   1405: # ------------------------------------------------------- Validate an accesskey
                   1406: 
                   1407: sub validate_access_key {
                   1408:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1409:     $cdom=
1.620     albertel 1410:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1411:     $cnum=
1.620     albertel 1412:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1413:     $udom=$env{'user.domain'} unless (defined($udom));
                   1414:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1415:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1416:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1417: }
                   1418: 
                   1419: # ------------------------------------- Find the section of student in a course
1.652     albertel 1420: sub devalidate_getsection_cache {
                   1421:     my ($udom,$unam,$courseid)=@_;
                   1422:     my $hashid="$udom:$unam:$courseid";
                   1423:     &devalidate_cache_new('getsection',$hashid);
                   1424: }
1.298     matthew  1425: 
1.815     albertel 1426: sub courseid_to_courseurl {
                   1427:     my ($courseid) = @_;
                   1428:     #already url style courseid
                   1429:     return $courseid if ($courseid =~ m{^/});
                   1430: 
                   1431:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1432: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1433: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1434: 	return "/$cdom/$cnum";
                   1435:     }
                   1436: 
                   1437:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1438:     if (exists($courseinfo{'num'})) {
                   1439: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1440:     }
                   1441: 
                   1442:     return undef;
                   1443: }
                   1444: 
1.298     matthew  1445: sub getsection {
                   1446:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1447:     my $cachetime=1800;
1.551     albertel 1448: 
                   1449:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1450:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1451:     if (defined($cached)) { return $result; }
                   1452: 
1.298     matthew  1453:     my %Pending; 
                   1454:     my %Expired;
                   1455:     #
                   1456:     # Each role can either have not started yet (pending), be active, 
                   1457:     #    or have expired.
                   1458:     #
                   1459:     # If there is an active role, we are done.
                   1460:     #
                   1461:     # If there is more than one role which has not started yet, 
                   1462:     #     choose the one which will start sooner
                   1463:     # If there is one role which has not started yet, return it.
                   1464:     #
                   1465:     # If there is more than one expired role, choose the one which ended last.
                   1466:     # If there is a role which has expired, return it.
                   1467:     #
1.815     albertel 1468:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1469:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1470:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1471:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1472:         my $section=$1;
                   1473:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1474:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1475:         my $now=time;
1.548     albertel 1476:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1477:             $Expired{$end}=$section;
                   1478:             next;
                   1479:         }
1.548     albertel 1480:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1481:             $Pending{$start}=$section;
                   1482:             next;
                   1483:         }
1.599     albertel 1484:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1485:     }
                   1486:     #
                   1487:     # Presumedly there will be few matching roles from the above
                   1488:     # loop and the sorting time will be negligible.
                   1489:     if (scalar(keys(%Pending))) {
                   1490:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1491:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1492:     } 
                   1493:     if (scalar(keys(%Expired))) {
                   1494:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1495:         my $time = pop(@sorted);
1.599     albertel 1496:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1497:     }
1.599     albertel 1498:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1499: }
1.70      www      1500: 
1.599     albertel 1501: sub save_cache {
                   1502:     &purge_remembered();
1.722     albertel 1503:     #&Apache::loncommon::validate_page();
1.620     albertel 1504:     undef(%env);
1.780     albertel 1505:     undef($env_loaded);
1.599     albertel 1506: }
1.452     albertel 1507: 
1.599     albertel 1508: my $to_remember=-1;
                   1509: my %remembered;
                   1510: my %accessed;
                   1511: my $kicks=0;
                   1512: my $hits=0;
1.849     albertel 1513: sub make_key {
                   1514:     my ($name,$id) = @_;
1.872     albertel 1515:     if (length($id) > 65 
                   1516: 	&& length(&escape($id)) > 200) {
                   1517: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1518:     }
1.849     albertel 1519:     return &escape($name.':'.$id);
                   1520: }
                   1521: 
1.599     albertel 1522: sub devalidate_cache_new {
                   1523:     my ($name,$id,$debug) = @_;
                   1524:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1525:     $id=&make_key($name,$id);
1.599     albertel 1526:     $memcache->delete($id);
                   1527:     delete($remembered{$id});
                   1528:     delete($accessed{$id});
                   1529: }
                   1530: 
                   1531: sub is_cached_new {
                   1532:     my ($name,$id,$debug) = @_;
1.849     albertel 1533:     $id=&make_key($name,$id);
1.599     albertel 1534:     if (exists($remembered{$id})) {
                   1535: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1536: 	$accessed{$id}=[&gettimeofday()];
                   1537: 	$hits++;
                   1538: 	return ($remembered{$id},1);
                   1539:     }
                   1540:     my $value = $memcache->get($id);
                   1541:     if (!(defined($value))) {
                   1542: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1543: 	return (undef,undef);
1.416     albertel 1544:     }
1.599     albertel 1545:     if ($value eq '__undef__') {
                   1546: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1547: 	$value=undef;
                   1548:     }
                   1549:     &make_room($id,$value,$debug);
                   1550:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1551:     return ($value,1);
                   1552: }
                   1553: 
                   1554: sub do_cache_new {
                   1555:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1556:     $id=&make_key($name,$id);
1.599     albertel 1557:     my $setvalue=$value;
                   1558:     if (!defined($setvalue)) {
                   1559: 	$setvalue='__undef__';
                   1560:     }
1.623     albertel 1561:     if (!defined($time) ) {
                   1562: 	$time=600;
                   1563:     }
1.599     albertel 1564:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1565:     my $result = $memcache->set($id,$setvalue,$time);
                   1566:     if (! $result) {
1.872     albertel 1567: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1568: 	$memcache->disconnect_all();
1.872     albertel 1569:     }
1.600     albertel 1570:     # need to make a copy of $value
1.919     albertel 1571:     &make_room($id,$value,$debug);
1.599     albertel 1572:     return $value;
                   1573: }
                   1574: 
                   1575: sub make_room {
                   1576:     my ($id,$value,$debug)=@_;
1.919     albertel 1577: 
                   1578:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1579:                                     : $value;
1.599     albertel 1580:     if ($to_remember<0) { return; }
                   1581:     $accessed{$id}=[&gettimeofday()];
                   1582:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1583:     my $to_kick;
                   1584:     my $max_time=0;
                   1585:     foreach my $other (keys(%accessed)) {
                   1586: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1587: 	    $to_kick=$other;
                   1588: 	    $max_time=&tv_interval($accessed{$other});
                   1589: 	}
                   1590:     }
                   1591:     delete($remembered{$to_kick});
                   1592:     delete($accessed{$to_kick});
                   1593:     $kicks++;
                   1594:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1595:     return;
                   1596: }
                   1597: 
1.599     albertel 1598: sub purge_remembered {
1.604     albertel 1599:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1600:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1601:     undef(%remembered);
                   1602:     undef(%accessed);
1.428     albertel 1603: }
1.70      www      1604: # ------------------------------------- Read an entry from a user's environment
                   1605: 
                   1606: sub userenvironment {
                   1607:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1608:     my $items;
                   1609:     foreach my $item (@what) {
                   1610:         $items.=&escape($item).'&';
                   1611:     }
                   1612:     $items=~s/\&$//;
1.70      www      1613:     my %returnhash=();
                   1614:     my @answer=split(/\&/,
1.976     raeburn  1615:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1616:                       &homeserver($unam,$udom)));
                   1617:     my $i;
                   1618:     for ($i=0;$i<=$#what;$i++) {
                   1619: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1620:     }
                   1621:     return %returnhash;
1.1       albertel 1622: }
                   1623: 
1.617     albertel 1624: # ---------------------------------------------------------- Get a studentphoto
                   1625: sub studentphoto {
                   1626:     my ($udom,$unam,$ext) = @_;
                   1627:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1628:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1629:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1630:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1631:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1632:             } else {
                   1633:                 my ($result,$perm_reqd)=
1.707     albertel 1634: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1635:                 if ($result eq 'ok') {
                   1636:                     if (!($perm_reqd eq 'yes')) {
                   1637:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1638:                     }
                   1639:                 }
                   1640:             }
                   1641:         }
                   1642:     } else {
                   1643:         my ($result,$perm_reqd) = 
1.707     albertel 1644: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1645:         if ($result eq 'ok') {
                   1646:             if (!($perm_reqd eq 'yes')) {
                   1647:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1648:             }
                   1649:         }
                   1650:     }
                   1651:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1652: }
                   1653: 
                   1654: sub retrievestudentphoto {
                   1655:     my ($udom,$unam,$ext,$type) = @_;
                   1656:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1657:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1658:     if ($ret eq 'ok') {
                   1659:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1660:         if ($type eq 'thumbnail') {
                   1661:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1662:         }
                   1663:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1664:         return $tokenurl;
                   1665:     } else {
                   1666:         if ($type eq 'thumbnail') {
                   1667:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1668:         } else { 
                   1669:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1670:         }
1.617     albertel 1671:     }
                   1672: }
                   1673: 
1.263     www      1674: # -------------------------------------------------------------------- New chat
                   1675: 
                   1676: sub chatsend {
1.724     raeburn  1677:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1678:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1679:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1680:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1681:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1682: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1683: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1684: }
                   1685: 
                   1686: # ------------------------------------------ Find current version of a resource
                   1687: 
                   1688: sub getversion {
                   1689:     my $fname=&clutter(shift);
                   1690:     unless ($fname=~/^\/res\//) { return -1; }
                   1691:     return &currentversion(&filelocation('',$fname));
                   1692: }
                   1693: 
                   1694: sub currentversion {
                   1695:     my $fname=shift;
1.599     albertel 1696:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1697:     if (defined($cached)) { return $result; }
1.292     www      1698:     my $author=$fname;
                   1699:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1700:     my ($udom,$uname)=split(/\//,$author);
                   1701:     my $home=homeserver($uname,$udom);
                   1702:     if ($home eq 'no_host') { 
                   1703:         return -1; 
                   1704:     }
                   1705:     my $answer=reply("currentversion:$fname",$home);
                   1706:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1707: 	return -1;
                   1708:     }
1.599     albertel 1709:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1710: }
                   1711: 
1.1       albertel 1712: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1713: 
1.1       albertel 1714: sub subscribe {
                   1715:     my $fname=shift;
1.761     raeburn  1716:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1717:     $fname=~s/[\n\r]//g;
1.1       albertel 1718:     my $author=$fname;
                   1719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1720:     my ($udom,$uname)=split(/\//,$author);
                   1721:     my $home=homeserver($uname,$udom);
1.335     albertel 1722:     if ($home eq 'no_host') {
                   1723:         return 'not_found';
1.1       albertel 1724:     }
                   1725:     my $answer=reply("sub:$fname",$home);
1.64      www      1726:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1727: 	$answer.=' by '.$home;
                   1728:     }
1.1       albertel 1729:     return $answer;
                   1730: }
                   1731:     
1.8       www      1732: # -------------------------------------------------------------- Replicate file
                   1733: 
                   1734: sub repcopy {
                   1735:     my $filename=shift;
1.23      www      1736:     $filename=~s/\/+/\//g;
1.607     raeburn  1737:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1738:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1739:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1740: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1741: 	return &repcopy_userfile($filename);
                   1742:     }
1.532     albertel 1743:     $filename=~s/[\n\r]//g;
1.8       www      1744:     my $transname="$filename.in.transfer";
1.828     www      1745: # FIXME: this should flock
1.607     raeburn  1746:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1747:     my $remoteurl=subscribe($filename);
1.64      www      1748:     if ($remoteurl =~ /^con_lost by/) {
                   1749: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1750:            return 'unavailable';
1.8       www      1751:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1752: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1753: 	   return 'not_found';
1.64      www      1754:     } elsif ($remoteurl =~ /^rejected by/) {
                   1755: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1756:            return 'forbidden';
1.20      www      1757:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1758:            return 'ok';
1.8       www      1759:     } else {
1.290     www      1760:         my $author=$filename;
                   1761:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1762:         my ($udom,$uname)=split(/\//,$author);
                   1763:         my $home=homeserver($uname,$udom);
                   1764:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1765:            my @parts=split(/\//,$filename);
                   1766:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1767:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1768:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1769: 	       return 'bad_request';
1.8       www      1770:            }
                   1771:            my $count;
                   1772:            for ($count=5;$count<$#parts;$count++) {
                   1773:                $path.="/$parts[$count]";
                   1774:                if ((-e $path)!=1) {
                   1775: 		   mkdir($path,0777);
                   1776:                }
                   1777:            }
                   1778:            my $ua=new LWP::UserAgent;
                   1779:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1780:            my $response=$ua->request($request,$transname);
                   1781:            if ($response->is_error()) {
                   1782: 	       unlink($transname);
                   1783:                my $message=$response->status_line;
1.672     albertel 1784:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1785:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1786:                return 'unavailable';
1.8       www      1787:            } else {
1.16      www      1788: 	       if ($remoteurl!~/\.meta$/) {
                   1789:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1790:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1791:                   if ($mresponse->is_error()) {
                   1792: 		      unlink($filename.'.meta');
                   1793:                       &logthis(
1.672     albertel 1794:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1795:                   }
                   1796: 	       }
1.8       www      1797:                rename($transname,$filename);
1.607     raeburn  1798:                return 'ok';
1.8       www      1799:            }
1.290     www      1800:        }
1.8       www      1801:     }
1.330     www      1802: }
                   1803: 
                   1804: # ------------------------------------------------ Get server side include body
                   1805: sub ssi_body {
1.381     albertel 1806:     my ($filelink,%form)=@_;
1.606     matthew  1807:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1808:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1809:     }
1.953     www      1810:     my $output='';
                   1811:     my $response;
1.976.4.1  raeburn  1812:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1813:        ($output,$response)=&externalssi($filelink);
1.953     www      1814:     } else {
                   1815:        ($output,$response)=&ssi($filelink,%form);
                   1816:     }
1.778     albertel 1817:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1818:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1819:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1820:     if (wantarray) {
                   1821:         return ($output, $response);
                   1822:     } else {
                   1823:         return $output;
                   1824:     }
1.8       www      1825: }
                   1826: 
1.15      www      1827: # --------------------------------------------------------- Server Side Include
                   1828: 
1.782     albertel 1829: sub absolute_url {
                   1830:     my ($host_name) = @_;
                   1831:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1832:     if ($host_name eq '') {
                   1833: 	$host_name = $ENV{'SERVER_NAME'};
                   1834:     }
                   1835:     return $protocol.$host_name;
                   1836: }
                   1837: 
1.942     foxr     1838: #
                   1839: #   Server side include.
                   1840: # Parameters:
                   1841: #  fn     Possibly encrypted resource name/id.
                   1842: #  form   Hash that describes how the rendering should be done
                   1843: #         and other things.
1.944     foxr     1844: # Returns:
1.950     raeburn  1845: #   Scalar context: The content of the response.
                   1846: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1847: #     
1.15      www      1848: sub ssi {
                   1849: 
1.944     foxr     1850:     my ($fn,%form)=@_;
1.15      www      1851:     my $ua=new LWP::UserAgent;
1.23      www      1852:     my $request;
1.711     albertel 1853: 
                   1854:     $form{'no_update_last_known'}=1;
1.895     albertel 1855:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1856:     if (%form) {
1.782     albertel 1857:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1858:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1859:     } else {
1.782     albertel 1860:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1861:     }
                   1862: 
1.15      www      1863:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1864:     my $response=$ua->request($request);
                   1865: 
1.944     foxr     1866:     if (wantarray) {
                   1867: 	return ($response->content, $response);
                   1868:     } else {
                   1869: 	return $response->content;
1.942     foxr     1870:     }
1.324     www      1871: }
                   1872: 
                   1873: sub externalssi {
                   1874:     my ($url)=@_;
                   1875:     my $ua=new LWP::UserAgent;
                   1876:     my $request=new HTTP::Request('GET',$url);
                   1877:     my $response=$ua->request($request);
1.954     raeburn  1878:     if (wantarray) {
                   1879:         return ($response->content, $response);
                   1880:     } else {
                   1881:         return $response->content;
                   1882:     }
1.15      www      1883: }
1.254     www      1884: 
1.492     albertel 1885: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1886: 
                   1887: sub allowuploaded {
                   1888:     my ($srcurl,$url)=@_;
                   1889:     $url=&clutter(&declutter($url));
                   1890:     my $dir=$url;
                   1891:     $dir=~s/\/[^\/]+$//;
                   1892:     my %httpref=();
                   1893:     my $httpurl=&hreflocation('',$url);
                   1894:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1895:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1896: }
1.477     raeburn  1897: 
1.478     albertel 1898: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1899: # input: action, courseID, current domain, intended
1.637     raeburn  1900: #        path to file, source of file, instruction to parse file for objects,
                   1901: #        ref to hash for embedded objects,
                   1902: #        ref to hash for codebase of java objects.
                   1903: #
1.485     raeburn  1904: # output: url to file (if action was uploaddoc), 
                   1905: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1906: #
1.478     albertel 1907: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1908: # course.
1.477     raeburn  1909: #
1.478     albertel 1910: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1911: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1912: #          course's home server.
1.477     raeburn  1913: #
1.478     albertel 1914: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1915: #          be copied from $source (current location) to 
                   1916: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1917: #         and will then be copied to
                   1918: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1919: #         course's home server.
1.485     raeburn  1920: #
1.481     raeburn  1921: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1922: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1923: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1924: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1925: #         in course's home server.
1.637     raeburn  1926: #
1.477     raeburn  1927: 
                   1928: sub process_coursefile {
1.638     albertel 1929:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1930:     my $fetchresult;
1.638     albertel 1931:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1932:     if ($action eq 'propagate') {
1.638     albertel 1933:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1934: 			     $home);
1.481     raeburn  1935:     } else {
1.477     raeburn  1936:         my $fpath = '';
                   1937:         my $fname = $file;
1.478     albertel 1938:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1939:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1940:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1941:         if ($action eq 'copy') {
                   1942:             if ($source eq '') {
                   1943:                 $fetchresult = 'no source file';
                   1944:                 return $fetchresult;
                   1945:             } else {
                   1946:                 my $destination = $filepath.'/'.$fname;
                   1947:                 rename($source,$destination);
                   1948:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1949:                                  $home);
1.481     raeburn  1950:             }
                   1951:         } elsif ($action eq 'uploaddoc') {
                   1952:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1953:             print $fh $env{'form.'.$source};
1.481     raeburn  1954:             close($fh);
1.637     raeburn  1955:             if ($parser eq 'parse') {
1.961     raeburn  1956:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1957:                 unless ($parse_result eq 'ok') {
                   1958:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1959:                 }
                   1960:             }
1.477     raeburn  1961:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1962:                                  $home);
1.481     raeburn  1963:             if ($fetchresult eq 'ok') {
                   1964:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1965:             } else {
                   1966:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1967:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1968:                 return '/adm/notfound.html';
                   1969:             }
1.477     raeburn  1970:         }
                   1971:     }
1.485     raeburn  1972:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1973:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1974:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1975:     }
                   1976:     return $fetchresult;
                   1977: }
                   1978: 
1.637     raeburn  1979: sub build_filepath {
                   1980:     my ($fpath) = @_;
                   1981:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1982:     unless ($fpath eq '') {
                   1983:         my @parts=split('/',$fpath);
                   1984:         foreach my $part (@parts) {
                   1985:             $filepath.= '/'.$part;
                   1986:             if ((-e $filepath)!=1) {
                   1987:                 mkdir($filepath,0777);
                   1988:             }
                   1989:         }
                   1990:     }
                   1991:     return $filepath;
                   1992: }
                   1993: 
                   1994: sub store_edited_file {
1.638     albertel 1995:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1996:     my $file = $primary_url;
                   1997:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1998:     my $fpath = '';
                   1999:     my $fname = $file;
                   2000:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2001:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2002:     my $filepath = &build_filepath($fpath);
                   2003:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2004:     print $fh $content;
                   2005:     close($fh);
1.638     albertel 2006:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2007:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2008: 			  $home);
1.637     raeburn  2009:     if ($$fetchresult eq 'ok') {
                   2010:         return '/uploaded/'.$fpath.'/'.$fname;
                   2011:     } else {
1.638     albertel 2012:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2013: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2014:         return '/adm/notfound.html';
                   2015:     }
                   2016: }
                   2017: 
1.531     albertel 2018: sub clean_filename {
1.831     albertel 2019:     my ($fname,$args)=@_;
1.315     www      2020: # Replace Windows backslashes by forward slashes
1.257     www      2021:     $fname=~s/\\/\//g;
1.831     albertel 2022:     if (!$args->{'keep_path'}) {
                   2023:         # Get rid of everything but the actual filename
                   2024: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2025:     }
1.315     www      2026: # Replace spaces by underscores
                   2027:     $fname=~s/\s+/\_/g;
                   2028: # Replace all other weird characters by nothing
1.831     albertel 2029:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2030: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2031: # numbers
                   2032:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2033:     return $fname;
                   2034: }
                   2035: 
1.608     albertel 2036: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2037: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2038: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2039: #        $coursedoc - if true up to the current course
                   2040: #                     if false
                   2041: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2042: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2043: #        $allfiles - reference to hash for embedded objects
                   2044: #        $codebase - reference to hash for codebase of java objects
                   2045: #        $desuname - username for permanent storage of uploaded file
                   2046: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2047: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2048: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2049: # 
1.686     albertel 2050: # output: url of file in userspace, or error: <message> 
                   2051: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2052: 
                   2053: 
1.531     albertel 2054: sub userfileupload {
1.860     raeburn  2055:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2056:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2057:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2058:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2059:     $fname=&clean_filename($fname);
1.315     www      2060: # See if there is anything left
1.257     www      2061:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2062:     chop($env{'form.'.$formname});
1.523     raeburn  2063:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2064:         my $now = time;
                   2065:         my $filepath = 'tmp/helprequests/'.$now;
                   2066:         my @parts=split(/\//,$filepath);
                   2067:         my $fullpath = $perlvar{'lonDaemons'};
                   2068:         for (my $i=0;$i<@parts;$i++) {
                   2069:             $fullpath .= '/'.$parts[$i];
                   2070:             if ((-e $fullpath)!=1) {
                   2071:                 mkdir($fullpath,0777);
                   2072:             }
                   2073:         }
                   2074:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2075:         print $fh $env{'form.'.$formname};
1.523     raeburn  2076:         close($fh);
1.741     raeburn  2077:         return $fullpath.'/'.$fname;
                   2078:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2079:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2080:                        '_'.$env{'user.domain'}.'/pending';
                   2081:         my @parts=split(/\//,$filepath);
                   2082:         my $fullpath = $perlvar{'lonDaemons'};
                   2083:         for (my $i=0;$i<@parts;$i++) {
                   2084:             $fullpath .= '/'.$parts[$i];
                   2085:             if ((-e $fullpath)!=1) {
                   2086:                 mkdir($fullpath,0777);
                   2087:             }
                   2088:         }
                   2089:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2090:         print $fh $env{'form.'.$formname};
                   2091:         close($fh);
                   2092:         return $fullpath.'/'.$fname;
1.523     raeburn  2093:     }
1.719     banghart 2094:     
1.258     www      2095: # Create the directory if not present
1.493     albertel 2096:     $fname="$subdir/$fname";
1.259     www      2097:     if ($coursedoc) {
1.638     albertel 2098: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2099: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2100:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2101:             return &finishuserfileupload($docuname,$docudom,
                   2102: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2103: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2104:         } else {
1.620     albertel 2105:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2106:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2107: 				       $fname,$formname,$parser,
                   2108: 				       $allfiles,$codebase);
1.481     raeburn  2109:         }
1.719     banghart 2110:     } elsif (defined($destuname)) {
                   2111:         my $docuname=$destuname;
                   2112:         my $docudom=$destudom;
1.860     raeburn  2113: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2114: 				     $parser,$allfiles,$codebase,
                   2115:                                      $thumbwidth,$thumbheight);
1.719     banghart 2116:         
1.259     www      2117:     } else {
1.638     albertel 2118:         my $docuname=$env{'user.name'};
                   2119:         my $docudom=$env{'user.domain'};
1.714     raeburn  2120:         if (exists($env{'form.group'})) {
                   2121:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2122:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2123:         }
1.860     raeburn  2124: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2125: 				     $parser,$allfiles,$codebase,
                   2126:                                      $thumbwidth,$thumbheight);
1.259     www      2127:     }
1.271     www      2128: }
                   2129: 
                   2130: sub finishuserfileupload {
1.860     raeburn  2131:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2132:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2133:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2134:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2135:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2136:     $file=$fname;
                   2137:     if ($fname=~m|/|) {
                   2138:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2139: 	$path.=$fnamepath.'/';
                   2140:     }
1.259     www      2141:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2142:     my $count;
                   2143:     for ($count=4;$count<=$#parts;$count++) {
                   2144:         $filepath.="/$parts[$count]";
                   2145:         if ((-e $filepath)!=1) {
                   2146: 	    mkdir($filepath,0777);
                   2147:         }
                   2148:     }
                   2149: # Save the file
                   2150:     {
1.701     albertel 2151: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2152: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2153: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2154: 	    return '/adm/notfound.html';
                   2155: 	}
                   2156: 	if (!print FH ($env{'form.'.$formname})) {
                   2157: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2158: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2159: 	    return '/adm/notfound.html';
                   2160: 	}
1.570     albertel 2161: 	close(FH);
1.258     www      2162:     }
1.637     raeburn  2163:     if ($parser eq 'parse') {
1.961     raeburn  2164:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2165: 						   $codebase);
1.637     raeburn  2166:         unless ($parse_result eq 'ok') {
1.638     albertel 2167:             &logthis('Failed to parse '.$filepath.$file.
                   2168: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2169:         }
                   2170:     }
1.860     raeburn  2171:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2172:         my $input = $filepath.'/'.$file;
                   2173:         my $output = $filepath.'/'.'tn-'.$file;
                   2174:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2175:         system("convert -sample $thumbsize $input $output");
                   2176:         if (-e $filepath.'/'.'tn-'.$file) {
                   2177:             $fetchthumb  = 1; 
                   2178:         }
                   2179:     }
1.858     raeburn  2180:  
1.259     www      2181: # Notify homeserver to grep it
                   2182: #
1.638     albertel 2183:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2184:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2185:     if ($fetchresult eq 'ok') {
1.860     raeburn  2186:         if ($fetchthumb) {
                   2187:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2188:             if ($thumbresult ne 'ok') {
                   2189:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2190:                          $docuhome.': '.$thumbresult);
                   2191:             }
                   2192:         }
1.259     www      2193: #
1.258     www      2194: # Return the URL to it
1.494     albertel 2195:         return '/uploaded/'.$path.$file;
1.263     www      2196:     } else {
1.494     albertel 2197:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2198: 		 ': '.$fetchresult);
1.263     www      2199:         return '/adm/notfound.html';
1.858     raeburn  2200:     }
1.493     albertel 2201: }
                   2202: 
1.637     raeburn  2203: sub extract_embedded_items {
1.961     raeburn  2204:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2205:     my @state = ();
                   2206:     my %javafiles = (
                   2207:                       codebase => '',
                   2208:                       code => '',
                   2209:                       archive => ''
                   2210:                     );
                   2211:     my %mediafiles = (
                   2212:                       src => '',
                   2213:                       movie => '',
                   2214:                      );
1.648     raeburn  2215:     my $p;
                   2216:     if ($content) {
                   2217:         $p = HTML::LCParser->new($content);
                   2218:     } else {
1.961     raeburn  2219:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2220:     }
1.641     albertel 2221:     while (my $t=$p->get_token()) {
1.640     albertel 2222: 	if ($t->[0] eq 'S') {
                   2223: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2224: 	    push(@state, $tagname);
1.648     raeburn  2225:             if (lc($tagname) eq 'allow') {
                   2226:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2227:             }
1.640     albertel 2228: 	    if (lc($tagname) eq 'img') {
                   2229: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2230: 	    }
1.886     albertel 2231: 	    if (lc($tagname) eq 'a') {
                   2232: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2233: 	    }
1.645     raeburn  2234:             if (lc($tagname) eq 'script') {
                   2235:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2236:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2237:                 } else {
                   2238:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2239:                 }
                   2240:             }
                   2241:             if (lc($tagname) eq 'link') {
                   2242:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2243:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2244:                 }
                   2245:             }
1.640     albertel 2246: 	    if (lc($tagname) eq 'object' ||
                   2247: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2248: 		foreach my $item (keys(%javafiles)) {
                   2249: 		    $javafiles{$item} = '';
                   2250: 		}
                   2251: 	    }
                   2252: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2253: 		my $name = lc($attr->{'name'});
                   2254: 		foreach my $item (keys(%javafiles)) {
                   2255: 		    if ($name eq $item) {
                   2256: 			$javafiles{$item} = $attr->{'value'};
                   2257: 			last;
                   2258: 		    }
                   2259: 		}
                   2260: 		foreach my $item (keys(%mediafiles)) {
                   2261: 		    if ($name eq $item) {
                   2262: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2263: 			last;
                   2264: 		    }
                   2265: 		}
                   2266: 	    }
                   2267: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2268: 		foreach my $item (keys(%javafiles)) {
                   2269: 		    if ($attr->{$item}) {
                   2270: 			$javafiles{$item} = $attr->{$item};
                   2271: 			last;
                   2272: 		    }
                   2273: 		}
                   2274: 		foreach my $item (keys(%mediafiles)) {
                   2275: 		    if ($attr->{$item}) {
                   2276: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2277: 			last;
                   2278: 		    }
                   2279: 		}
                   2280: 	    }
                   2281: 	} elsif ($t->[0] eq 'E') {
                   2282: 	    my ($tagname) = ($t->[1]);
                   2283: 	    if ($javafiles{'codebase'} ne '') {
                   2284: 		$javafiles{'codebase'} .= '/';
                   2285: 	    }  
                   2286: 	    if (lc($tagname) eq 'applet' ||
                   2287: 		lc($tagname) eq 'object' ||
                   2288: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2289: 		) {
                   2290: 		foreach my $item (keys(%javafiles)) {
                   2291: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2292: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2293: 			&add_filetype($allfiles,$file,$item);
                   2294: 		    }
                   2295: 		}
                   2296: 	    } 
                   2297: 	    pop @state;
                   2298: 	}
                   2299:     }
1.637     raeburn  2300:     return 'ok';
                   2301: }
                   2302: 
1.639     albertel 2303: sub add_filetype {
                   2304:     my ($allfiles,$file,$type)=@_;
                   2305:     if (exists($allfiles->{$file})) {
                   2306: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2307: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2308: 	}
                   2309:     } else {
                   2310: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2311:     }
                   2312: }
                   2313: 
1.493     albertel 2314: sub removeuploadedurl {
                   2315:     my ($url)=@_;
                   2316:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2317:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2318: }
                   2319: 
                   2320: sub removeuserfile {
                   2321:     my ($docuname,$docudom,$fname)=@_;
                   2322:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2323:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2324:     if ($result eq 'ok') {
                   2325:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2326:             my $metafile = $fname.'.meta';
                   2327:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2328: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2329:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2330:             my $sqlresult = 
1.823     albertel 2331:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2332:                                         'portfolio_metadata',$group,
                   2333:                                         'delete');
1.798     raeburn  2334:         }
                   2335:     }
                   2336:     return $result;
1.257     www      2337: }
1.15      www      2338: 
1.530     albertel 2339: sub mkdiruserfile {
                   2340:     my ($docuname,$docudom,$dir)=@_;
                   2341:     my $home=&homeserver($docuname,$docudom);
                   2342:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2343: }
                   2344: 
1.531     albertel 2345: sub renameuserfile {
                   2346:     my ($docuname,$docudom,$old,$new)=@_;
                   2347:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2348:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2349:                         &escape("$old").':'.&escape("$new"),$home);
                   2350:     if ($result eq 'ok') {
                   2351:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2352:             my $oldmeta = $old.'.meta';
                   2353:             my $newmeta = $new.'.meta';
                   2354:             my $metaresult = 
                   2355:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2356: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2357:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2358:             my $sqlresult = 
1.823     albertel 2359:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2360:                                         'portfolio_metadata',$group,
                   2361:                                         'delete');
1.798     raeburn  2362:         }
                   2363:     }
                   2364:     return $result;
1.531     albertel 2365: }
                   2366: 
1.14      www      2367: # ------------------------------------------------------------------------- Log
                   2368: 
                   2369: sub log {
                   2370:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2371:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2372: }
                   2373: 
                   2374: # ------------------------------------------------------------------ Course Log
1.352     www      2375: #
                   2376: # This routine flushes several buffers of non-mission-critical nature
                   2377: #
1.157     www      2378: 
                   2379: sub flushcourselogs {
1.352     www      2380:     &logthis('Flushing log buffers');
                   2381: #
                   2382: # course logs
                   2383: # This is a log of all transactions in a course, which can be used
                   2384: # for data mining purposes
                   2385: #
                   2386: # It also collects the courseid database, which lists last transaction
                   2387: # times and course titles for all courseids
                   2388: #
                   2389:     my %courseidbuffer=();
1.921     raeburn  2390:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2391:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2392: 		          &escape($courselogs{$crsid}),
                   2393: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2394: 	    delete $courselogs{$crsid};
                   2395:         } else {
                   2396:             &logthis('Failed to flush log buffer for '.$crsid);
                   2397:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2398:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2399:                         " exceeded maximum size, deleting.</font>");
                   2400:                delete $courselogs{$crsid};
                   2401:             }
1.352     www      2402:         }
1.920     raeburn  2403:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2404:             'description' => $coursedescrbuf{$crsid},
                   2405:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2406:             'type'        => $coursetypebuf{$crsid},
                   2407:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2408:         };
1.191     harris41 2409:     }
1.352     www      2410: #
                   2411: # Write course id database (reverse lookup) to homeserver of courses 
                   2412: # Is used in pickcourse
                   2413: #
1.840     albertel 2414:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2415:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2416:                                     $courseidbuffer{$crs_home},
                   2417:                                     $crs_home,'timeonly');
1.352     www      2418:     }
                   2419: #
                   2420: # File accesses
                   2421: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2422: #
1.449     matthew  2423:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2424:         if ($entry =~ /___count$/) {
                   2425:             my ($dom,$name);
1.807     albertel 2426:             ($dom,$name,undef)=
1.811     albertel 2427: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2428:             if (! defined($dom) || $dom eq '' || 
                   2429:                 ! defined($name) || $name eq '') {
1.620     albertel 2430:                 my $cid = $env{'request.course.id'};
                   2431:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2432:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2433:             }
1.450     matthew  2434:             my $value = $accesshash{$entry};
                   2435:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2436:             my %temphash=($url => $value);
1.449     matthew  2437:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2438:             if ($result eq 'ok') {
                   2439:                 delete $accesshash{$entry};
                   2440:             } elsif ($result eq 'unknown_cmd') {
                   2441:                 # Target server has old code running on it.
1.450     matthew  2442:                 my %temphash=($entry => $value);
1.449     matthew  2443:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2444:                     delete $accesshash{$entry};
                   2445:                 }
                   2446:             }
                   2447:         } else {
1.811     albertel 2448:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2449:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2450:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2451:                 delete $accesshash{$entry};
                   2452:             }
1.185     www      2453:         }
1.191     harris41 2454:     }
1.352     www      2455: #
                   2456: # Roles
                   2457: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2458: #
1.800     albertel 2459:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2460:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2461: 	    split(/\:/,$entry);
                   2462:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2463:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2464:                 $rudom,$runame) eq 'ok') {
                   2465: 	    delete $userrolehash{$entry};
                   2466:         }
                   2467:     }
1.662     raeburn  2468: #
                   2469: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2470: #
                   2471:     my %domrolebuffer = ();
                   2472:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2473:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2474:         if ($domrolebuffer{$rudom}) {
                   2475:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2476:                       '='.&escape($domainrolehash{$entry});
                   2477:         } else {
                   2478:             $domrolebuffer{$rudom}.=&escape($entry).
                   2479:                       '='.&escape($domainrolehash{$entry});
                   2480:         }
                   2481:         delete $domainrolehash{$entry};
                   2482:     }
                   2483:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2484: 	my %servers = &get_servers($dom,'library');
                   2485: 	foreach my $tryserver (keys(%servers)) {
                   2486: 	    unless (&reply('domroleput:'.$dom.':'.
                   2487: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2488: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2489: 	    }
1.662     raeburn  2490:         }
                   2491:     }
1.186     www      2492:     $dumpcount++;
1.157     www      2493: }
                   2494: 
                   2495: sub courselog {
                   2496:     my $what=shift;
1.158     www      2497:     $what=time.':'.$what;
1.620     albertel 2498:     unless ($env{'request.course.id'}) { return ''; }
                   2499:     $coursedombuf{$env{'request.course.id'}}=
                   2500:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2501:     $coursenumbuf{$env{'request.course.id'}}=
                   2502:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2503:     $coursehombuf{$env{'request.course.id'}}=
                   2504:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2505:     $coursedescrbuf{$env{'request.course.id'}}=
                   2506:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2507:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2508:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2509:     $courseownerbuf{$env{'request.course.id'}}=
                   2510:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2511:     $coursetypebuf{$env{'request.course.id'}}=
                   2512:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2513:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2514: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2515:     } else {
1.620     albertel 2516: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2517:     }
1.620     albertel 2518:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2519: 	&flushcourselogs();
                   2520:     }
1.158     www      2521: }
                   2522: 
                   2523: sub courseacclog {
                   2524:     my $fnsymb=shift;
1.620     albertel 2525:     unless ($env{'request.course.id'}) { return ''; }
                   2526:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2527:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2528:         $what.=':POST';
1.583     matthew  2529:         # FIXME: Probably ought to escape things....
1.800     albertel 2530: 	foreach my $key (keys(%env)) {
                   2531:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2532:                 my $formitem = $1;
                   2533:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2534:                     $what.=':'.$formitem.'='.$env{$key};
                   2535:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2536:                     $what.=':'.$formitem.'='.$env{$key};
                   2537:                 }
1.158     www      2538:             }
1.191     harris41 2539:         }
1.583     matthew  2540:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2541:         # FIXME: We should not be depending on a form parameter that someone
                   2542:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2543:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2544:             $what.= ':POST';
                   2545:             # FIXME: Probably ought to escape things....
                   2546:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2547:                                  'crsdiscuss') {
1.620     albertel 2548:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2549:             }
                   2550:         }
1.158     www      2551:     }
                   2552:     &courselog($what);
1.149     www      2553: }
                   2554: 
1.185     www      2555: sub countacc {
                   2556:     my $url=&declutter(shift);
1.458     matthew  2557:     return if (! defined($url) || $url eq '');
1.620     albertel 2558:     unless ($env{'request.course.id'}) { return ''; }
                   2559:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2560:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2561:     $accesshash{$key}++;
1.185     www      2562: }
1.349     www      2563: 
1.361     www      2564: sub linklog {
                   2565:     my ($from,$to)=@_;
                   2566:     $from=&declutter($from);
                   2567:     $to=&declutter($to);
                   2568:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2569:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2570: }
                   2571:   
1.349     www      2572: sub userrolelog {
                   2573:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2574:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2575:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2576:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2577:         ($trole=~/^ta/)) {
1.350     www      2578:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2579:        $userrolehash
                   2580:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2581:                     =$tend.':'.$tstart;
1.662     raeburn  2582:     }
1.898     albertel 2583:     if (($env{'request.role'} =~ /dc\./) &&
                   2584: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2585: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2586: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2587:        $userrolehash
                   2588:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2589:                     =$tend.':'.$tstart;
                   2590:     }
1.662     raeburn  2591:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2592:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2593:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2594:         ($trole=~/^sc/)) {
                   2595:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2596:        $domainrolehash
                   2597:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2598:                     = $tend.':'.$tstart;
                   2599:     }
1.351     www      2600: }
                   2601: 
1.957     raeburn  2602: sub courserolelog {
                   2603:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2604:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2605:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2606:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2607:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2608:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2609:             my $cdom = $1;
                   2610:             my $cnum = $2;
                   2611:             my $sec = $3;
                   2612:             my $namespace = 'rolelog';
                   2613:             my %storehash = (
                   2614:                                role    => $trole,
                   2615:                                start   => $tstart,
                   2616:                                end     => $tend,
                   2617:                                selfenroll => $selfenroll,
                   2618:                                context    => $context,
                   2619:                             );
                   2620:             if ($trole eq 'gr') {
                   2621:                 $namespace = 'groupslog';
                   2622:                 $storehash{'group'} = $sec;
                   2623:             } else {
                   2624:                 $storehash{'section'} = $sec;
                   2625:             }
                   2626:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.976.4.1  raeburn  2627:             if (($trole ne 'st') || ($sec ne '')) {
                   2628:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2629:             }
1.957     raeburn  2630:         }
                   2631:     }
                   2632:     return;
                   2633: }
                   2634: 
1.351     www      2635: sub get_course_adv_roles {
1.948     raeburn  2636:     my ($cid,$codes) = @_;
1.620     albertel 2637:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2638:     my %coursehash=&coursedescription($cid);
1.976.4.2! raeburn  2639:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2640:     my %nothide=();
1.800     albertel 2641:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2642:         if ($user !~ /:/) {
                   2643: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2644:         } else {
                   2645:             $nothide{$user}=1;
                   2646:         }
1.470     www      2647:     }
1.351     www      2648:     my %returnhash=();
                   2649:     my %dumphash=
                   2650:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2651:     my $now=time;
1.976.4.1  raeburn  2652:     my %privileged;
1.800     albertel 2653:     foreach my $entry (keys %dumphash) {
                   2654: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2655:         if (($tstart) && ($tstart<0)) { next; }
                   2656:         if (($tend) && ($tend<$now)) { next; }
                   2657:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2658:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2659: 	if ($username eq '' || $domain eq '') { next; }
1.976.4.1  raeburn  2660:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2661:             my %dompersonnel =
                   2662:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2663:             $privileged{$domain} = {};
                   2664:             foreach my $server (keys(%dompersonnel)) {
                   2665:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   2666:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2667:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2668:                         $privileged{$udom}{$uname} = 1;
                   2669:                     }
                   2670:                 }
                   2671:             }
                   2672:         }
                   2673:         if ((exists($privileged{$domain}{$username})) &&
                   2674:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2675: 	if ($role eq 'cr') { next; }
1.948     raeburn  2676:         if ($codes) {
                   2677:             if ($section) { $role .= ':'.$section; }
                   2678:             if ($returnhash{$role}) {
                   2679:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2680:             } else {
                   2681:                 $returnhash{$role}=$username.':'.$domain;
                   2682:             }
1.351     www      2683:         } else {
1.976.4.2! raeburn  2684:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2685:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2686:             if ($returnhash{$key}) {
                   2687: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2688:             } else {
                   2689:                 $returnhash{$key}=$username.':'.$domain;
                   2690:             }
1.351     www      2691:         }
1.948     raeburn  2692:     }
1.400     www      2693:     return %returnhash;
                   2694: }
                   2695: 
                   2696: sub get_my_roles {
1.937     raeburn  2697:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2698:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2699:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2700:     my (%dumphash,%nothide);
1.858     raeburn  2701:     if ($context eq 'userroles') { 
                   2702:         %dumphash = &dump('roles',$udom,$uname);
                   2703:     } else {
                   2704:         %dumphash=
1.400     www      2705:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2706:         if ($hidepriv) {
                   2707:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2708:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2709:                 if ($user !~ /:/) {
                   2710:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2711:                 } else {
                   2712:                     $nothide{$user} = 1;
                   2713:                 }
                   2714:             }
                   2715:         }
1.858     raeburn  2716:     }
1.400     www      2717:     my %returnhash=();
                   2718:     my $now=time;
1.976.4.1  raeburn  2719:     my %privileged;
1.800     albertel 2720:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2721:         my ($role,$tend,$tstart);
                   2722:         if ($context eq 'userroles') {
                   2723: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2724:         } else {
                   2725:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2726:         }
1.400     www      2727:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2728:         my $status = 'active';
1.939     raeburn  2729:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2730:             $status = 'previous';
                   2731:         } 
                   2732:         if (($tstart) && ($now<$tstart)) {
                   2733:             $status = 'future';
                   2734:         }
                   2735:         if (ref($types) eq 'ARRAY') {
                   2736:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2737:                 next;
                   2738:             } 
                   2739:         } else {
                   2740:             if ($status ne 'active') {
                   2741:                 next;
                   2742:             }
                   2743:         }
1.867     raeburn  2744:         my ($rolecode,$username,$domain,$section,$area);
                   2745:         if ($context eq 'userroles') {
                   2746:             ($area,$rolecode) = split(/_/,$entry);
                   2747:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2748:         } else {
                   2749:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2750:         }
1.832     raeburn  2751:         if (ref($roledoms) eq 'ARRAY') {
                   2752:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2753:                 next;
                   2754:             }
                   2755:         }
                   2756:         if (ref($roles) eq 'ARRAY') {
                   2757:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2758:                 if ($role =~ /^cr\//) {
                   2759:                     if (!grep(/^cr$/,@{$roles})) {
                   2760:                         next;
                   2761:                     }
                   2762:                 } else {
                   2763:                     next;
                   2764:                 }
1.832     raeburn  2765:             }
1.867     raeburn  2766:         }
1.937     raeburn  2767:         if ($hidepriv) {
1.976.4.1  raeburn  2768:             if ($context eq 'userroles') {
                   2769:                 if ((&privileged($username,$domain)) &&
                   2770:                     (!$nothide{$username.':'.$domain})) {
                   2771:                     next;
                   2772:                 }
                   2773:             } else {
                   2774:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2775:                     my %dompersonnel =
                   2776:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2777:                     $privileged{$domain} = {};
                   2778:                     if (keys(%dompersonnel)) {
                   2779:                         foreach my $server (keys(%dompersonnel)) {
                   2780:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2781:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2782:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2783:                                     $privileged{$udom}{$uname} = $trole;
                   2784:                                 }
                   2785:                             }
                   2786:                         }
                   2787:                     }
                   2788:                 }
                   2789:                 if (exists($privileged{$domain}{$username})) {
                   2790:                     if (!$nothide{$username.':'.$domain}) {
                   2791:                         next;
                   2792:                     }
                   2793:                 }
1.937     raeburn  2794:             }
                   2795:         }
1.933     raeburn  2796:         if ($withsec) {
                   2797:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2798:                 $tstart.':'.$tend;
                   2799:         } else {
                   2800:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2801:         }
1.832     raeburn  2802:     }
1.373     www      2803:     return %returnhash;
1.399     www      2804: }
                   2805: 
                   2806: # ----------------------------------------------------- Frontpage Announcements
                   2807: #
                   2808: #
                   2809: 
                   2810: sub postannounce {
                   2811:     my ($server,$text)=@_;
1.844     albertel 2812:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2813:     unless ($text=~/\w/) { $text=''; }
                   2814:     return &reply('setannounce:'.&escape($text),$server);
                   2815: }
                   2816: 
                   2817: sub getannounce {
1.448     albertel 2818: 
                   2819:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2820: 	my $announcement='';
1.800     albertel 2821: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2822: 	close($fh);
1.399     www      2823: 	if ($announcement=~/\w/) { 
                   2824: 	    return 
                   2825:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2826:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2827: 	} else {
                   2828: 	    return '';
                   2829: 	}
                   2830:     } else {
                   2831: 	return '';
                   2832:     }
1.351     www      2833: }
1.353     www      2834: 
                   2835: # ---------------------------------------------------------- Course ID routines
                   2836: # Deal with domain's nohist_courseid.db files
                   2837: #
                   2838: 
                   2839: sub courseidput {
1.921     raeburn  2840:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2841:     my $outcome;
                   2842:     if ($caller eq 'timeonly') {
                   2843:         my $cids = '';
                   2844:         foreach my $item (keys(%$storehash)) {
                   2845:             $cids.=&escape($item).'&';
                   2846:         }
                   2847:         $cids=~s/\&$//;
                   2848:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2849:                           $coursehome);       
                   2850:     } else {
                   2851:         my $items = '';
                   2852:         foreach my $item (keys(%$storehash)) {
                   2853:             $items.= &escape($item).'='.
                   2854:                      &freeze_escape($$storehash{$item}).'&';
                   2855:         }
                   2856:         $items=~s/\&$//;
                   2857:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2858:                           $coursehome);
1.918     raeburn  2859:     }
                   2860:     if ($outcome eq 'unknown_cmd') {
                   2861:         my $what;
                   2862:         foreach my $cid (keys(%$storehash)) {
                   2863:             $what .= &escape($cid).'=';
1.921     raeburn  2864:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2865:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2866:             }
                   2867:             $what =~ s/\:$/&/;
                   2868:         }
                   2869:         $what =~ s/\&$//;  
                   2870:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2871:     } else {
                   2872:         return $outcome;
                   2873:     }
1.353     www      2874: }
                   2875: 
                   2876: sub courseiddump {
1.921     raeburn  2877:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2878:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2879:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2880:     my $as_hash = 1;
                   2881:     my %returnhash;
                   2882:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2883:     my %libserv = &all_library();
                   2884:     foreach my $tryserver (keys(%libserv)) {
                   2885:         if ( (  $hostidflag == 1 
                   2886: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2887: 	     || (!defined($hostidflag)) ) {
                   2888: 
1.918     raeburn  2889: 	    if (($domfilter eq '') ||
                   2890: 		(&host_domain($tryserver) eq $domfilter)) {
                   2891:                 my $rep = 
                   2892:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2893:                          $sincefilter.':'.&escape($descfilter).':'.
                   2894:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2895:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2896:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2897:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2898:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2899:                 my @pairs=split(/\&/,$rep);
                   2900:                 foreach my $item (@pairs) {
                   2901:                     my ($key,$value)=split(/\=/,$item,2);
                   2902:                     $key = &unescape($key);
                   2903:                     next if ($key =~ /^error: 2 /);
                   2904:                     my $result = &thaw_unescape($value);
                   2905:                     if (ref($result) eq 'HASH') {
                   2906:                         $returnhash{$key}=$result;
                   2907:                     } else {
1.921     raeburn  2908:                         my @responses = split(/:/,$value);
                   2909:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2910:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2911:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2912:                         }
                   2913:                     } 
1.353     www      2914:                 }
                   2915:             }
                   2916:         }
                   2917:     }
                   2918:     return %returnhash;
                   2919: }
                   2920: 
1.658     raeburn  2921: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2922: 
                   2923: sub dcmailput {
1.685     raeburn  2924:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2925:     my $status = &Apache::lonnet::critical(
1.740     www      2926:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2927:        &escape($message),$server);
1.662     raeburn  2928:     return $status;
                   2929: }
                   2930: 
1.658     raeburn  2931: sub dcmaildump {
                   2932:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2933:     my %returnhash=();
1.846     albertel 2934: 
                   2935:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2936:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2937:                                                          &escape($enddate).':';
                   2938: 	my @esc_senders=map { &escape($_)} @$senders;
                   2939: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2940: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2941:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2942:             if (($key) && ($value)) {
                   2943:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2944:             }
                   2945:         }
                   2946:     }
                   2947:     return %returnhash;
                   2948: }
1.662     raeburn  2949: # ---------------------------------------------------------- Domain roles
                   2950: 
                   2951: sub get_domain_roles {
                   2952:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2953:     if (undef($startdate) || $startdate eq '') {
                   2954:         $startdate = '.';
                   2955:     }
                   2956:     if (undef($enddate) || $enddate eq '') {
                   2957:         $enddate = '.';
                   2958:     }
1.922     raeburn  2959:     my $rolelist;
                   2960:     if (ref($roles) eq 'ARRAY') {
                   2961:         $rolelist = join(':',@{$roles});
                   2962:     }
1.662     raeburn  2963:     my %personnel = ();
1.841     albertel 2964: 
                   2965:     my %servers = &get_servers($dom,'library');
                   2966:     foreach my $tryserver (keys(%servers)) {
                   2967: 	%{$personnel{$tryserver}}=();
                   2968: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2969: 					    &escape($startdate).':'.
                   2970: 					    &escape($enddate).':'.
                   2971: 					    &escape($rolelist), $tryserver))) {
                   2972: 	    my ($key,$value) = split(/\=/,$line,2);
                   2973: 	    if (($key) && ($value)) {
                   2974: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2975: 	    }
                   2976: 	}
1.662     raeburn  2977:     }
                   2978:     return %personnel;
                   2979: }
1.658     raeburn  2980: 
1.149     www      2981: # ----------------------------------------------------------- Check out an item
                   2982: 
1.504     albertel 2983: sub get_first_access {
                   2984:     my ($type,$argsymb)=@_;
1.790     albertel 2985:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2986:     if ($argsymb) { $symb=$argsymb; }
                   2987:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2988:     if ($type eq 'course') {
                   2989: 	$res='course';
                   2990:     } elsif ($type eq 'map') {
1.588     albertel 2991: 	$res=&symbread($map);
                   2992:     } else {
                   2993: 	$res=$symb;
                   2994:     }
                   2995:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2996:     return $times{"$courseid\0$res"};
1.504     albertel 2997: }
                   2998: 
                   2999: sub set_first_access {
                   3000:     my ($type)=@_;
1.790     albertel 3001:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3002:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3003:     if ($type eq 'course') {
                   3004: 	$res='course';
                   3005:     } elsif ($type eq 'map') {
1.588     albertel 3006: 	$res=&symbread($map);
                   3007:     } else {
                   3008: 	$res=$symb;
                   3009:     }
                   3010:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3011:     if (!$firstaccess) {
1.588     albertel 3012: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3013:     }
                   3014:     return 'already_set';
1.504     albertel 3015: }
                   3016: 
1.149     www      3017: sub checkout {
                   3018:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3019:     my $now=time;
                   3020:     my $lonhost=$perlvar{'lonHostID'};
                   3021:     my $infostr=&escape(
1.234     www      3022:                  'CHECKOUTTOKEN&'.
1.149     www      3023:                  $tuname.'&'.
                   3024:                  $tudom.'&'.
                   3025:                  $tcrsid.'&'.
                   3026:                  $symb.'&'.
                   3027: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3028:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3029:     if ($token=~/^error\:/) { 
1.672     albertel 3030:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3031:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3032:                  "</font>");
                   3033:         return ''; 
                   3034:     }
                   3035: 
1.149     www      3036:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3037:     $token=~tr/a-z/A-Z/;
                   3038: 
1.153     www      3039:     my %infohash=('resource.0.outtoken' => $token,
                   3040:                   'resource.0.checkouttime' => $now,
                   3041:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3042: 
                   3043:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3044:        return '';
1.151     www      3045:     } else {
1.672     albertel 3046:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3047:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3048:                  "</font>");
1.149     www      3049:     }    
                   3050: 
                   3051:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3052:                          &escape('Checkout '.$infostr.' - '.
                   3053:                                                  $token)) ne 'ok') {
                   3054: 	return '';
1.151     www      3055:     } else {
1.672     albertel 3056:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3057:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3058:                  "</font>");
1.149     www      3059:     }
1.151     www      3060:     return $token;
1.149     www      3061: }
                   3062: 
                   3063: # ------------------------------------------------------------ Check in an item
                   3064: 
                   3065: sub checkin {
                   3066:     my $token=shift;
1.150     www      3067:     my $now=time;
                   3068:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3069:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3070:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3071:     $dtoken=~s/\W/\_/g;
1.234     www      3072:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3073:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3074: 
1.154     www      3075:     unless (($tuname) && ($tudom)) {
                   3076:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3077:         return '';
                   3078:     }
                   3079:     
                   3080:     unless (&allowed('mgr',$tcrsid)) {
                   3081:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3082:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3083:         return '';
                   3084:     }
                   3085: 
1.153     www      3086:     my %infohash=('resource.0.intoken' => $token,
                   3087:                   'resource.0.checkintime' => $now,
                   3088:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3089: 
                   3090:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3091:        return '';
                   3092:     }    
                   3093: 
                   3094:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3095:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3096: 	return '';
                   3097:     }
                   3098: 
                   3099:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3100: }
                   3101: 
                   3102: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3103: 
                   3104: sub expirespread {
                   3105:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3106:     my $cid=$env{'request.course.id'}; 
1.110     www      3107:     if ($cid) {
                   3108:        my $now=time;
                   3109:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3110:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3111:                             $env{'course.'.$cid.'.num'}.
1.110     www      3112: 	        	    ':nohist_expirationdates:'.
                   3113:                             &escape($key).'='.$now,
1.620     albertel 3114:                             $env{'course.'.$cid.'.home'})
1.110     www      3115:     }
                   3116:     return 'ok';
1.14      www      3117: }
                   3118: 
1.109     www      3119: # ----------------------------------------------------- Devalidate Spreadsheets
                   3120: 
                   3121: sub devalidate {
1.325     www      3122:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3123:     my $cid=$env{'request.course.id'}; 
1.109     www      3124:     if ($cid) {
1.391     matthew  3125:         # delete the stored spreadsheets for
                   3126:         # - the student level sheet of this user in course's homespace
                   3127:         # - the assessment level sheet for this resource 
                   3128:         #   for this user in user's homespace
1.553     albertel 3129: 	# - current conditional state info
1.325     www      3130: 	my $key=$uname.':'.$udom.':';
1.109     www      3131:         my $status=
1.299     matthew  3132: 	    &del('nohist_calculatedsheets',
1.391     matthew  3133: 		 [$key.'studentcalc:'],
1.620     albertel 3134: 		 $env{'course.'.$cid.'.domain'},
                   3135: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3136: 		.' '.
                   3137: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3138: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3139:         unless ($status eq 'ok ok') {
                   3140:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3141:                     $uname.' at '.$udom.' for '.
1.109     www      3142: 		    $symb.': '.$status);
1.133     albertel 3143:         }
1.553     albertel 3144: 	&delenv('user.state.'.$cid);
1.109     www      3145:     }
                   3146: }
                   3147: 
1.265     albertel 3148: sub get_scalar {
                   3149:     my ($string,$end) = @_;
                   3150:     my $value;
                   3151:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3152: 	$value = $1;
                   3153:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3154: 	$value = $1;
                   3155:     }
                   3156:     return &unescape($value);
                   3157: }
                   3158: 
                   3159: sub array2str {
                   3160:   my (@array) = @_;
                   3161:   my $result=&arrayref2str(\@array);
                   3162:   $result=~s/^__ARRAY_REF__//;
                   3163:   $result=~s/__END_ARRAY_REF__$//;
                   3164:   return $result;
                   3165: }
                   3166: 
1.204     albertel 3167: sub arrayref2str {
                   3168:   my ($arrayref) = @_;
1.265     albertel 3169:   my $result='__ARRAY_REF__';
1.204     albertel 3170:   foreach my $elem (@$arrayref) {
1.265     albertel 3171:     if(ref($elem) eq 'ARRAY') {
                   3172:       $result.=&arrayref2str($elem).'&';
                   3173:     } elsif(ref($elem) eq 'HASH') {
                   3174:       $result.=&hashref2str($elem).'&';
                   3175:     } elsif(ref($elem)) {
                   3176:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3177:     } else {
                   3178:       $result.=&escape($elem).'&';
                   3179:     }
                   3180:   }
                   3181:   $result=~s/\&$//;
1.265     albertel 3182:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3183:   return $result;
                   3184: }
                   3185: 
1.168     albertel 3186: sub hash2str {
1.204     albertel 3187:   my (%hash) = @_;
                   3188:   my $result=&hashref2str(\%hash);
1.265     albertel 3189:   $result=~s/^__HASH_REF__//;
                   3190:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3191:   return $result;
                   3192: }
                   3193: 
                   3194: sub hashref2str {
                   3195:   my ($hashref)=@_;
1.265     albertel 3196:   my $result='__HASH_REF__';
1.800     albertel 3197:   foreach my $key (sort(keys(%$hashref))) {
                   3198:     if (ref($key) eq 'ARRAY') {
                   3199:       $result.=&arrayref2str($key).'=';
                   3200:     } elsif (ref($key) eq 'HASH') {
                   3201:       $result.=&hashref2str($key).'=';
                   3202:     } elsif (ref($key)) {
1.265     albertel 3203:       $result.='=';
1.800     albertel 3204:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3205:     } else {
1.800     albertel 3206: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3207:     }
                   3208: 
1.800     albertel 3209:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3210:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3211:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3212:       $result.=&hashref2str($hashref->{$key}).'&';
                   3213:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3214:        $result.='&';
1.800     albertel 3215:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3216:     } else {
1.800     albertel 3217:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3218:     }
                   3219:   }
1.168     albertel 3220:   $result=~s/\&$//;
1.265     albertel 3221:   $result .= '__END_HASH_REF__';
1.168     albertel 3222:   return $result;
                   3223: }
                   3224: 
                   3225: sub str2hash {
1.265     albertel 3226:     my ($string)=@_;
                   3227:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3228:     return %$hash;
                   3229: }
                   3230: 
                   3231: sub str2hashref {
1.168     albertel 3232:   my ($string) = @_;
1.265     albertel 3233: 
                   3234:   my %hash;
                   3235: 
                   3236:   if($string !~ /^__HASH_REF__/) {
                   3237:       if (! ($string eq '' || !defined($string))) {
                   3238: 	  $hash{'error'}='Not hash reference';
                   3239:       }
                   3240:       return (\%hash, $string);
                   3241:   }
                   3242: 
                   3243:   $string =~ s/^__HASH_REF__//;
                   3244: 
                   3245:   while($string !~ /^__END_HASH_REF__/) {
                   3246:       #key
                   3247:       my $key='';
                   3248:       if($string =~ /^__HASH_REF__/) {
                   3249:           ($key, $string)=&str2hashref($string);
                   3250:           if(defined($key->{'error'})) {
                   3251:               $hash{'error'}='Bad data';
                   3252:               return (\%hash, $string);
                   3253:           }
                   3254:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3255:           ($key, $string)=&str2arrayref($string);
                   3256:           if($key->[0] eq 'Array reference error') {
                   3257:               $hash{'error'}='Bad data';
                   3258:               return (\%hash, $string);
                   3259:           }
                   3260:       } else {
                   3261:           $string =~ s/^(.*?)=//;
1.267     albertel 3262: 	  $key=&unescape($1);
1.265     albertel 3263:       }
                   3264:       $string =~ s/^=//;
                   3265: 
                   3266:       #value
                   3267:       my $value='';
                   3268:       if($string =~ /^__HASH_REF__/) {
                   3269:           ($value, $string)=&str2hashref($string);
                   3270:           if(defined($value->{'error'})) {
                   3271:               $hash{'error'}='Bad data';
                   3272:               return (\%hash, $string);
                   3273:           }
                   3274:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3275:           ($value, $string)=&str2arrayref($string);
                   3276:           if($value->[0] eq 'Array reference error') {
                   3277:               $hash{'error'}='Bad data';
                   3278:               return (\%hash, $string);
                   3279:           }
                   3280:       } else {
                   3281: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3282:       }
                   3283:       $string =~ s/^&//;
                   3284: 
                   3285:       $hash{$key}=$value;
1.204     albertel 3286:   }
1.265     albertel 3287: 
                   3288:   $string =~ s/^__END_HASH_REF__//;
                   3289: 
                   3290:   return (\%hash, $string);
1.204     albertel 3291: }
                   3292: 
                   3293: sub str2array {
1.265     albertel 3294:     my ($string)=@_;
                   3295:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3296:     return @$array;
                   3297: }
                   3298: 
                   3299: sub str2arrayref {
1.204     albertel 3300:   my ($string) = @_;
1.265     albertel 3301:   my @array;
                   3302: 
                   3303:   if($string !~ /^__ARRAY_REF__/) {
                   3304:       if (! ($string eq '' || !defined($string))) {
                   3305: 	  $array[0]='Array reference error';
                   3306:       }
                   3307:       return (\@array, $string);
                   3308:   }
                   3309: 
                   3310:   $string =~ s/^__ARRAY_REF__//;
                   3311: 
                   3312:   while($string !~ /^__END_ARRAY_REF__/) {
                   3313:       my $value='';
                   3314:       if($string =~ /^__HASH_REF__/) {
                   3315:           ($value, $string)=&str2hashref($string);
                   3316:           if(defined($value->{'error'})) {
                   3317:               $array[0] ='Array reference error';
                   3318:               return (\@array, $string);
                   3319:           }
                   3320:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3321:           ($value, $string)=&str2arrayref($string);
                   3322:           if($value->[0] eq 'Array reference error') {
                   3323:               $array[0] ='Array reference error';
                   3324:               return (\@array, $string);
                   3325:           }
                   3326:       } else {
                   3327: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3328:       }
                   3329:       $string =~ s/^&//;
                   3330: 
                   3331:       push(@array, $value);
1.191     harris41 3332:   }
1.265     albertel 3333: 
                   3334:   $string =~ s/^__END_ARRAY_REF__//;
                   3335: 
                   3336:   return (\@array, $string);
1.168     albertel 3337: }
                   3338: 
1.167     albertel 3339: # -------------------------------------------------------------------Temp Store
                   3340: 
1.168     albertel 3341: sub tmpreset {
                   3342:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3343:   if (!$symb) {
                   3344:     $symb=&symbread();
1.620     albertel 3345:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3346:   }
                   3347:   $symb=escape($symb);
                   3348: 
1.620     albertel 3349:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3350:   $namespace=~s/\//\_/g;
                   3351:   $namespace=~s/\W//g;
                   3352: 
1.620     albertel 3353:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3354:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3355:   if ($domain eq 'public' && $stuname eq 'public') {
                   3356:       $stuname=$ENV{'REMOTE_ADDR'};
                   3357:   }
1.168     albertel 3358:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3359:   my %hash;
                   3360:   if (tie(%hash,'GDBM_File',
                   3361: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3362: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3363:     foreach my $key (keys %hash) {
1.180     albertel 3364:       if ($key=~ /:$symb/) {
1.168     albertel 3365: 	delete($hash{$key});
                   3366:       }
                   3367:     }
                   3368:   }
                   3369: }
                   3370: 
1.167     albertel 3371: sub tmpstore {
1.168     albertel 3372:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3373: 
                   3374:   if (!$symb) {
                   3375:     $symb=&symbread();
1.620     albertel 3376:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3377:   }
                   3378:   $symb=escape($symb);
                   3379: 
                   3380:   if (!$namespace) {
                   3381:     # I don't think we would ever want to store this for a course.
                   3382:     # it seems this will only be used if we don't have a course.
1.620     albertel 3383:     #$namespace=$env{'request.course.id'};
1.168     albertel 3384:     #if (!$namespace) {
1.620     albertel 3385:       $namespace=$env{'request.state'};
1.168     albertel 3386:     #}
                   3387:   }
                   3388:   $namespace=~s/\//\_/g;
                   3389:   $namespace=~s/\W//g;
1.620     albertel 3390:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3391:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3392:   if ($domain eq 'public' && $stuname eq 'public') {
                   3393:       $stuname=$ENV{'REMOTE_ADDR'};
                   3394:   }
1.168     albertel 3395:   my $now=time;
                   3396:   my %hash;
                   3397:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3398:   if (tie(%hash,'GDBM_File',
                   3399: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3400: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3401:     $hash{"version:$symb"}++;
                   3402:     my $version=$hash{"version:$symb"};
                   3403:     my $allkeys=''; 
                   3404:     foreach my $key (keys(%$storehash)) {
                   3405:       $allkeys.=$key.':';
1.591     albertel 3406:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3407:     }
                   3408:     $hash{"$version:$symb:timestamp"}=$now;
                   3409:     $allkeys.='timestamp';
                   3410:     $hash{"$version:keys:$symb"}=$allkeys;
                   3411:     if (untie(%hash)) {
                   3412:       return 'ok';
                   3413:     } else {
                   3414:       return "error:$!";
                   3415:     }
                   3416:   } else {
                   3417:     return "error:$!";
                   3418:   }
                   3419: }
1.167     albertel 3420: 
1.168     albertel 3421: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3422: 
1.168     albertel 3423: sub tmprestore {
                   3424:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3425: 
1.168     albertel 3426:   if (!$symb) {
                   3427:     $symb=&symbread();
1.620     albertel 3428:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3429:   }
                   3430:   $symb=escape($symb);
                   3431: 
1.620     albertel 3432:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3433: 
1.620     albertel 3434:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3435:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3436:   if ($domain eq 'public' && $stuname eq 'public') {
                   3437:       $stuname=$ENV{'REMOTE_ADDR'};
                   3438:   }
1.168     albertel 3439:   my %returnhash;
                   3440:   $namespace=~s/\//\_/g;
                   3441:   $namespace=~s/\W//g;
                   3442:   my %hash;
                   3443:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3444:   if (tie(%hash,'GDBM_File',
                   3445: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3446: 	  &GDBM_READER(),0640)) {
1.168     albertel 3447:     my $version=$hash{"version:$symb"};
                   3448:     $returnhash{'version'}=$version;
                   3449:     my $scope;
                   3450:     for ($scope=1;$scope<=$version;$scope++) {
                   3451:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3452:       my @keys=split(/:/,$vkeys);
                   3453:       my $key;
                   3454:       $returnhash{"$scope:keys"}=$vkeys;
                   3455:       foreach $key (@keys) {
1.591     albertel 3456: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3457: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3458:       }
                   3459:     }
1.168     albertel 3460:     if (!(untie(%hash))) {
                   3461:       return "error:$!";
                   3462:     }
                   3463:   } else {
                   3464:     return "error:$!";
                   3465:   }
                   3466:   return %returnhash;
1.167     albertel 3467: }
                   3468: 
1.9       www      3469: # ----------------------------------------------------------------------- Store
                   3470: 
                   3471: sub store {
1.124     www      3472:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3473:     my $home='';
                   3474: 
1.168     albertel 3475:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3476: 
1.213     www      3477:     $symb=&symbclean($symb);
1.122     albertel 3478:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3479: 
1.620     albertel 3480:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3481:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3482: 
                   3483:     &devalidate($symb,$stuname,$domain);
1.109     www      3484: 
                   3485:     $symb=escape($symb);
1.187     www      3486:     if (!$namespace) { 
1.620     albertel 3487:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3488:           return ''; 
                   3489:        } 
                   3490:     }
1.620     albertel 3491:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3492: 
                   3493:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3494:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3495: 
1.12      www      3496:     my $namevalue='';
1.800     albertel 3497:     foreach my $key (keys(%$storehash)) {
                   3498:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3499:     }
1.12      www      3500:     $namevalue=~s/\&$//;
1.187     www      3501:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3502:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3503: }
                   3504: 
1.47      www      3505: # -------------------------------------------------------------- Critical Store
                   3506: 
                   3507: sub cstore {
1.124     www      3508:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3509:     my $home='';
                   3510: 
1.168     albertel 3511:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3512: 
1.213     www      3513:     $symb=&symbclean($symb);
1.122     albertel 3514:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3515: 
1.620     albertel 3516:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3517:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3518: 
                   3519:     &devalidate($symb,$stuname,$domain);
1.109     www      3520: 
                   3521:     $symb=escape($symb);
1.187     www      3522:     if (!$namespace) { 
1.620     albertel 3523:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3524:           return ''; 
                   3525:        } 
                   3526:     }
1.620     albertel 3527:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3528: 
                   3529:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3530:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3531: 
1.47      www      3532:     my $namevalue='';
1.800     albertel 3533:     foreach my $key (keys(%$storehash)) {
                   3534:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3535:     }
1.47      www      3536:     $namevalue=~s/\&$//;
1.187     www      3537:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3538:     return critical
                   3539:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3540: }
                   3541: 
1.9       www      3542: # --------------------------------------------------------------------- Restore
                   3543: 
                   3544: sub restore {
1.124     www      3545:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3546:     my $home='';
                   3547: 
1.168     albertel 3548:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3549: 
1.122     albertel 3550:     if (!$symb) {
                   3551:       unless ($symb=escape(&symbread())) { return ''; }
                   3552:     } else {
1.213     www      3553:       $symb=&escape(&symbclean($symb));
1.122     albertel 3554:     }
1.188     www      3555:     if (!$namespace) { 
1.620     albertel 3556:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3557:           return ''; 
                   3558:        } 
                   3559:     }
1.620     albertel 3560:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3561:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3562:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3563:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3564: 
1.12      www      3565:     my %returnhash=();
1.800     albertel 3566:     foreach my $line (split(/\&/,$answer)) {
                   3567: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3568:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3569:     }
1.75      www      3570:     my $version;
                   3571:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3572:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3573:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3574:        }
1.75      www      3575:     }
1.13      www      3576:     return %returnhash;
1.34      www      3577: }
                   3578: 
                   3579: # ---------------------------------------------------------- Course Description
                   3580: 
                   3581: sub coursedescription {
1.731     albertel 3582:     my ($courseid,$args)=@_;
1.34      www      3583:     $courseid=~s/^\///;
1.49      www      3584:     $courseid=~s/\_/\//g;
1.34      www      3585:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3586:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3587:     my $normalid=$cdomain.'_'.$cnum;
                   3588:     # need to always cache even if we get errors otherwise we keep 
                   3589:     # trying and trying and trying to get the course description.
                   3590:     my %envhash=();
                   3591:     my %returnhash=();
1.731     albertel 3592:     
                   3593:     my $expiretime=600;
                   3594:     if ($env{'request.course.id'} eq $normalid) {
                   3595: 	$expiretime=120;
                   3596:     }
                   3597: 
                   3598:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3599:     if (!$args->{'freshen_cache'}
                   3600: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3601: 	foreach my $key (keys(%env)) {
                   3602: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3603: 	    my ($setting) = $1;
                   3604: 	    $returnhash{$setting} = $env{$key};
                   3605: 	}
                   3606: 	return %returnhash;
                   3607:     }
                   3608: 
                   3609:     # get the data agin
                   3610:     if (!$args->{'one_time'}) {
                   3611: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3612:     }
1.811     albertel 3613: 
1.34      www      3614:     if ($chome ne 'no_host') {
1.302     albertel 3615:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3616:        if (!exists($returnhash{'con_lost'})) {
                   3617:            $returnhash{'home'}= $chome;
                   3618: 	   $returnhash{'domain'} = $cdomain;
                   3619: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3620:            if (!defined($returnhash{'type'})) {
                   3621:                $returnhash{'type'} = 'Course';
                   3622:            }
1.130     albertel 3623:            while (my ($name,$value) = each %returnhash) {
1.53      www      3624:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3625:            }
1.270     www      3626:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3627:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3628: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3629:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3630:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3631:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3632:        }
                   3633:     }
1.731     albertel 3634:     if (!$args->{'one_time'}) {
1.949     raeburn  3635: 	&appenv(\%envhash);
1.731     albertel 3636:     }
1.302     albertel 3637:     return %returnhash;
1.461     www      3638: }
                   3639: 
                   3640: # -------------------------------------------------See if a user is privileged
                   3641: 
                   3642: sub privileged {
                   3643:     my ($username,$domain)=@_;
                   3644:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3645: 			&homeserver($username,$domain));
                   3646:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3647:     my $now=time;
                   3648:     if ($rolesdump ne '') {
1.800     albertel 3649:         foreach my $entry (split(/&/,$rolesdump)) {
                   3650: 	    if ($entry!~/^rolesdef_/) {
                   3651: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3652: 		$area=~s/\_\w\w$//;
                   3653: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3654: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3655: 		    my $active=1;
                   3656: 		    if ($tend) {
                   3657: 			if ($tend<$now) { $active=0; }
                   3658: 		    }
                   3659: 		    if ($tstart) {
                   3660: 			if ($tstart>$now) { $active=0; }
                   3661: 		    }
                   3662: 		    if ($active) { return 1; }
                   3663: 		}
                   3664: 	    }
                   3665: 	}
                   3666:     }
                   3667:     return 0;
1.9       www      3668: }
1.1       albertel 3669: 
1.103     harris41 3670: # -------------------------------------------------------- Get user privileges
1.11      www      3671: 
                   3672: sub rolesinit {
                   3673:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3674:     my %userroles;
1.11      www      3675:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3676:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3677:     my %allroles=();
1.678     raeburn  3678:     my %allgroups=();   
1.11      www      3679:     my $now=time;
1.966     raeburn  3680:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3681:     my $group_privs;
1.11      www      3682: 
                   3683:     if ($rolesdump ne '') {
1.800     albertel 3684:         foreach my $entry (split(/&/,$rolesdump)) {
                   3685: 	  if ($entry!~/^rolesdef_/) {
                   3686:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3687: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3688:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3689: 	    if ($role=~/^cr/) { 
1.807     albertel 3690: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3691: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3692: 		    ($tend,$tstart)=split('_',$trest);
                   3693: 		} else {
                   3694: 		    $trole=$role;
                   3695: 		}
1.678     raeburn  3696:             } elsif ($role =~ m|^gr/|) {
                   3697:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3698:                 ($trole,$group_privs) = split(/\//,$trole);
                   3699:                 $group_privs = &unescape($group_privs);
1.587     albertel 3700: 	    } else {
                   3701: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3702: 	    }
1.743     albertel 3703: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3704: 					 $username);
                   3705: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3706:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3707:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3708:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3709: 		my $spec=$trole.'.'.$area;
                   3710: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3711: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3712:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3713:                 } elsif ($trole eq 'gr') {
                   3714:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3715: 		} else {
1.567     raeburn  3716:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3717: 		}
1.12      www      3718:             }
1.662     raeburn  3719:           }
1.191     harris41 3720:         }
1.743     albertel 3721:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3722:         $userroles{'user.adv'}    = $adv;
                   3723: 	$userroles{'user.author'} = $author;
1.620     albertel 3724:         $env{'user.adv'}=$adv;
1.11      www      3725:     }
1.743     albertel 3726:     return \%userroles;  
1.11      www      3727: }
                   3728: 
1.567     raeburn  3729: sub set_arearole {
                   3730:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3731: # log the associated role with the area
                   3732:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3733:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3734: }
                   3735: 
                   3736: sub custom_roleprivs {
                   3737:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3738:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3739:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3740:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3741:         my ($rdummy,$roledef)=
                   3742:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3743:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3744:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3745:             if (defined($syspriv)) {
                   3746:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3747:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3748:             }
                   3749:             if ($tdomain ne '') {
                   3750:                 if (defined($dompriv)) {
                   3751:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3752:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3753:                 }
                   3754:                 if (($trest ne '') && (defined($coursepriv))) {
                   3755:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3756:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3757:                 }
                   3758:             }
                   3759:         }
                   3760:     }
                   3761: }
                   3762: 
1.678     raeburn  3763: sub group_roleprivs {
                   3764:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3765:     my $access = 1;
                   3766:     my $now = time;
                   3767:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3768:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3769:     if ($access) {
1.811     albertel 3770:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3771:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3772:     }
                   3773: }
1.567     raeburn  3774: 
                   3775: sub standard_roleprivs {
                   3776:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3777:     if (defined($pr{$trole.':s'})) {
                   3778:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3779:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3780:     }
                   3781:     if ($tdomain ne '') {
                   3782:         if (defined($pr{$trole.':d'})) {
                   3783:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3784:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3785:         }
                   3786:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3787:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3788:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3789:         }
                   3790:     }
                   3791: }
                   3792: 
                   3793: sub set_userprivs {
1.678     raeburn  3794:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3795:     my $author=0;
                   3796:     my $adv=0;
1.678     raeburn  3797:     my %grouproles = ();
                   3798:     if (keys(%{$allgroups}) > 0) {
                   3799:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3800:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3801:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3802:                 $trole = $1;
                   3803:                 $area = $2;
1.681     raeburn  3804:                 $sec = $3;
                   3805:                 $extendedarea = $area.$sec;
                   3806:                 if (exists($$allgroups{$area})) {
                   3807:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3808:                         my $spec = $trole.'.'.$extendedarea;
                   3809:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3810:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3811:                     }
                   3812:                 }
                   3813:             }
                   3814:         }
                   3815:     }
1.800     albertel 3816:     foreach my $group (keys(%grouproles)) {
                   3817:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3818:     }
1.800     albertel 3819:     foreach my $role (keys(%{$allroles})) {
                   3820:         my %thesepriv;
1.941     raeburn  3821:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3822:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3823:             if ($item ne '') {
                   3824:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3825:                 if ($restrictions eq '') {
                   3826:                     $thesepriv{$privilege}='F';
                   3827:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3828:                     $thesepriv{$privilege}.=$restrictions;
                   3829:                 }
                   3830:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3831:             }
                   3832:         }
                   3833:         my $thesestr='';
1.800     albertel 3834:         foreach my $priv (keys(%thesepriv)) {
                   3835: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3836: 	}
                   3837:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3838:     }
                   3839:     return ($author,$adv);
                   3840: }
                   3841: 
1.12      www      3842: # --------------------------------------------------------------- get interface
                   3843: 
                   3844: sub get {
1.131     albertel 3845:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3846:    my $items='';
1.800     albertel 3847:    foreach my $item (@$storearr) {
                   3848:        $items.=&escape($item).'&';
1.191     harris41 3849:    }
1.12      www      3850:    $items=~s/\&$//;
1.620     albertel 3851:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3852:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3853:    my $uhome=&homeserver($uname,$udomain);
                   3854: 
1.133     albertel 3855:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3856:    my @pairs=split(/\&/,$rep);
1.273     albertel 3857:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3858:      return @pairs;
                   3859:    }
1.15      www      3860:    my %returnhash=();
1.42      www      3861:    my $i=0;
1.800     albertel 3862:    foreach my $item (@$storearr) {
                   3863:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3864:       $i++;
1.191     harris41 3865:    }
1.15      www      3866:    return %returnhash;
1.27      www      3867: }
                   3868: 
                   3869: # --------------------------------------------------------------- del interface
                   3870: 
                   3871: sub del {
1.133     albertel 3872:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3873:    my $items='';
1.800     albertel 3874:    foreach my $item (@$storearr) {
                   3875:        $items.=&escape($item).'&';
1.191     harris41 3876:    }
1.27      www      3877:    $items=~s/\&$//;
1.620     albertel 3878:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3879:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3880:    my $uhome=&homeserver($uname,$udomain);
                   3881: 
                   3882:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3883: }
                   3884: 
                   3885: # -------------------------------------------------------------- dump interface
                   3886: 
                   3887: sub dump {
1.755     albertel 3888:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3889:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3890:     if (!$uname) { $uname=$env{'user.name'}; }
                   3891:     my $uhome=&homeserver($uname,$udomain);
                   3892:     if ($regexp) {
                   3893: 	$regexp=&escape($regexp);
                   3894:     } else {
                   3895: 	$regexp='.';
                   3896:     }
                   3897:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3898:     my @pairs=split(/\&/,$rep);
                   3899:     my %returnhash=();
                   3900:     foreach my $item (@pairs) {
                   3901: 	my ($key,$value)=split(/=/,$item,2);
                   3902: 	$key = &unescape($key);
                   3903: 	next if ($key =~ /^error: 2 /);
                   3904: 	$returnhash{$key}=&thaw_unescape($value);
                   3905:     }
                   3906:     return %returnhash;
1.407     www      3907: }
                   3908: 
1.717     albertel 3909: # --------------------------------------------------------- dumpstore interface
                   3910: 
                   3911: sub dumpstore {
                   3912:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3914:    if (!$uname) { $uname=$env{'user.name'}; }
                   3915:    my $uhome=&homeserver($uname,$udomain);
                   3916:    if ($regexp) {
                   3917:        $regexp=&escape($regexp);
                   3918:    } else {
                   3919:        $regexp='.';
                   3920:    }
                   3921:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3922:    my @pairs=split(/\&/,$rep);
                   3923:    my %returnhash=();
                   3924:    foreach my $item (@pairs) {
                   3925:        my ($key,$value)=split(/=/,$item,2);
                   3926:        next if ($key =~ /^error: 2 /);
                   3927:        $returnhash{$key}=&thaw_unescape($value);
                   3928:    }
                   3929:    return %returnhash;
1.717     albertel 3930: }
                   3931: 
1.407     www      3932: # -------------------------------------------------------------- keys interface
                   3933: 
                   3934: sub getkeys {
                   3935:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3936:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3937:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3938:    my $uhome=&homeserver($uname,$udomain);
                   3939:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3940:    my @keyarray=();
1.800     albertel 3941:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3942:       next if ($key =~ /^error: 2 /);
1.800     albertel 3943:       push(@keyarray,&unescape($key));
1.407     www      3944:    }
                   3945:    return @keyarray;
1.318     matthew  3946: }
                   3947: 
1.319     matthew  3948: # --------------------------------------------------------------- currentdump
                   3949: sub currentdump {
1.328     matthew  3950:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3951:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3952:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3953:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3954:    my $uhome = &homeserver($sname,$sdom);
                   3955:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3956:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3957:    #
1.318     matthew  3958:    my %returnhash=();
1.319     matthew  3959:    #
                   3960:    if ($rep eq "unknown_cmd") { 
                   3961:        # an old lond will not know currentdump
                   3962:        # Do a dump and make it look like a currentdump
1.822     albertel 3963:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3964:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3965:        my %hash = @tmp;
                   3966:        @tmp=();
1.424     matthew  3967:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3968:    } else {
                   3969:        my @pairs=split(/\&/,$rep);
1.800     albertel 3970:        foreach my $pair (@pairs) {
                   3971:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3972:            my ($symb,$param) = split(/:/,$key);
                   3973:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3974:                                                         &thaw_unescape($value);
1.319     matthew  3975:        }
1.191     harris41 3976:    }
1.12      www      3977:    return %returnhash;
1.424     matthew  3978: }
                   3979: 
                   3980: sub convert_dump_to_currentdump{
                   3981:     my %hash = %{shift()};
                   3982:     my %returnhash;
                   3983:     # Code ripped from lond, essentially.  The only difference
                   3984:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3985:     # we might run in to problems with parameter names =~ /^v\./
                   3986:     while (my ($key,$value) = each(%hash)) {
                   3987:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3988: 	$symb  = &unescape($symb);
                   3989: 	$param = &unescape($param);
1.424     matthew  3990:         next if ($v eq 'version' || $symb eq 'keys');
                   3991:         next if (exists($returnhash{$symb}) &&
                   3992:                  exists($returnhash{$symb}->{$param}) &&
                   3993:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3994:         $returnhash{$symb}->{$param}=$value;
                   3995:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3996:     }
                   3997:     #
                   3998:     # Remove all of the keys in the hashes which keep track of
                   3999:     # the version of the parameter.
                   4000:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4001:         # use a foreach because we are going to delete from the hash.
                   4002:         foreach my $key (keys(%$param_hash)) {
                   4003:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4004:         }
                   4005:     }
                   4006:     return \%returnhash;
1.12      www      4007: }
                   4008: 
1.627     albertel 4009: # ------------------------------------------------------ critical inc interface
                   4010: 
                   4011: sub cinc {
                   4012:     return &inc(@_,'critical');
                   4013: }
                   4014: 
1.449     matthew  4015: # --------------------------------------------------------------- inc interface
                   4016: 
                   4017: sub inc {
1.627     albertel 4018:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4019:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4020:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4021:     my $uhome=&homeserver($uname,$udomain);
                   4022:     my $items='';
                   4023:     if (! ref($store)) {
                   4024:         # got a single value, so use that instead
                   4025:         $items = &escape($store).'=&';
                   4026:     } elsif (ref($store) eq 'SCALAR') {
                   4027:         $items = &escape($$store).'=&';        
                   4028:     } elsif (ref($store) eq 'ARRAY') {
                   4029:         $items = join('=&',map {&escape($_);} @{$store});
                   4030:     } elsif (ref($store) eq 'HASH') {
                   4031:         while (my($key,$value) = each(%{$store})) {
                   4032:             $items.= &escape($key).'='.&escape($value).'&';
                   4033:         }
                   4034:     }
                   4035:     $items=~s/\&$//;
1.627     albertel 4036:     if ($critical) {
                   4037: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4038:     } else {
                   4039: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4040:     }
1.449     matthew  4041: }
                   4042: 
1.12      www      4043: # --------------------------------------------------------------- put interface
                   4044: 
                   4045: sub put {
1.134     albertel 4046:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4047:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4048:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4049:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4050:    my $items='';
1.800     albertel 4051:    foreach my $item (keys(%$storehash)) {
                   4052:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4053:    }
1.12      www      4054:    $items=~s/\&$//;
1.134     albertel 4055:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4056: }
                   4057: 
1.631     albertel 4058: # ------------------------------------------------------------ newput interface
                   4059: 
                   4060: sub newput {
                   4061:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4062:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4063:    if (!$uname) { $uname=$env{'user.name'}; }
                   4064:    my $uhome=&homeserver($uname,$udomain);
                   4065:    my $items='';
                   4066:    foreach my $key (keys(%$storehash)) {
                   4067:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4068:    }
                   4069:    $items=~s/\&$//;
                   4070:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4071: }
                   4072: 
                   4073: # ---------------------------------------------------------  putstore interface
                   4074: 
1.524     raeburn  4075: sub putstore {
1.715     albertel 4076:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4077:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4078:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4079:    my $uhome=&homeserver($uname,$udomain);
                   4080:    my $items='';
1.715     albertel 4081:    foreach my $key (keys(%$storehash)) {
                   4082:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4083:    }
1.715     albertel 4084:    $items=~s/\&$//;
1.716     albertel 4085:    my $esc_symb=&escape($symb);
                   4086:    my $esc_v=&escape($version);
1.715     albertel 4087:    my $reply =
1.716     albertel 4088:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4089: 	      $uhome);
                   4090:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4091:        # gfall back to way things use to be done
1.715     albertel 4092:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4093: 			    $uname);
1.524     raeburn  4094:    }
1.715     albertel 4095:    return $reply;
                   4096: }
                   4097: 
                   4098: sub old_putstore {
1.716     albertel 4099:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4100:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4101:     if (!$uname) { $uname=$env{'user.name'}; }
                   4102:     my $uhome=&homeserver($uname,$udomain);
                   4103:     my %newstorehash;
1.800     albertel 4104:     foreach my $item (keys(%$storehash)) {
                   4105: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4106: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4107:     }
                   4108:     my $items='';
                   4109:     my %allitems = ();
1.800     albertel 4110:     foreach my $item (keys(%newstorehash)) {
                   4111: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4112: 	    my $key = $1.':keys:'.$2;
                   4113: 	    $allitems{$key} .= $3.':';
                   4114: 	}
1.800     albertel 4115: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4116:     }
1.800     albertel 4117:     foreach my $item (keys(%allitems)) {
                   4118: 	$allitems{$item} =~ s/\:$//;
                   4119: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4120:     }
                   4121:     $items=~s/\&$//;
                   4122:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4123: }
                   4124: 
1.47      www      4125: # ------------------------------------------------------ critical put interface
                   4126: 
                   4127: sub cput {
1.134     albertel 4128:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4130:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4131:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4132:    my $items='';
1.800     albertel 4133:    foreach my $item (keys(%$storehash)) {
                   4134:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4135:    }
1.47      www      4136:    $items=~s/\&$//;
1.134     albertel 4137:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4138: }
                   4139: 
                   4140: # -------------------------------------------------------------- eget interface
                   4141: 
                   4142: sub eget {
1.133     albertel 4143:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4144:    my $items='';
1.800     albertel 4145:    foreach my $item (@$storearr) {
                   4146:        $items.=&escape($item).'&';
1.191     harris41 4147:    }
1.12      www      4148:    $items=~s/\&$//;
1.620     albertel 4149:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4150:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4151:    my $uhome=&homeserver($uname,$udomain);
                   4152:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4153:    my @pairs=split(/\&/,$rep);
                   4154:    my %returnhash=();
1.42      www      4155:    my $i=0;
1.800     albertel 4156:    foreach my $item (@$storearr) {
                   4157:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4158:       $i++;
1.191     harris41 4159:    }
1.12      www      4160:    return %returnhash;
                   4161: }
                   4162: 
1.667     albertel 4163: # ------------------------------------------------------------ tmpput interface
                   4164: sub tmpput {
1.802     raeburn  4165:     my ($storehash,$server,$context)=@_;
1.667     albertel 4166:     my $items='';
1.800     albertel 4167:     foreach my $item (keys(%$storehash)) {
                   4168: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4169:     }
                   4170:     $items=~s/\&$//;
1.802     raeburn  4171:     if (defined($context)) {
                   4172:         $items .= ':'.&escape($context);
                   4173:     }
1.667     albertel 4174:     return &reply("tmpput:$items",$server);
                   4175: }
                   4176: 
                   4177: # ------------------------------------------------------------ tmpget interface
                   4178: sub tmpget {
1.688     albertel 4179:     my ($token,$server)=@_;
                   4180:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4181:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4182:     my %returnhash;
                   4183:     foreach my $item (split(/\&/,$rep)) {
                   4184: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4185:         next if ($key =~ /^error: 2 /);
1.667     albertel 4186: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4187:     }
                   4188:     return %returnhash;
                   4189: }
                   4190: 
1.688     albertel 4191: # ------------------------------------------------------------ tmpget interface
                   4192: sub tmpdel {
                   4193:     my ($token,$server)=@_;
                   4194:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4195:     return &reply("tmpdel:$token",$server);
                   4196: }
                   4197: 
1.765     albertel 4198: # -------------------------------------------------- portfolio access checking
                   4199: 
                   4200: sub portfolio_access {
1.766     albertel 4201:     my ($requrl) = @_;
1.765     albertel 4202:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4203:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4204:     if ($result) {
                   4205:         my %setters;
                   4206:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4207:             my ($startblock,$endblock) =
                   4208:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4209:             if ($startblock && $endblock) {
                   4210:                 return 'B';
                   4211:             }
                   4212:         } else {
                   4213:             my ($startblock,$endblock) =
                   4214:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4215:             if ($startblock && $endblock) {
                   4216:                 return 'B';
                   4217:             }
                   4218:         }
                   4219:     }
1.765     albertel 4220:     if ($result eq 'ok') {
1.766     albertel 4221:        return 'F';
1.765     albertel 4222:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4223:        return 'A';
1.765     albertel 4224:     }
1.766     albertel 4225:     return '';
1.765     albertel 4226: }
                   4227: 
                   4228: sub get_portfolio_access {
1.767     albertel 4229:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4230: 
                   4231:     if (!ref($access_hash)) {
                   4232: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4233: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4234: 						   $file_name);
                   4235: 	$access_hash = $access_controls{$file_name};
                   4236:     }
                   4237: 
1.765     albertel 4238:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4239:     my $now = time;
                   4240:     if (ref($access_hash) eq 'HASH') {
                   4241:         foreach my $key (keys(%{$access_hash})) {
                   4242:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4243:             if ($start > $now) {
                   4244:                 next;
                   4245:             }
                   4246:             if ($end && $end<$now) {
                   4247:                 next;
                   4248:             }
                   4249:             if ($scope eq 'public') {
                   4250:                 $public = $key;
                   4251:                 last;
                   4252:             } elsif ($scope eq 'guest') {
                   4253:                 $guest = $key;
                   4254:             } elsif ($scope eq 'domains') {
                   4255:                 push(@domains,$key);
                   4256:             } elsif ($scope eq 'users') {
                   4257:                 push(@users,$key);
                   4258:             } elsif ($scope eq 'course') {
                   4259:                 push(@courses,$key);
                   4260:             } elsif ($scope eq 'group') {
                   4261:                 push(@groups,$key);
                   4262:             }
                   4263:         }
                   4264:         if ($public) {
                   4265:             return 'ok';
                   4266:         }
                   4267:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4268:             if ($guest) {
                   4269:                 return $guest;
                   4270:             }
                   4271:         } else {
                   4272:             if (@domains > 0) {
                   4273:                 foreach my $domkey (@domains) {
                   4274:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4275:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4276:                             return 'ok';
                   4277:                         }
                   4278:                     }
                   4279:                 }
                   4280:             }
                   4281:             if (@users > 0) {
                   4282:                 foreach my $userkey (@users) {
1.865     raeburn  4283:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4284:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4285:                             if (ref($item) eq 'HASH') {
                   4286:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4287:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4288:                                     return 'ok';
                   4289:                                 }
                   4290:                             }
                   4291:                         }
                   4292:                     } 
1.765     albertel 4293:                 }
                   4294:             }
                   4295:             my %roleshash;
                   4296:             my @courses_and_groups = @courses;
                   4297:             push(@courses_and_groups,@groups); 
                   4298:             if (@courses_and_groups > 0) {
                   4299:                 my (%allgroups,%allroles); 
                   4300:                 my ($start,$end,$role,$sec,$group);
                   4301:                 foreach my $envkey (%env) {
1.811     albertel 4302:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4303:                         my $cid = $2.'_'.$3; 
                   4304:                         if ($1 eq 'gr') {
                   4305:                             $group = $4;
                   4306:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4307:                         } else {
                   4308:                             if ($4 eq '') {
                   4309:                                 $sec = 'none';
                   4310:                             } else {
                   4311:                                 $sec = $4;
                   4312:                             }
                   4313:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4314:                         }
1.811     albertel 4315:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4316:                         my $cid = $2.'_'.$3;
                   4317:                         if ($4 eq '') {
                   4318:                             $sec = 'none';
                   4319:                         } else {
                   4320:                             $sec = $4;
                   4321:                         }
                   4322:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4323:                     }
                   4324:                 }
                   4325:                 if (keys(%allroles) == 0) {
                   4326:                     return;
                   4327:                 }
                   4328:                 foreach my $key (@courses_and_groups) {
                   4329:                     my %content = %{$$access_hash{$key}};
                   4330:                     my $cnum = $content{'number'};
                   4331:                     my $cdom = $content{'domain'};
                   4332:                     my $cid = $cdom.'_'.$cnum;
                   4333:                     if (!exists($allroles{$cid})) {
                   4334:                         next;
                   4335:                     }    
                   4336:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4337:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4338:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4339:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4340:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4341:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4342:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4343:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4344:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4345:                                         if (grep/^all$/,@sections) {
                   4346:                                             return 'ok';
                   4347:                                         } else {
                   4348:                                             if (grep/^$sec$/,@sections) {
                   4349:                                                 return 'ok';
                   4350:                                             }
                   4351:                                         }
                   4352:                                     }
                   4353:                                 }
                   4354:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4355:                                     if (grep/^none$/,@groups) {
                   4356:                                         return 'ok';
                   4357:                                     }
                   4358:                                 } else {
                   4359:                                     if (grep/^all$/,@groups) {
                   4360:                                         return 'ok';
                   4361:                                     } 
                   4362:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4363:                                         if (grep/^$group$/,@groups) {
                   4364:                                             return 'ok';
                   4365:                                         }
                   4366:                                     }
                   4367:                                 } 
                   4368:                             }
                   4369:                         }
                   4370:                     }
                   4371:                 }
                   4372:             }
                   4373:             if ($guest) {
                   4374:                 return $guest;
                   4375:             }
                   4376:         }
                   4377:     }
                   4378:     return;
                   4379: }
                   4380: 
                   4381: sub course_group_datechecker {
                   4382:     my ($dates,$now,$status) = @_;
                   4383:     my ($start,$end) = split(/\./,$dates);
                   4384:     if (!$start && !$end) {
                   4385:         return 'ok';
                   4386:     }
                   4387:     if (grep/^active$/,@{$status}) {
                   4388:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4389:             return 'ok';
                   4390:         }
                   4391:     }
                   4392:     if (grep/^previous$/,@{$status}) {
                   4393:         if ($end > $now ) {
                   4394:             return 'ok';
                   4395:         }
                   4396:     }
                   4397:     if (grep/^future$/,@{$status}) {
                   4398:         if ($start > $now) {
                   4399:             return 'ok';
                   4400:         }
                   4401:     }
                   4402:     return; 
                   4403: }
                   4404: 
                   4405: sub parse_portfolio_url {
                   4406:     my ($url) = @_;
                   4407: 
                   4408:     my ($type,$udom,$unum,$group,$file_name);
                   4409:     
1.823     albertel 4410:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4411: 	$type = 1;
                   4412:         $udom = $1;
                   4413:         $unum = $2;
                   4414:         $file_name = $3;
1.823     albertel 4415:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4416: 	$type = 2;
                   4417:         $udom = $1;
                   4418:         $unum = $2;
                   4419:         $group = $3;
                   4420:         $file_name = $3.'/'.$4;
                   4421:     }
                   4422:     if (wantarray) {
                   4423: 	return ($type,$udom,$unum,$file_name,$group);
                   4424:     }
                   4425:     return $type;
                   4426: }
                   4427: 
                   4428: sub is_portfolio_url {
                   4429:     my ($url) = @_;
                   4430:     return scalar(&parse_portfolio_url($url));
                   4431: }
                   4432: 
1.798     raeburn  4433: sub is_portfolio_file {
                   4434:     my ($file) = @_;
1.820     raeburn  4435:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4436:         return 1;
                   4437:     }
                   4438:     return;
                   4439: }
                   4440: 
1.976     raeburn  4441: sub usertools_access {
1.976.4.1  raeburn  4442:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4443:     my $access;
                   4444:     my %tools = (
                   4445:                   aboutme   => 1,
                   4446:                   blog      => 1,
                   4447:                   portfolio => 1,
                   4448:                 );
                   4449:     return if (!defined($tools{$tool}));
                   4450: 
                   4451:     if ((!defined($udom)) || (!defined($uname))) {
                   4452:         $udom = $env{'user.domain'};
                   4453:         $uname = $env{'user.name'};
                   4454:     }
                   4455: 
1.976.4.1  raeburn  4456:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4457:         if ($action ne 'reload') {
                   4458:             return $env{'environment.availabletools.'.$tool};
                   4459:         }
1.976     raeburn  4460:     }
                   4461: 
                   4462:     my ($toolstatus,$inststatus);
                   4463: 
                   4464:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4465:         $toolstatus = $env{'environment.tools.'.$tool};
                   4466:         $inststatus = $env{'environment.inststatus'};
                   4467:     } else {
                   4468:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4469:         $toolstatus = $userenv{'tools.'.$tool};
                   4470:         $inststatus = $userenv{'inststatus'};
                   4471:     }
                   4472: 
                   4473:     if ($toolstatus ne '') {
                   4474:         if ($toolstatus) {
                   4475:             $access = 1;
                   4476:         } else {
                   4477:             $access = 0;
                   4478:         }
                   4479:         return $access;
                   4480:     }
                   4481: 
                   4482:     my $is_adv = &is_advanced_user($udom,$uname);
                   4483:     my %domdef = &get_domain_defaults($udom);
                   4484:     if (ref($domdef{$tool}) eq 'HASH') {
                   4485:         if ($is_adv) {
                   4486:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4487:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4488:                     $access = 1;
                   4489:                 } else {
                   4490:                     $access = 0;
                   4491:                 }
                   4492:                 return $access;
                   4493:             }
                   4494:         }
                   4495:         if ($inststatus ne '') {
                   4496:             my ($hasaccess,$hasnoaccess);
                   4497:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4498:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4499:                     if ($domdef{$tool}{$affiliation}) {
                   4500:                         $hasaccess = 1;
                   4501:                     } else {
                   4502:                         $hasnoaccess = 1;
                   4503:                     }
                   4504:                 }
                   4505:             }
                   4506:             if ($hasaccess || $hasnoaccess) {
                   4507:                 if ($hasaccess) {
                   4508:                     $access = 1;
                   4509:                 } elsif ($hasnoaccess) {
                   4510:                     $access = 0; 
                   4511:                 }
                   4512:                 return $access;
                   4513:             }
                   4514:         } else {
                   4515:             if ($domdef{$tool}{'default'} ne '') {
                   4516:                 if ($domdef{$tool}{'default'}) {
                   4517:                     $access = 1;
                   4518:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4519:                     $access = 0;
                   4520:                 }
                   4521:                 return $access;
                   4522:             }
                   4523:         }
                   4524:     } else {
                   4525:         $access = 1;
                   4526:         return $access;
                   4527:     }
                   4528: }
                   4529: 
                   4530: sub is_advanced_user {
                   4531:     my ($udom,$uname) = @_;
                   4532:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4533:     my %allroles;
                   4534:     my $is_adv;
                   4535:     foreach my $role (keys(%roleshash)) {
                   4536:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4537:         my $area = '/'.$tdomain.'/'.$trest;
                   4538:         if ($sec ne '') {
                   4539:             $area .= '/'.$sec;
                   4540:         }
                   4541:         if (($area ne '') && ($trole ne '')) {
                   4542:             my $spec=$trole.'.'.$area;
                   4543:             if ($trole =~ /^cr\//) {
                   4544:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4545:             } elsif ($trole ne 'gr') {
                   4546:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4547:             }
                   4548:         }
                   4549:     }
                   4550:     foreach my $role (keys(%allroles)) {
                   4551:         last if ($is_adv);
                   4552:         foreach my $item (split(/:/,$allroles{$role})) {
                   4553:             if ($item ne '') {
                   4554:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4555:                 if ($privilege eq 'adv') {
                   4556:                     $is_adv = 1;
                   4557:                     last;
                   4558:                 }
                   4559:             }
                   4560:         }
                   4561:     }
                   4562:     return $is_adv;
                   4563: }
1.798     raeburn  4564: 
1.341     www      4565: # ---------------------------------------------- Custom access rule evaluation
                   4566: 
                   4567: sub customaccess {
                   4568:     my ($priv,$uri)=@_;
1.807     albertel 4569:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4570:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4571:     $udom = &LONCAPA::clean_domain($udom);
                   4572:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4573:     my $access=0;
1.800     albertel 4574:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4575: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4576: 	if ($type eq 'user') {
                   4577: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4578: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4579: 		if ($tdom) {
                   4580: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4581: 		}
1.896     albertel 4582: 		if ($tuname) {
                   4583: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4584: 		}
                   4585: 		$access=($effect eq 'allow');
                   4586: 		last;
                   4587: 	    }
                   4588: 	} else {
                   4589: 	    if ($role) {
                   4590: 		if ($role ne $urole) { next; }
                   4591: 	    }
                   4592: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4593: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4594: 		if ($tdom) {
                   4595: 		    if ($tdom ne $udom) { next; }
                   4596: 		}
                   4597: 		if ($tcrs) {
                   4598: 		    if ($tcrs ne $ucrs) { next; }
                   4599: 		}
                   4600: 		if ($tsec) {
                   4601: 		    if ($tsec ne $usec) { next; }
                   4602: 		}
                   4603: 		$access=($effect eq 'allow');
                   4604: 		last;
                   4605: 	    }
                   4606: 	    if ($realm eq '' && $role eq '') {
                   4607: 		$access=($effect eq 'allow');
                   4608: 	    }
1.402     bowersj2 4609: 	}
1.341     www      4610:     }
                   4611:     return $access;
                   4612: }
                   4613: 
1.103     harris41 4614: # ------------------------------------------------- Check for a user privilege
1.12      www      4615: 
                   4616: sub allowed {
1.810     raeburn  4617:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4618:     my $ver_orguri=$uri;
1.439     www      4619:     $uri=&deversion($uri);
1.152     www      4620:     my $orguri=$uri;
1.52      www      4621:     $uri=&declutter($uri);
1.809     raeburn  4622: 
1.810     raeburn  4623:     if ($priv eq 'evb') {
                   4624: # Evade communication block restrictions for specified role in a course
                   4625:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4626:             return $1;
                   4627:         } else {
                   4628:             return;
                   4629:         }
                   4630:     }
                   4631: 
1.620     albertel 4632:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4633: # Free bre access to adm and meta resources
1.775     albertel 4634:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4635: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4636: 	&& ($priv eq 'bre')) {
1.14      www      4637: 	return 'F';
1.159     www      4638:     }
                   4639: 
1.545     banghart 4640: # Free bre access to user's own portfolio contents
1.714     raeburn  4641:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4642:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4643: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4644:         my %setters;
                   4645:         my ($startblock,$endblock) = 
                   4646:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4647:         if ($startblock && $endblock) {
                   4648:             return 'B';
                   4649:         } else {
                   4650:             return 'F';
                   4651:         }
1.545     banghart 4652:     }
                   4653: 
1.762     raeburn  4654: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4655:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4656:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4657:         if (exists($env{'request.course.id'})) {
                   4658:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4659:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4660:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4661:                 my $courseprivid=$env{'request.course.id'};
                   4662:                 $courseprivid=~s/\_/\//;
                   4663:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4664:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4665:                     return $1; 
1.762     raeburn  4666:                 } else {
                   4667:                     if ($env{'request.course.sec'}) {
                   4668:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4669:                     }
                   4670:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4671:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4672:                         return $2;
                   4673:                     }
1.714     raeburn  4674:                 }
                   4675:             }
                   4676:         }
                   4677:     }
                   4678: 
1.159     www      4679: # Free bre to public access
                   4680: 
                   4681:     if ($priv eq 'bre') {
1.238     www      4682:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4683: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4684:            return 'F'; 
                   4685:         }
1.238     www      4686:         if ($copyright eq 'priv') {
                   4687:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4688: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4689: 		return '';
                   4690:             }
                   4691:         }
                   4692:         if ($copyright eq 'domain') {
                   4693:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4694: 	    unless (($env{'user.domain'} eq $1) ||
                   4695:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4696: 		return '';
                   4697:             }
1.262     matthew  4698:         }
1.620     albertel 4699:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4700:             # Library role, so allow browsing of resources in this domain.
                   4701:             return 'F';
1.238     www      4702:         }
1.341     www      4703:         if ($copyright eq 'custom') {
                   4704: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4705:         }
1.14      www      4706:     }
1.264     matthew  4707:     # Domain coordinator is trying to create a course
1.620     albertel 4708:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4709:         # uri is the requested domain in this case.
                   4710:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4711:         # a role of dc for the domain in question.
1.620     albertel 4712:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4713:     }
1.29      www      4714: 
1.52      www      4715:     my $thisallowed='';
                   4716:     my $statecond=0;
                   4717:     my $courseprivid='';
                   4718: 
                   4719: # Course
                   4720: 
1.620     albertel 4721:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4722:        $thisallowed.=$1;
                   4723:     }
1.29      www      4724: 
1.52      www      4725: # Domain
                   4726: 
1.620     albertel 4727:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4728:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4729:        $thisallowed.=$1;
                   4730:     }
1.52      www      4731: 
                   4732: # Course: uri itself is a course
1.66      www      4733:     my $courseuri=$uri;
                   4734:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4735:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4736: 
1.620     albertel 4737:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4738:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4739:        $thisallowed.=$1;
                   4740:     }
1.29      www      4741: 
1.665     albertel 4742: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4743: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4744:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4745: 	$thisallowed='';
1.671     raeburn  4746:         my ($match)=&is_on_map($uri);
                   4747:         if ($match) {
                   4748:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4749:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4750:                 $thisallowed.=$1;
                   4751:             }
                   4752:         } else {
1.705     albertel 4753:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4754:             if ($refuri) {
                   4755:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4756:                     $thisallowed='F';
1.671     raeburn  4757:                 } else {
                   4758:                     $refuri=&declutter($refuri);
                   4759:                     my ($match) = &is_on_map($refuri);
                   4760:                     if ($match) {
                   4761:                         $thisallowed='F';
                   4762:                     }
1.669     raeburn  4763:                 }
1.671     raeburn  4764:             }
                   4765:         }
1.314     www      4766:     }
1.492     albertel 4767: 
1.766     albertel 4768:     if ($priv eq 'bre'
                   4769: 	&& $thisallowed ne 'F' 
                   4770: 	&& $thisallowed ne '2'
                   4771: 	&& &is_portfolio_url($uri)) {
                   4772: 	$thisallowed = &portfolio_access($uri);
                   4773:     }
                   4774:     
1.52      www      4775: # Full access at system, domain or course-wide level? Exit.
1.29      www      4776:     if ($thisallowed=~/F/) {
                   4777: 	return 'F';
                   4778:     }
                   4779: 
1.52      www      4780: # If this is generating or modifying users, exit with special codes
1.29      www      4781: 
1.643     www      4782:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4783: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4784: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4785: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4786: 	    unless ($auname) { return $thisallowed; }
                   4787: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4788: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4789: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4790: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4791: 	}
1.52      www      4792: 	return $thisallowed;
                   4793:     }
                   4794: #
1.103     harris41 4795: # Gathered so far: system, domain and course wide privileges
1.52      www      4796: #
                   4797: # Course: See if uri or referer is an individual resource that is part of 
                   4798: # the course
                   4799: 
1.620     albertel 4800:     if ($env{'request.course.id'}) {
1.232     www      4801: 
1.620     albertel 4802:        $courseprivid=$env{'request.course.id'};
                   4803:        if ($env{'request.course.sec'}) {
                   4804:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4805:        }
                   4806:        $courseprivid=~s/\_/\//;
                   4807:        my $checkreferer=1;
1.232     www      4808:        my ($match,$cond)=&is_on_map($uri);
                   4809:        if ($match) {
                   4810:            $statecond=$cond;
1.620     albertel 4811:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4812:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4813:                $thisallowed.=$1;
                   4814:                $checkreferer=0;
                   4815:            }
1.29      www      4816:        }
1.83      www      4817:        
1.148     www      4818:        if ($checkreferer) {
1.620     albertel 4819: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4820:             unless ($refuri) {
1.800     albertel 4821:                 foreach my $key (keys(%env)) {
                   4822: 		    if ($key=~/^httpref\..*\*/) {
                   4823: 			my $pattern=$key;
1.156     www      4824:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4825:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4826:                         $pattern=~s/\//\\\//g;
1.152     www      4827:                         if ($orguri=~/$pattern/) {
1.800     albertel 4828: 			    $refuri=$env{$key};
1.148     www      4829:                         }
                   4830:                     }
1.191     harris41 4831:                 }
1.148     www      4832:             }
1.232     www      4833: 
1.148     www      4834:          if ($refuri) { 
1.152     www      4835: 	  $refuri=&declutter($refuri);
1.232     www      4836:           my ($match,$cond)=&is_on_map($refuri);
                   4837:             if ($match) {
                   4838:               my $refstatecond=$cond;
1.620     albertel 4839:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4840:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4841:                   $thisallowed.=$1;
1.53      www      4842:                   $uri=$refuri;
                   4843:                   $statecond=$refstatecond;
1.52      www      4844:               }
                   4845:           }
1.148     www      4846:         }
1.29      www      4847:        }
1.52      www      4848:    }
1.29      www      4849: 
1.52      www      4850: #
1.103     harris41 4851: # Gathered now: all privileges that could apply, and condition number
1.52      www      4852: # 
                   4853: #
                   4854: # Full or no access?
                   4855: #
1.29      www      4856: 
1.52      www      4857:     if ($thisallowed=~/F/) {
                   4858: 	return 'F';
                   4859:     }
1.29      www      4860: 
1.52      www      4861:     unless ($thisallowed) {
                   4862:         return '';
                   4863:     }
1.29      www      4864: 
1.52      www      4865: # Restrictions exist, deal with them
                   4866: #
                   4867: #   C:according to course preferences
                   4868: #   R:according to resource settings
                   4869: #   L:unless locked
                   4870: #   X:according to user session state
                   4871: #
                   4872: 
                   4873: # Possibly locked functionality, check all courses
1.54      www      4874: # Locks might take effect only after 10 minutes cache expiration for other
                   4875: # courses, and 2 minutes for current course
1.52      www      4876: 
                   4877:     my $envkey;
                   4878:     if ($thisallowed=~/L/) {
1.620     albertel 4879:         foreach $envkey (keys %env) {
1.54      www      4880:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4881:                my $courseid=$2;
                   4882:                my $roleid=$1.'.'.$2;
1.92      www      4883:                $courseid=~s/^\///;
1.54      www      4884:                my $expiretime=600;
1.620     albertel 4885:                if ($env{'request.role'} eq $roleid) {
1.54      www      4886: 		  $expiretime=120;
                   4887:                }
                   4888: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4889:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4890:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4891: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4892:                }
1.620     albertel 4893:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4894:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4895: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4896:                        &log($env{'user.domain'},$env{'user.name'},
                   4897:                             $env{'user.home'},
1.57      www      4898:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4899:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4900:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4901: 		       return '';
                   4902:                    }
                   4903:                }
1.620     albertel 4904:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4905:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4906: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4907:                        &log($env{'user.domain'},$env{'user.name'},
                   4908:                             $env{'user.home'},
1.57      www      4909:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4910:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4911:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4912: 		       return '';
                   4913:                    }
                   4914:                }
                   4915: 	   }
1.29      www      4916:        }
1.52      www      4917:     }
                   4918:    
                   4919: #
                   4920: # Rest of the restrictions depend on selected course
                   4921: #
                   4922: 
1.620     albertel 4923:     unless ($env{'request.course.id'}) {
1.766     albertel 4924: 	if ($thisallowed eq 'A') {
                   4925: 	    return 'A';
1.814     raeburn  4926:         } elsif ($thisallowed eq 'B') {
                   4927:             return 'B';
1.766     albertel 4928: 	} else {
                   4929: 	    return '1';
                   4930: 	}
1.52      www      4931:     }
1.29      www      4932: 
1.52      www      4933: #
                   4934: # Now user is definitely in a course
                   4935: #
1.53      www      4936: 
                   4937: 
                   4938: # Course preferences
                   4939: 
                   4940:    if ($thisallowed=~/C/) {
1.620     albertel 4941:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4942:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4943:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4944: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4945: 	   if ($priv ne 'pch') { 
                   4946: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4947: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4948: 			$env{'request.course.id'});
                   4949: 	   }
1.237     www      4950:            return '';
                   4951:        }
                   4952: 
1.620     albertel 4953:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4954: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4955: 	   if ($priv ne 'pch') { 
                   4956: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4957: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4958: 			$env{'request.course.id'});
                   4959: 	   }
1.54      www      4960:            return '';
                   4961:        }
1.53      www      4962:    }
                   4963: 
                   4964: # Resource preferences
                   4965: 
                   4966:    if ($thisallowed=~/R/) {
1.620     albertel 4967:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4968:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4969: 	   if ($priv ne 'pch') { 
                   4970: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4971: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4972: 	   }
                   4973: 	   return '';
1.54      www      4974:        }
1.53      www      4975:    }
1.30      www      4976: 
1.246     www      4977: # Restricted by state or randomout?
1.30      www      4978: 
1.52      www      4979:    if ($thisallowed=~/X/) {
1.620     albertel 4980:       if ($env{'acc.randomout'}) {
1.579     albertel 4981: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4982:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4983:             return ''; 
                   4984:          }
1.247     www      4985:       }
                   4986:       if (&condval($statecond)) {
1.52      www      4987: 	 return '2';
                   4988:       } else {
                   4989:          return '';
                   4990:       }
                   4991:    }
1.30      www      4992: 
1.766     albertel 4993:     if ($thisallowed eq 'A') {
                   4994: 	return 'A';
1.814     raeburn  4995:     } elsif ($thisallowed eq 'B') {
                   4996:         return 'B';
1.766     albertel 4997:     }
1.52      www      4998:    return 'F';
1.232     www      4999: }
                   5000: 
1.710     albertel 5001: sub split_uri_for_cond {
                   5002:     my $uri=&deversion(&declutter(shift));
                   5003:     my @uriparts=split(/\//,$uri);
                   5004:     my $filename=pop(@uriparts);
                   5005:     my $pathname=join('/',@uriparts);
                   5006:     return ($pathname,$filename);
                   5007: }
1.232     www      5008: # --------------------------------------------------- Is a resource on the map?
                   5009: 
                   5010: sub is_on_map {
1.710     albertel 5011:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5012:     #Trying to find the conditional for the file
1.620     albertel 5013:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5014: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5015:     if ($match) {
1.289     bowersj2 5016: 	return (1,$1);
                   5017:     } else {
1.434     www      5018: 	return (0,0);
1.289     bowersj2 5019:     }
1.12      www      5020: }
                   5021: 
1.427     www      5022: # --------------------------------------------------------- Get symb from alias
                   5023: 
                   5024: sub get_symb_from_alias {
                   5025:     my $symb=shift;
                   5026:     my ($map,$resid,$url)=&decode_symb($symb);
                   5027: # Already is a symb
                   5028:     if ($url) { return $symb; }
                   5029: # Must be an alias
                   5030:     my $aliassymb='';
                   5031:     my %bighash;
1.620     albertel 5032:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5033:                             &GDBM_READER(),0640)) {
                   5034:         my $rid=$bighash{'mapalias_'.$symb};
                   5035: 	if ($rid) {
                   5036: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5037: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5038: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5039: 	}
                   5040:         untie %bighash;
                   5041:     }
                   5042:     return $aliassymb;
                   5043: }
                   5044: 
1.12      www      5045: # ----------------------------------------------------------------- Define Role
                   5046: 
                   5047: sub definerole {
                   5048:   if (allowed('mcr','/')) {
                   5049:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5050:     foreach my $role (split(':',$sysrole)) {
                   5051: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5052:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5053:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5054: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5055:                return "refused:s:$crole&$cqual"; 
                   5056:             }
                   5057:         }
1.191     harris41 5058:     }
1.800     albertel 5059:     foreach my $role (split(':',$domrole)) {
                   5060: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5061:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5062:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5063: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5064:                return "refused:d:$crole&$cqual"; 
                   5065:             }
                   5066:         }
1.191     harris41 5067:     }
1.800     albertel 5068:     foreach my $role (split(':',$courole)) {
                   5069: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5070:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5071:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5072: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5073:                return "refused:c:$crole&$cqual"; 
                   5074:             }
                   5075:         }
1.191     harris41 5076:     }
1.620     albertel 5077:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5078:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5079: 	        "rolesdef_$rolename=".
                   5080:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5081:     return reply($command,$env{'user.home'});
1.12      www      5082:   } else {
                   5083:     return 'refused';
                   5084:   }
1.105     harris41 5085: }
                   5086: 
                   5087: # ---------------- Make a metadata query against the network of library servers
                   5088: 
                   5089: sub metadata_query {
1.244     matthew  5090:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5091:     my %rhash;
1.845     albertel 5092:     my %libserv = &all_library();
1.244     matthew  5093:     my @server_list = (defined($server_array) ? @$server_array
                   5094:                                               : keys(%libserv) );
                   5095:     for my $server (@server_list) {
1.118     harris41 5096: 	unless ($custom or $customshow) {
                   5097: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5098: 	    $rhash{$server}=$reply;
                   5099: 	}
                   5100: 	else {
                   5101: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5102: 			     &escape($custom).':'.&escape($customshow),
                   5103: 			     $server);
                   5104: 	    $rhash{$server}=$reply;
                   5105: 	}
1.112     harris41 5106:     }
1.118     harris41 5107:     return \%rhash;
1.240     www      5108: }
                   5109: 
                   5110: # ----------------------------------------- Send log queries and wait for reply
                   5111: 
                   5112: sub log_query {
                   5113:     my ($uname,$udom,$query,%filters)=@_;
                   5114:     my $uhome=&homeserver($uname,$udom);
                   5115:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5116:     my $uhost=&hostname($uhome);
1.800     albertel 5117:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5118:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5119:                        $uhome);
1.479     albertel 5120:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5121:     return get_query_reply($queryid);
                   5122: }
                   5123: 
1.818     raeburn  5124: # -------------------------- Update MySQL table for portfolio file
                   5125: 
                   5126: sub update_portfolio_table {
1.821     raeburn  5127:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5128:     if ($group ne '') {
                   5129:         $file_name =~s /^\Q$group\E//;
                   5130:     }
1.818     raeburn  5131:     my $homeserver = &homeserver($uname,$udom);
                   5132:     my $queryid=
1.821     raeburn  5133:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5134:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5135:     my $reply = &get_query_reply($queryid);
                   5136:     return $reply;
                   5137: }
                   5138: 
1.899     raeburn  5139: # -------------------------- Update MySQL allusers table
                   5140: 
                   5141: sub update_allusers_table {
                   5142:     my ($uname,$udom,$names) = @_;
                   5143:     my $homeserver = &homeserver($uname,$udom);
                   5144:     my $queryid=
                   5145:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5146:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5147:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5148:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5149:                'generation='.&escape($names->{'generation'}).'%%'.
                   5150:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5151:                'id='.&escape($names->{'id'}),$homeserver);
                   5152:     my $reply = &get_query_reply($queryid);
                   5153:     return $reply;
                   5154: }
                   5155: 
1.508     raeburn  5156: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5157: 
                   5158: sub fetch_enrollment_query {
1.511     raeburn  5159:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5160:     my $homeserver;
1.547     raeburn  5161:     my $maxtries = 1;
1.508     raeburn  5162:     if ($context eq 'automated') {
                   5163:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5164:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5165:     } else {
                   5166:         $homeserver = &homeserver($cnum,$dom);
                   5167:     }
1.838     albertel 5168:     my $host=&hostname($homeserver);
1.506     raeburn  5169:     my $cmd = '';
1.800     albertel 5170:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5171:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5172:     }
                   5173:     $cmd =~ s/%%$//;
                   5174:     $cmd = &escape($cmd);
                   5175:     my $query = 'fetchenrollment';
1.620     albertel 5176:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5177:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5178:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5179:         return 'error: '.$queryid;
                   5180:     }
1.506     raeburn  5181:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5182:     my $tries = 1;
                   5183:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5184:         $reply = &get_query_reply($queryid);
                   5185:         $tries ++;
                   5186:     }
1.526     raeburn  5187:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5188:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5189:     } else {
1.901     albertel 5190:         my @responses = split(/:/,$reply);
1.515     raeburn  5191:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5192:             foreach my $line (@responses) {
                   5193:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5194:                 $$replyref{$key} = $value;
                   5195:             }
                   5196:         } else {
1.506     raeburn  5197:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5198:             foreach my $line (@responses) {
                   5199:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5200:                 $$replyref{$key} = $value;
                   5201:                 if ($value > 0) {
1.800     albertel 5202:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5203:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5204:                         my $destname = $pathname.'/'.$filename;
                   5205:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5206:                         if ($xml_classlist =~ /^error/) {
                   5207:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5208:                         } else {
1.506     raeburn  5209:                             if ( open(FILE,">$destname") ) {
                   5210:                                 print FILE &unescape($xml_classlist);
                   5211:                                 close(FILE);
1.526     raeburn  5212:                             } else {
                   5213:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5214:                             }
                   5215:                         }
                   5216:                     }
                   5217:                 }
                   5218:             }
                   5219:         }
                   5220:         return 'ok';
                   5221:     }
                   5222:     return 'error';
                   5223: }
                   5224: 
1.242     www      5225: sub get_query_reply {
                   5226:     my $queryid=shift;
1.240     www      5227:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5228:     my $reply='';
                   5229:     for (1..100) {
                   5230: 	sleep 2;
                   5231:         if (-e $replyfile.'.end') {
1.448     albertel 5232: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5233: 		$reply = join('',<$fh>);
                   5234: 		close($fh);
1.240     www      5235: 	   } else { return 'error: reply_file_error'; }
1.242     www      5236:            return &unescape($reply);
                   5237: 	}
1.240     www      5238:     }
1.242     www      5239:     return 'timeout:'.$queryid;
1.240     www      5240: }
                   5241: 
                   5242: sub courselog_query {
1.241     www      5243: #
                   5244: # possible filters:
                   5245: # url: url or symb
                   5246: # username
                   5247: # domain
                   5248: # action: view, submit, grade
                   5249: # start: timestamp
                   5250: # end: timestamp
                   5251: #
1.240     www      5252:     my (%filters)=@_;
1.620     albertel 5253:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5254:     if ($filters{'url'}) {
                   5255: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5256:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5257:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5258:     }
1.620     albertel 5259:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5260:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5261:     return &log_query($cname,$cdom,'courselog',%filters);
                   5262: }
                   5263: 
                   5264: sub userlog_query {
1.858     raeburn  5265: #
                   5266: # possible filters:
                   5267: # action: log check role
                   5268: # start: timestamp
                   5269: # end: timestamp
                   5270: #
1.240     www      5271:     my ($uname,$udom,%filters)=@_;
                   5272:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5273: }
                   5274: 
1.506     raeburn  5275: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5276: 
                   5277: sub auto_run {
1.508     raeburn  5278:     my ($cnum,$cdom) = @_;
1.876     raeburn  5279:     my $response = 0;
                   5280:     my $settings;
                   5281:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5282:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5283:         $settings = $domconfig{'autoenroll'};
                   5284:         if ($settings->{'run'} eq '1') {
                   5285:             $response = 1;
                   5286:         }
                   5287:     } else {
1.934     raeburn  5288:         my $homeserver;
                   5289:         if (&is_course($cdom,$cnum)) {
                   5290:             $homeserver = &homeserver($cnum,$cdom);
                   5291:         } else {
                   5292:             $homeserver = &domain($cdom,'primary');
                   5293:         }
                   5294:         if ($homeserver ne 'no_host') {
                   5295:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5296:         }
1.876     raeburn  5297:     }
1.506     raeburn  5298:     return $response;
                   5299: }
1.776     albertel 5300: 
1.506     raeburn  5301: sub auto_get_sections {
1.508     raeburn  5302:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5303:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5304:     my @secs = ();
1.511     raeburn  5305:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5306:     unless ($response eq 'refused') {
1.901     albertel 5307:         @secs = split(/:/,$response);
1.506     raeburn  5308:     }
                   5309:     return @secs;
                   5310: }
1.776     albertel 5311: 
1.506     raeburn  5312: sub auto_new_course {
1.508     raeburn  5313:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5314:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5315:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5316:     return $response;
                   5317: }
1.776     albertel 5318: 
1.506     raeburn  5319: sub auto_validate_courseID {
1.508     raeburn  5320:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5321:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5322:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5323:     return $response;
                   5324: }
1.776     albertel 5325: 
1.506     raeburn  5326: sub auto_create_password {
1.873     raeburn  5327:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5328:     my ($homeserver,$response);
1.506     raeburn  5329:     my $create_passwd = 0;
                   5330:     my $authchk = '';
1.873     raeburn  5331:     if ($udom =~ /^$match_domain$/) {
                   5332:         $homeserver = &domain($udom,'primary');
                   5333:     }
                   5334:     if ($homeserver eq '') {
                   5335:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5336:             $homeserver = &homeserver($cnum,$cdom);
                   5337:         }
                   5338:     }
                   5339:     if ($homeserver eq '') {
                   5340:         $authchk = 'nodomain';
1.506     raeburn  5341:     } else {
1.873     raeburn  5342:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5343:         if ($response eq 'refused') {
                   5344:             $authchk = 'refused';
                   5345:         } else {
1.901     albertel 5346:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5347:         }
1.506     raeburn  5348:     }
                   5349:     return ($authparam,$create_passwd,$authchk);
                   5350: }
                   5351: 
1.706     raeburn  5352: sub auto_photo_permission {
                   5353:     my ($cnum,$cdom,$students) = @_;
                   5354:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5355:     my ($outcome,$perm_reqd,$conditions) = 
                   5356: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5357:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5358: 	return (undef,undef);
                   5359:     }
1.706     raeburn  5360:     return ($outcome,$perm_reqd,$conditions);
                   5361: }
                   5362: 
                   5363: sub auto_checkphotos {
                   5364:     my ($uname,$udom,$pid) = @_;
                   5365:     my $homeserver = &homeserver($uname,$udom);
                   5366:     my ($result,$resulttype);
                   5367:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5368: 				   &escape($uname).':'.&escape($pid),
                   5369: 				   $homeserver));
1.709     albertel 5370:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5371: 	return (undef,undef);
                   5372:     }
1.706     raeburn  5373:     if ($outcome) {
                   5374:         ($result,$resulttype) = split(/:/,$outcome);
                   5375:     } 
                   5376:     return ($result,$resulttype);
                   5377: }
                   5378: 
                   5379: sub auto_photochoice {
                   5380:     my ($cnum,$cdom) = @_;
                   5381:     my $homeserver = &homeserver($cnum,$cdom);
                   5382:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5383: 						       &escape($cdom),
                   5384: 						       $homeserver)));
1.709     albertel 5385:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5386: 	return (undef,undef);
                   5387:     }
1.706     raeburn  5388:     return ($update,$comment);
                   5389: }
                   5390: 
                   5391: sub auto_photoupdate {
                   5392:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5393:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5394:     my $host=&hostname($homeserver);
1.706     raeburn  5395:     my $cmd = '';
                   5396:     my $maxtries = 1;
1.800     albertel 5397:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5398:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5399:     }
                   5400:     $cmd =~ s/%%$//;
                   5401:     $cmd = &escape($cmd);
                   5402:     my $query = 'institutionalphotos';
                   5403:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5404:     unless ($queryid=~/^\Q$host\E\_/) {
                   5405:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5406:         return 'error: '.$queryid;
                   5407:     }
                   5408:     my $reply = &get_query_reply($queryid);
                   5409:     my $tries = 1;
                   5410:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5411:         $reply = &get_query_reply($queryid);
                   5412:         $tries ++;
                   5413:     }
                   5414:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5415:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5416:     } else {
                   5417:         my @responses = split(/:/,$reply);
                   5418:         my $outcome = shift(@responses); 
                   5419:         foreach my $item (@responses) {
                   5420:             my ($key,$value) = split(/=/,$item);
                   5421:             $$photo{$key} = $value;
                   5422:         }
                   5423:         return $outcome;
                   5424:     }
                   5425:     return 'error';
                   5426: }
                   5427: 
1.521     raeburn  5428: sub auto_instcode_format {
1.793     albertel 5429:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5430: 	$cat_order) = @_;
1.521     raeburn  5431:     my $courses = '';
1.772     raeburn  5432:     my @homeservers;
1.521     raeburn  5433:     if ($caller eq 'global') {
1.841     albertel 5434: 	my %servers = &get_servers($codedom,'library');
                   5435: 	foreach my $tryserver (keys(%servers)) {
                   5436: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5437: 		push(@homeservers,$tryserver);
                   5438: 	    }
1.584     raeburn  5439:         }
1.521     raeburn  5440:     } else {
1.772     raeburn  5441:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5442:     }
1.793     albertel 5443:     foreach my $code (keys(%{$instcodes})) {
                   5444:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5445:     }
                   5446:     chop($courses);
1.772     raeburn  5447:     my $ok_response = 0;
                   5448:     my $response;
                   5449:     while (@homeservers > 0 && $ok_response == 0) {
                   5450:         my $server = shift(@homeservers); 
                   5451:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5452:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5453:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5454: 		split(/:/,$response);
1.772     raeburn  5455:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5456:             push(@{$codetitles},&str2array($codetitles_str));
                   5457:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5458:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5459:             $ok_response = 1;
                   5460:         }
                   5461:     }
                   5462:     if ($ok_response) {
1.521     raeburn  5463:         return 'ok';
1.772     raeburn  5464:     } else {
                   5465:         return $response;
1.521     raeburn  5466:     }
                   5467: }
                   5468: 
1.792     raeburn  5469: sub auto_instcode_defaults {
                   5470:     my ($domain,$returnhash,$code_order) = @_;
                   5471:     my @homeservers;
1.841     albertel 5472: 
                   5473:     my %servers = &get_servers($domain,'library');
                   5474:     foreach my $tryserver (keys(%servers)) {
                   5475: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5476: 	    push(@homeservers,$tryserver);
                   5477: 	}
1.792     raeburn  5478:     }
1.841     albertel 5479: 
1.792     raeburn  5480:     my $response;
1.841     albertel 5481:     foreach my $server (@homeservers) {
1.792     raeburn  5482:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5483:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5484: 	
                   5485: 	foreach my $pair (split(/\&/,$response)) {
                   5486: 	    my ($name,$value)=split(/\=/,$pair);
                   5487: 	    if ($name eq 'code_order') {
                   5488: 		@{$code_order} = split(/\&/,&unescape($value));
                   5489: 	    } else {
                   5490: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5491: 	    }
                   5492: 	}
                   5493: 	return 'ok';
1.792     raeburn  5494:     }
1.841     albertel 5495: 
                   5496:     return $response;
1.792     raeburn  5497: } 
                   5498: 
1.777     albertel 5499: sub auto_validate_class_sec {
1.918     raeburn  5500:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5501:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5502:     my $ownerlist;
                   5503:     if (ref($owners) eq 'ARRAY') {
                   5504:         $ownerlist = join(',',@{$owners});
                   5505:     } else {
                   5506:         $ownerlist = $owners;
                   5507:     }
1.773     raeburn  5508:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5509:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5510:     return $response;
                   5511: }
                   5512: 
1.679     raeburn  5513: # ------------------------------------------------------- Course Group routines
                   5514: 
                   5515: sub get_coursegroups {
1.809     raeburn  5516:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5517:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5518: }
                   5519: 
1.679     raeburn  5520: sub modify_coursegroup {
                   5521:     my ($cdom,$cnum,$groupsettings) = @_;
                   5522:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5523: }
                   5524: 
1.809     raeburn  5525: sub toggle_coursegroup_status {
                   5526:     my ($cdom,$cnum,$group,$action) = @_;
                   5527:     my ($from_namespace,$to_namespace);
                   5528:     if ($action eq 'delete') {
                   5529:         $from_namespace = 'coursegroups';
                   5530:         $to_namespace = 'deleted_groups';
                   5531:     } else {
                   5532:         $from_namespace = 'deleted_groups';
                   5533:         $to_namespace = 'coursegroups';
                   5534:     }
                   5535:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5536:     if (my $tmp = &error(%curr_group)) {
                   5537:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5538:         return ('read error',$tmp);
                   5539:     } else {
                   5540:         my %savedsettings = %curr_group; 
1.809     raeburn  5541:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5542:         my $deloutcome;
                   5543:         if ($result eq 'ok') {
1.809     raeburn  5544:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5545:         } else {
                   5546:             return ('write error',$result);
                   5547:         }
                   5548:         if ($deloutcome eq 'ok') {
                   5549:             return 'ok';
                   5550:         } else {
                   5551:             return ('delete error',$deloutcome);
                   5552:         }
                   5553:     }
                   5554: }
                   5555: 
1.679     raeburn  5556: sub modify_group_roles {
1.957     raeburn  5557:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5558:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5559:     my $role = 'gr/'.&escape($userprivs);
                   5560:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5561:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5562:     if ($result eq 'ok') {
                   5563:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5564:     }
1.679     raeburn  5565:     return $result;
                   5566: }
                   5567: 
                   5568: sub modify_coursegroup_membership {
                   5569:     my ($cdom,$cnum,$membership) = @_;
                   5570:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5571:     return $result;
                   5572: }
                   5573: 
1.682     raeburn  5574: sub get_active_groups {
                   5575:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5576:     my $now = time;
                   5577:     my %groups = ();
                   5578:     foreach my $key (keys(%env)) {
1.811     albertel 5579:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5580:             my ($start,$end) = split(/\./,$env{$key});
                   5581:             if (($end!=0) && ($end<$now)) { next; }
                   5582:             if (($start!=0) && ($start>$now)) { next; }
                   5583:             if ($1 eq $cdom && $2 eq $cnum) {
                   5584:                 $groups{$3} = $env{$key} ;
                   5585:             }
                   5586:         }
                   5587:     }
                   5588:     return %groups;
                   5589: }
                   5590: 
1.683     raeburn  5591: sub get_group_membership {
                   5592:     my ($cdom,$cnum,$group) = @_;
                   5593:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5594: }
                   5595: 
                   5596: sub get_users_groups {
                   5597:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5598:     my @usersgroups;
1.683     raeburn  5599:     my $cachetime=1800;
                   5600: 
                   5601:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5602:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5603:     if (defined($cached)) {
1.734     albertel 5604:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5605:     } else {  
                   5606:         $grouplist = '';
1.816     raeburn  5607:         my $courseurl = &courseid_to_courseurl($courseid);
                   5608:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5609:         my $access_end = $env{'course.'.$courseid.
                   5610:                               '.default_enrollment_end_date'};
                   5611:         my $now = time;
                   5612:         foreach my $key (keys(%roleshash)) {
                   5613:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5614:                 my $group = $1;
                   5615:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5616:                     my $start = $2;
                   5617:                     my $end = $1;
                   5618:                     if ($start == -1) { next; } # deleted from group
                   5619:                     if (($start!=0) && ($start>$now)) { next; }
                   5620:                     if (($end!=0) && ($end<$now)) {
                   5621:                         if ($access_end && $access_end < $now) {
                   5622:                             if ($access_end - $end < 86400) {
                   5623:                                 push(@usersgroups,$group);
1.733     raeburn  5624:                             }
                   5625:                         }
1.817     raeburn  5626:                         next;
1.733     raeburn  5627:                     }
1.817     raeburn  5628:                     push(@usersgroups,$group);
1.683     raeburn  5629:                 }
                   5630:             }
                   5631:         }
1.817     raeburn  5632:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5633:         $grouplist = join(':',@usersgroups);
                   5634:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5635:     }
1.733     raeburn  5636:     return @usersgroups;
1.683     raeburn  5637: }
                   5638: 
                   5639: sub devalidate_getgroups_cache {
                   5640:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5641:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5642: 
1.683     raeburn  5643:     my $hashid="$udom:$uname:$courseid";
                   5644:     &devalidate_cache_new('getgroups',$hashid);
                   5645: }
                   5646: 
1.12      www      5647: # ------------------------------------------------------------------ Plain Text
                   5648: 
                   5649: sub plaintext {
1.976.4.2! raeburn  5650:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5651:     if ($short =~ /^cr/) {
                   5652: 	return (split('/',$short))[-1];
                   5653:     }
1.742     raeburn  5654:     if (!defined($cid)) {
                   5655:         $cid = $env{'request.course.id'};
                   5656:     }
1.976.4.2! raeburn  5657:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
        !          5658:         unless ($forcedefault) {
        !          5659:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
        !          5660:             &Apache::lonlocal::mt_escape(\$roletext);
        !          5661:             return &Apache::lonlocal::mt($roletext);
        !          5662:         }
1.742     raeburn  5663:     }
                   5664:     my %rolenames = (
                   5665:                       Course => 'std',
                   5666:                       Group => 'alt1',
                   5667:                     );
                   5668:     if (defined($type) && 
                   5669:          defined($rolenames{$type}) && 
                   5670:          defined($prp{$short}{$rolenames{$type}})) {
                   5671:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5672:     } else {
                   5673:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5674:     }
1.12      www      5675: }
                   5676: 
                   5677: # ----------------------------------------------------------------- Assign Role
                   5678: 
                   5679: sub assignrole {
1.957     raeburn  5680:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5681:         $context)=@_;
1.21      www      5682:     my $mrole;
                   5683:     if ($role =~ /^cr\//) {
1.393     www      5684:         my $cwosec=$url;
1.811     albertel 5685:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5686: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5687:            &logthis('Refused custom assignrole: '.
                   5688:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5689: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5690:            return 'refused'; 
                   5691:         }
1.21      www      5692:         $mrole='cr';
1.678     raeburn  5693:     } elsif ($role =~ /^gr\//) {
                   5694:         my $cwogrp=$url;
1.811     albertel 5695:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5696:         unless (&allowed('mdg',$cwogrp)) {
                   5697:             &logthis('Refused group assignrole: '.
                   5698:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5699:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5700:             return 'refused';
                   5701:         }
                   5702:         $mrole='gr';
1.21      www      5703:     } else {
1.82      www      5704:         my $cwosec=$url;
1.811     albertel 5705:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5706:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5707:             my $refused;
                   5708:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5709:                 if (!(&allowed('c'.$role,$url))) {
                   5710:                     $refused = 1;
                   5711:                 }
                   5712:             } else {
                   5713:                 $refused = 1;
                   5714:             }
1.947     raeburn  5715:             if ($refused) {
                   5716:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5717:                     $refused = '';
                   5718:                 } else {
                   5719:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5720:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5721: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5722:                     return 'refused';
                   5723:                 }
1.932     raeburn  5724:             }
1.104     www      5725:         }
1.21      www      5726:         $mrole=$role;
                   5727:     }
1.620     albertel 5728:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5729:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5730:     if ($end) { $command.='_'.$end; }
1.21      www      5731:     if ($start) {
                   5732: 	if ($end) { 
1.81      www      5733:            $command.='_'.$start; 
1.21      www      5734:         } else {
1.81      www      5735:            $command.='_0_'.$start;
1.21      www      5736:         }
                   5737:     }
1.739     raeburn  5738:     my $origstart = $start;
                   5739:     my $origend = $end;
1.957     raeburn  5740:     my $delflag;
1.357     www      5741: # actually delete
                   5742:     if ($deleteflag) {
1.373     www      5743: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5744: # modify command to delete the role
1.620     albertel 5745:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5746:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5747: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5748: # set start and finish to negative values for userrolelog
                   5749:            $start=-1;
                   5750:            $end=-1;
1.957     raeburn  5751:            $delflag = 1;
1.357     www      5752:         }
                   5753:     }
                   5754: # send command
1.349     www      5755:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5756: # log new user role if status is ok
1.349     www      5757:     if ($answer eq 'ok') {
1.663     raeburn  5758: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5759: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5760:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5761:         unless ($role =~ /^gr/) {
                   5762:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5763:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5764:         }
1.349     www      5765:     }
                   5766:     return $answer;
1.169     harris41 5767: }
                   5768: 
                   5769: # -------------------------------------------------- Modify user authentication
1.197     www      5770: # Overrides without validation
                   5771: 
1.169     harris41 5772: sub modifyuserauth {
                   5773:     my ($udom,$uname,$umode,$upass)=@_;
                   5774:     my $uhome=&homeserver($uname,$udom);
1.197     www      5775:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5776:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5777:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5778:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5779:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5780: 		     &escape($upass),$uhome);
1.620     albertel 5781:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5782:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5783:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5784:     &log($udom,,$uname,$uhome,
1.620     albertel 5785:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5786:                                      $env{'user.name'}.', '.$umode.
1.197     www      5787:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5788:     unless ($reply eq 'ok') {
1.197     www      5789:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5790: 	return 'error: '.$reply;
                   5791:     }   
1.170     harris41 5792:     return 'ok';
1.80      www      5793: }
                   5794: 
1.81      www      5795: # --------------------------------------------------------------- Modify a user
1.80      www      5796: 
1.81      www      5797: sub modifyuser {
1.206     matthew  5798:     my ($udom,    $uname, $uid,
                   5799:         $umode,   $upass, $first,
                   5800:         $middle,  $last,  $gene,
1.963     raeburn  5801:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5802:     $udom= &LONCAPA::clean_domain($udom);
                   5803:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5804:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5805:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5806: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5807:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5808:                                      ' desiredhome not specified'). 
1.620     albertel 5809:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5810:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5811:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5812: # ----------------------------------------------------------------- Create User
1.406     albertel 5813:     if (($uhome eq 'no_host') && 
                   5814: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5815:         my $unhome='';
1.844     albertel 5816:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5817:             $unhome = $desiredhome;
1.620     albertel 5818: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5819: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5820:         } else { # load balancing routine for determining $unhome
1.81      www      5821:             my $loadm=10000000;
1.841     albertel 5822: 	    my %servers = &get_servers($udom,'library');
                   5823: 	    foreach my $tryserver (keys(%servers)) {
                   5824: 		my $answer=reply('load',$tryserver);
                   5825: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5826: 		    $loadm=$answer;
                   5827: 		    $unhome=$tryserver;
                   5828: 		}
1.80      www      5829: 	    }
                   5830:         }
                   5831:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5832: 	    return 'error: unable to find a home server for '.$uname.
                   5833:                    ' in domain '.$udom;
1.80      www      5834:         }
                   5835:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5836:                          &escape($upass),$unhome);
                   5837: 	unless ($reply eq 'ok') {
                   5838:             return 'error: '.$reply;
                   5839:         }   
1.230     stredwic 5840:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5841:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5842: 	    return 'error: unable verify users home machine.';
1.80      www      5843:         }
1.209     matthew  5844:     }   # End of creation of new user
1.80      www      5845: # ---------------------------------------------------------------------- Add ID
                   5846:     if ($uid) {
                   5847:        $uid=~tr/A-Z/a-z/;
                   5848:        my %uidhash=&idrget($udom,$uname);
1.196     www      5849:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5850:          && (!$forceid)) {
1.80      www      5851: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5852: 	      return 'error: user id "'.$uid.'" does not match '.
                   5853:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5854:           }
                   5855:        } else {
                   5856: 	  &idput($udom,($uname => $uid));
                   5857:        }
                   5858:     }
                   5859: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5860:     my @tmp=&get('environment',
1.899     raeburn  5861: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5862:                     'permanentemail','inststatus'],
1.134     albertel 5863: 		   $udom,$uname);
1.313     matthew  5864:     my %names;
                   5865:     if ($tmp[0] =~ m/^error:.*/) { 
                   5866:         %names=(); 
                   5867:     } else {
                   5868:         %names = @tmp;
                   5869:     }
1.388     www      5870: #
                   5871: # Make sure to not trash student environment if instructor does not bother
                   5872: # to supply name and email information
                   5873: #
                   5874:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5875:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5876:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5877:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5878:     if ($email) {
                   5879:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5880:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5881:     }
1.899     raeburn  5882:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5883:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5884:     my $reply = &put('environment', \%names, $udom,$uname);
                   5885:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5886:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5887:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5888:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5889:                  $umode.', '.$first.', '.$middle.', '.
                   5890: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5891:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5892:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5893:     } else {
                   5894:         $logmsg .= ' during self creation';
                   5895:     }
                   5896:     &logthis($logmsg);
1.134     albertel 5897:     return 'ok';
1.80      www      5898: }
                   5899: 
1.81      www      5900: # -------------------------------------------------------------- Modify student
1.80      www      5901: 
1.81      www      5902: sub modifystudent {
                   5903:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5904:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5905:         $selfenroll,$context)=@_;
1.455     albertel 5906:     if (!$cid) {
1.620     albertel 5907: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5908: 	    return 'not_in_class';
                   5909: 	}
1.80      www      5910:     }
                   5911: # --------------------------------------------------------------- Make the user
1.81      www      5912:     my $reply=&modifyuser
1.209     matthew  5913: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5914:          $desiredhome,$email);
1.80      www      5915:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5916:     # This will cause &modify_student_enrollment to get the uid from the
                   5917:     # students environment
                   5918:     $uid = undef if (!$forceid);
1.455     albertel 5919:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5920: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5921:     return $reply;
                   5922: }
                   5923: 
                   5924: sub modify_student_enrollment {
1.957     raeburn  5925:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5926:     my ($cdom,$cnum,$chome);
                   5927:     if (!$cid) {
1.620     albertel 5928: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5929: 	    return 'not_in_class';
                   5930: 	}
1.620     albertel 5931: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5932: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5933:     } else {
                   5934: 	($cdom,$cnum)=split(/_/,$cid);
                   5935:     }
1.620     albertel 5936:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5937:     if (!$chome) {
1.457     raeburn  5938: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5939:     }
1.455     albertel 5940:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5941:     # Make sure the user exists
1.81      www      5942:     my $uhome=&homeserver($uname,$udom);
                   5943:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5944: 	return 'error: no such user';
                   5945:     }
1.297     matthew  5946:     # Get student data if we were not given enough information
                   5947:     if (!defined($first)  || $first  eq '' || 
                   5948:         !defined($last)   || $last   eq '' || 
                   5949:         !defined($uid)    || $uid    eq '' || 
                   5950:         !defined($middle) || $middle eq '' || 
                   5951:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5952:         # They did not supply us with enough data to enroll the student, so
                   5953:         # we need to pick up more information.
1.297     matthew  5954:         my %tmp = &get('environment',
1.294     matthew  5955:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5956:                        ,$udom,$uname);
                   5957: 
1.800     albertel 5958:         #foreach my $key (keys(%tmp)) {
                   5959:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5960:         #}
1.294     matthew  5961:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5962:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5963:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5964:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5965:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5966:     }
1.556     albertel 5967:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5968:     my $reply=cput('classlist',
                   5969: 		   {"$uname:$udom" => 
1.515     raeburn  5970: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5971: 		   $cdom,$cnum);
1.81      www      5972:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5973: 	return 'error: '.$reply;
1.652     albertel 5974:     } else {
                   5975: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5976:     }
1.297     matthew  5977:     # Add student role to user
1.83      www      5978:     my $uurl='/'.$cid;
1.81      www      5979:     $uurl=~s/\_/\//g;
                   5980:     if ($usec) {
                   5981: 	$uurl.='/'.$usec;
                   5982:     }
1.957     raeburn  5983:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5984: }
                   5985: 
1.556     albertel 5986: sub format_name {
                   5987:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5988:     my $name;
                   5989:     if ($first ne 'lastname') {
                   5990: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5991:     } else {
                   5992: 	if ($lastname=~/\S/) {
                   5993: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5994: 	    $name=~s/\s+,/,/;
                   5995: 	} else {
                   5996: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5997: 	}
                   5998:     }
                   5999:     $name=~s/^\s+//;
                   6000:     $name=~s/\s+$//;
                   6001:     $name=~s/\s+/ /g;
                   6002:     return $name;
                   6003: }
                   6004: 
1.84      www      6005: # ------------------------------------------------- Write to course preferences
                   6006: 
                   6007: sub writecoursepref {
                   6008:     my ($courseid,%prefs)=@_;
                   6009:     $courseid=~s/^\///;
                   6010:     $courseid=~s/\_/\//g;
                   6011:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6012:     my $chome=homeserver($cnum,$cdomain);
                   6013:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6014: 	return 'error: no such course';
                   6015:     }
                   6016:     my $cstring='';
1.800     albertel 6017:     foreach my $pref (keys(%prefs)) {
                   6018: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6019:     }
1.84      www      6020:     $cstring=~s/\&$//;
                   6021:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6022: }
                   6023: 
                   6024: # ---------------------------------------------------------- Make/modify course
                   6025: 
                   6026: sub createcourse {
1.741     raeburn  6027:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6028:         $course_owner,$crstype)=@_;
1.84      www      6029:     $url=&declutter($url);
                   6030:     my $cid='';
1.264     matthew  6031:     unless (&allowed('ccc',$udom)) {
1.84      www      6032:         return 'refused';
                   6033:     }
                   6034: # ------------------------------------------------------------------- Create ID
1.674     www      6035:    my $uname=int(1+rand(9)).
                   6036:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6037:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6038:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6039: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6040:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6041:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6042:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6043:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6044:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6045:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6046:            return 'error: unable to generate unique course-ID';
                   6047:        } 
                   6048:    }
1.264     matthew  6049: # ------------------------------------------------ Check supplied server name
1.620     albertel 6050:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6051:     if (! &is_library($course_server)) {
1.264     matthew  6052:         return 'error:bad server name '.$course_server;
                   6053:     }
1.84      www      6054: # ------------------------------------------------------------- Make the course
                   6055:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6056:                       $course_server);
1.84      www      6057:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6058:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6059:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6060: 	return 'error: no such course';
                   6061:     }
1.271     www      6062: # ----------------------------------------------------------------- Course made
1.516     raeburn  6063: # log existence
1.918     raeburn  6064:     my $newcourse = {
                   6065:                     $udom.'_'.$uname => {
1.921     raeburn  6066:                                      description => $description,
                   6067:                                      inst_code   => $inst_code,
                   6068:                                      owner       => $course_owner,
                   6069:                                      type        => $crstype,
1.918     raeburn  6070:                                                 },
                   6071:                     };
1.921     raeburn  6072:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6073: # set toplevel url
1.271     www      6074:     my $topurl=$url;
                   6075:     unless ($nonstandard) {
                   6076: # ------------------------------------------ For standard courses, make top url
                   6077:         my $mapurl=&clutter($url);
1.278     www      6078:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6079:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6080: <map>
                   6081: <resource id="1" type="start"></resource>
                   6082: <resource id="2" src="$mapurl"></resource>
                   6083: <resource id="3" type="finish"></resource>
                   6084: <link index="1" from="1" to="2"></link>
                   6085: <link index="2" from="2" to="3"></link>
                   6086: </map>
                   6087: ENDINITMAP
                   6088:         $topurl=&declutter(
1.638     albertel 6089:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6090:                           );
                   6091:     }
                   6092: # ----------------------------------------------------------- Write preferences
1.84      www      6093:     &writecoursepref($udom.'_'.$uname,
                   6094:                      ('description' => $description,
1.271     www      6095:                       'url'         => $topurl));
1.84      www      6096:     return '/'.$udom.'/'.$uname;
                   6097: }
                   6098: 
1.813     albertel 6099: sub is_course {
                   6100:     my ($cdom,$cnum) = @_;
                   6101:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6102: 				undef,'.');
1.813     albertel 6103:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6104:         return 1;
                   6105:     }
                   6106:     return 0;
                   6107: }
                   6108: 
1.21      www      6109: # ---------------------------------------------------------- Assign Custom Role
                   6110: 
                   6111: sub assigncustomrole {
1.957     raeburn  6112:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6113:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6114:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6115: }
                   6116: 
                   6117: # ----------------------------------------------------------------- Revoke Role
                   6118: 
                   6119: sub revokerole {
1.957     raeburn  6120:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6121:     my $now=time;
1.965     raeburn  6122:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6123: }
                   6124: 
                   6125: # ---------------------------------------------------------- Revoke Custom Role
                   6126: 
                   6127: sub revokecustomrole {
1.957     raeburn  6128:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6129:     my $now=time;
1.357     www      6130:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6131:            $deleteflag,$selfenroll,$context);
1.17      www      6132: }
                   6133: 
1.533     banghart 6134: # ------------------------------------------------------------ Disk usage
1.535     albertel 6135: sub diskusage {
1.955     raeburn  6136:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6137:     $directorypath =~ s/\/$//;
                   6138:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6139:                        .&escape($getpropath).':'.&escape($uname).':'
                   6140:                        .&escape($udom),homeserver($uname,$udom));
                   6141:     if ($listing eq 'unknown_cmd') {
                   6142:         if ($getpropath) {
                   6143:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6144:         }
                   6145:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6146:     }
1.514     albertel 6147:     return $listing;
1.512     banghart 6148: }
                   6149: 
1.566     banghart 6150: sub is_locked {
                   6151:     my ($file_name, $domain, $user) = @_;
                   6152:     my @check;
                   6153:     my $is_locked;
                   6154:     push @check, $file_name;
1.613     albertel 6155:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6156: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6157:     my ($tmp)=keys(%locked);
                   6158:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6159:     
1.566     banghart 6160:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6161:         $is_locked = 'false';
                   6162:         foreach my $entry (@{$locked{$file_name}}) {
                   6163:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6164:                $is_locked = 'true';
                   6165:                last;
1.745     raeburn  6166:            }
                   6167:        }
1.566     banghart 6168:     } else {
                   6169:         $is_locked = 'false';
                   6170:     }
                   6171: }
                   6172: 
1.759     albertel 6173: sub declutter_portfile {
                   6174:     my ($file) = @_;
1.833     albertel 6175:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6176:     return $file;
                   6177: }
                   6178: 
1.559     banghart 6179: # ------------------------------------------------------------- Mark as Read Only
                   6180: 
                   6181: sub mark_as_readonly {
                   6182:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6183:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6184:     my ($tmp)=keys(%current_permissions);
                   6185:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6186:     foreach my $file (@{$files}) {
1.759     albertel 6187: 	$file = &declutter_portfile($file);
1.561     banghart 6188:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6189:     }
1.613     albertel 6190:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6191:     return;
                   6192: }
                   6193: 
1.572     banghart 6194: # ------------------------------------------------------------Save Selected Files
                   6195: 
                   6196: sub save_selected_files {
                   6197:     my ($user, $path, @files) = @_;
                   6198:     my $filename = $user."savedfiles";
1.573     banghart 6199:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6200:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6201:     foreach my $file (@files) {
1.620     albertel 6202:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6203:     }
                   6204:     foreach my $file (@other_files) {
1.574     banghart 6205:         print (OUT $file."\n");
1.572     banghart 6206:     }
1.574     banghart 6207:     close (OUT);
1.572     banghart 6208:     return 'ok';
                   6209: }
                   6210: 
1.574     banghart 6211: sub clear_selected_files {
                   6212:     my ($user) = @_;
                   6213:     my $filename = $user."savedfiles";
                   6214:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6215:     print (OUT undef);
                   6216:     close (OUT);
                   6217:     return ("ok");    
                   6218: }
                   6219: 
1.572     banghart 6220: sub files_in_path {
                   6221:     my ($user, $path) = @_;
                   6222:     my $filename = $user."savedfiles";
                   6223:     my %return_files;
1.574     banghart 6224:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6225:     while (my $line_in = <IN>) {
1.574     banghart 6226:         chomp ($line_in);
                   6227:         my @paths_and_file = split (m!/!, $line_in);
                   6228:         my $file_part = pop (@paths_and_file);
                   6229:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6230:         $path_part.='/';
                   6231:         my $path_and_file = $path_part.$file_part;
                   6232:         if ($path_part eq $path) {
                   6233:             $return_files{$file_part}= 'selected';
                   6234:         }
                   6235:     }
1.574     banghart 6236:     close (IN);
                   6237:     return (\%return_files);
1.572     banghart 6238: }
                   6239: 
                   6240: # called in portfolio select mode, to show files selected NOT in current directory
                   6241: sub files_not_in_path {
                   6242:     my ($user, $path) = @_;
                   6243:     my $filename = $user."savedfiles";
                   6244:     my @return_files;
                   6245:     my $path_part;
1.800     albertel 6246:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6247:     while (my $line = <IN>) {
1.572     banghart 6248:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6249:         my @paths_and_file = split(m|/|, $line);
                   6250:         my $file_part = pop(@paths_and_file);
                   6251:         chomp($file_part);
                   6252:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6253:         $path_part .= '/';
                   6254:         my $path_and_file = $path_part.$file_part;
                   6255:         if ($path_part ne $path) {
1.800     albertel 6256:             push(@return_files, ($path_and_file));
1.572     banghart 6257:         }
                   6258:     }
1.800     albertel 6259:     close(OUT);
1.574     banghart 6260:     return (@return_files);
1.572     banghart 6261: }
                   6262: 
1.745     raeburn  6263: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6264: 
1.745     raeburn  6265: sub get_portfile_permissions {
                   6266:     my ($domain,$user) = @_;
1.613     albertel 6267:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6268:     my ($tmp)=keys(%current_permissions);
                   6269:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6270:     return \%current_permissions;
                   6271: }
                   6272: 
                   6273: #---------------------------------------------Get portfolio file access controls
                   6274: 
1.749     raeburn  6275: sub get_access_controls {
1.745     raeburn  6276:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6277:     my %access;
                   6278:     my $real_file = $file;
                   6279:     $file =~ s/\.meta$//;
1.745     raeburn  6280:     if (defined($file)) {
1.749     raeburn  6281:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6282:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6283:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6284:             }
                   6285:         }
1.745     raeburn  6286:     } else {
1.749     raeburn  6287:         foreach my $key (keys(%{$current_permissions})) {
                   6288:             if ($key =~ /\0accesscontrol$/) {
                   6289:                 if (defined($group)) {
                   6290:                     if ($key !~ m-^\Q$group\E/-) {
                   6291:                         next;
                   6292:                     }
                   6293:                 }
                   6294:                 my ($fullpath) = split(/\0/,$key);
                   6295:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6296:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6297:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6298:                     }
                   6299:                 }
                   6300:             }
                   6301:         }
                   6302:     }
                   6303:     return %access;
                   6304: }
                   6305: 
                   6306: sub modify_access_controls {
                   6307:     my ($file_name,$changes,$domain,$user)=@_;
                   6308:     my ($outcome,$deloutcome);
                   6309:     my %store_permissions;
                   6310:     my %new_values;
                   6311:     my %new_control;
                   6312:     my %translation;
                   6313:     my @deletions = ();
                   6314:     my $now = time;
                   6315:     if (exists($$changes{'activate'})) {
                   6316:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6317:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6318:             my $numnew = scalar(@newitems);
                   6319:             for (my $i=0; $i<$numnew; $i++) {
                   6320:                 my $newkey = $newitems[$i];
                   6321:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6322:                 if ($newkey =~ /^\d+:/) { 
                   6323:                     $newkey =~ s/^(\d+)/$newid/;
                   6324:                     $translation{$1} = $newid;
                   6325:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6326:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6327:                     $translation{$1} = $newid;
                   6328:                 }
1.749     raeburn  6329:                 $new_values{$file_name."\0".$newkey} = 
                   6330:                                           $$changes{'activate'}{$newitems[$i]};
                   6331:                 $new_control{$newkey} = $now;
                   6332:             }
                   6333:         }
                   6334:     }
                   6335:     my %todelete;
                   6336:     my %changed_items;
                   6337:     foreach my $action ('delete','update') {
                   6338:         if (exists($$changes{$action})) {
                   6339:             if (ref($$changes{$action}) eq 'HASH') {
                   6340:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6341:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6342:                     if ($action eq 'delete') { 
                   6343:                         $todelete{$itemnum} = 1;
                   6344:                     } else {
                   6345:                         $changed_items{$itemnum} = $key;
                   6346:                     }
                   6347:                 }
1.745     raeburn  6348:             }
                   6349:         }
1.749     raeburn  6350:     }
                   6351:     # get lock on access controls for file.
                   6352:     my $lockhash = {
                   6353:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6354:                                                        ':'.$env{'user.domain'},
                   6355:                    }; 
                   6356:     my $tries = 0;
                   6357:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6358:    
                   6359:     while (($gotlock ne 'ok') && $tries <3) {
                   6360:         $tries ++;
                   6361:         sleep 1;
                   6362:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6363:     }
                   6364:     if ($gotlock eq 'ok') {
                   6365:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6366:         my ($tmp)=keys(%curr_permissions);
                   6367:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6368:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6369:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6370:             if (ref($curr_controls) eq 'HASH') {
                   6371:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6372:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6373:                     if (defined($todelete{$itemnum})) {
                   6374:                         push(@deletions,$file_name."\0".$control_item);
                   6375:                     } else {
                   6376:                         if (defined($changed_items{$itemnum})) {
                   6377:                             $new_control{$changed_items{$itemnum}} = $now;
                   6378:                             push(@deletions,$file_name."\0".$control_item);
                   6379:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6380:                         } else {
                   6381:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6382:                         }
                   6383:                     }
1.745     raeburn  6384:                 }
                   6385:             }
                   6386:         }
1.970     raeburn  6387:         my ($group);
                   6388:         if (&is_course($domain,$user)) {
                   6389:             ($group,my $file) = split(/\//,$file_name,2);
                   6390:         }
1.749     raeburn  6391:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6392:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6393:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6394:         #  remove lock
                   6395:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6396:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6397:         my $sqlresult =
1.970     raeburn  6398:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6399:                                     $group);
1.749     raeburn  6400:     } else {
                   6401:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6402:     }
1.749     raeburn  6403:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6404: }
                   6405: 
1.827     raeburn  6406: sub make_public_indefinitely {
                   6407:     my ($requrl) = @_;
                   6408:     my $now = time;
                   6409:     my $action = 'activate';
                   6410:     my $aclnum = 0;
                   6411:     if (&is_portfolio_url($requrl)) {
                   6412:         my (undef,$udom,$unum,$file_name,$group) =
                   6413:             &parse_portfolio_url($requrl);
                   6414:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6415:         my %access_controls = &get_access_controls($current_perms,
                   6416:                                                    $group,$file_name);
                   6417:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6418:             my ($num,$scope,$end,$start) = 
                   6419:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6420:             if ($scope eq 'public') {
                   6421:                 if ($start <= $now && $end == 0) {
                   6422:                     $action = 'none';
                   6423:                 } else {
                   6424:                     $action = 'update';
                   6425:                     $aclnum = $num;
                   6426:                 }
                   6427:                 last;
                   6428:             }
                   6429:         }
                   6430:         if ($action eq 'none') {
                   6431:              return 'ok';
                   6432:         } else {
                   6433:             my %changes;
                   6434:             my $newend = 0;
                   6435:             my $newstart = $now;
                   6436:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6437:             $changes{$action}{$newkey} = {
                   6438:                 type => 'public',
                   6439:                 time => {
                   6440:                     start => $newstart,
                   6441:                     end   => $newend,
                   6442:                 },
                   6443:             };
                   6444:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6445:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6446:             return $outcome;
                   6447:         }
                   6448:     } else {
                   6449:         return 'invalid';
                   6450:     }
                   6451: }
                   6452: 
1.745     raeburn  6453: #------------------------------------------------------Get Marked as Read Only
                   6454: 
                   6455: sub get_marked_as_readonly {
                   6456:     my ($domain,$user,$what,$group) = @_;
                   6457:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6458:     my @readonly_files;
1.629     banghart 6459:     my $cmp1=$what;
                   6460:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6461:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6462:         if (defined($group)) {
                   6463:             if ($file_name !~ m-^\Q$group\E/-) {
                   6464:                 next;
                   6465:             }
                   6466:         }
1.561     banghart 6467:         if (ref($value) eq "ARRAY"){
                   6468:             foreach my $stored_what (@{$value}) {
1.629     banghart 6469:                 my $cmp2=$stored_what;
1.759     albertel 6470:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6471:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6472:                 }
1.629     banghart 6473:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6474:                     push(@readonly_files, $file_name);
1.745     raeburn  6475:                     last;
1.563     banghart 6476:                 } elsif (!defined($what)) {
                   6477:                     push(@readonly_files, $file_name);
1.745     raeburn  6478:                     last;
1.561     banghart 6479:                 }
                   6480:             }
1.745     raeburn  6481:         }
1.561     banghart 6482:     }
                   6483:     return @readonly_files;
                   6484: }
1.577     banghart 6485: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6486: 
1.577     banghart 6487: sub get_marked_as_readonly_hash {
1.745     raeburn  6488:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6489:     my %readonly_files;
1.745     raeburn  6490:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6491:         if (defined($group)) {
                   6492:             if ($file_name !~ m-^\Q$group\E/-) {
                   6493:                 next;
                   6494:             }
                   6495:         }
1.577     banghart 6496:         if (ref($value) eq "ARRAY"){
                   6497:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6498:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6499:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6500:                         if ($lock_descriptor eq 'graded') {
                   6501:                             $readonly_files{$file_name} = 'graded';
                   6502:                         } elsif ($lock_descriptor eq 'handback') {
                   6503:                             $readonly_files{$file_name} = 'handback';
                   6504:                         } else {
                   6505:                             if (!exists($readonly_files{$file_name})) {
                   6506:                                 $readonly_files{$file_name} = 'locked';
                   6507:                             }
                   6508:                         }
1.745     raeburn  6509:                     }
1.750     banghart 6510:                 } 
1.577     banghart 6511:             }
                   6512:         } 
                   6513:     }
                   6514:     return %readonly_files;
                   6515: }
1.559     banghart 6516: # ------------------------------------------------------------ Unmark as Read Only
                   6517: 
                   6518: sub unmark_as_readonly {
1.629     banghart 6519:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6520:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6521:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6522:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6523:     my $symb_crs = $what;
                   6524:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6525:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6526:     my ($tmp)=keys(%current_permissions);
                   6527:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6528:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6529:     foreach my $file (@readonly_files) {
1.759     albertel 6530: 	my $clean_file = &declutter_portfile($file);
                   6531: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6532: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6533:         my @new_locks;
                   6534:         my @del_keys;
                   6535:         if (ref($current_locks) eq "ARRAY"){
                   6536:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6537:                 my $compare=$locker;
1.749     raeburn  6538:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6539:                     $compare=join('',@{$locker});
1.746     raeburn  6540:                     if ($compare ne $symb_crs) {
                   6541:                         push(@new_locks, $locker);
                   6542:                     }
1.563     banghart 6543:                 }
                   6544:             }
1.650     albertel 6545:             if (scalar(@new_locks) > 0) {
1.563     banghart 6546:                 $current_permissions{$file} = \@new_locks;
                   6547:             } else {
                   6548:                 push(@del_keys, $file);
1.613     albertel 6549:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6550:                 delete($current_permissions{$file});
1.563     banghart 6551:             }
                   6552:         }
1.561     banghart 6553:     }
1.613     albertel 6554:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6555:     return;
                   6556: }
1.512     banghart 6557: 
1.17      www      6558: # ------------------------------------------------------------ Directory lister
                   6559: 
                   6560: sub dirlist {
1.955     raeburn  6561:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6562:     $uri=~s/^\///;
                   6563:     $uri=~s/\/$//;
1.253     stredwic 6564:     my ($udom, $uname);
1.955     raeburn  6565:     if ($getuserdir) {
1.253     stredwic 6566:         $udom = $userdomain;
                   6567:         $uname = $username;
1.955     raeburn  6568:     } else {
                   6569:         (undef,$udom,$uname)=split(/\//,$uri);
                   6570:         if(defined($userdomain)) {
                   6571:             $udom = $userdomain;
                   6572:         }
                   6573:         if(defined($username)) {
                   6574:             $uname = $username;
                   6575:         }
1.253     stredwic 6576:     }
1.955     raeburn  6577:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6578: 
1.955     raeburn  6579:     $dirRoot = $perlvar{'lonDocRoot'};
                   6580:     if (defined($getpropath)) {
                   6581:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6582:         $dirRoot =~ s/\/$//;
1.955     raeburn  6583:     } elsif (defined($getuserdir)) {
                   6584:         my $subdir=$uname.'__';
                   6585:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6586:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6587:                    ."/$udom/$subdir/$uname";
                   6588:     } elsif (defined($alternateRoot)) {
                   6589:         $dirRoot = $alternateRoot;
1.751     banghart 6590:     }
1.253     stredwic 6591: 
                   6592:     if($udom) {
                   6593:         if($uname) {
1.955     raeburn  6594:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6595:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6596:                               .':'.&escape($uname).':'.&escape($udom),
                   6597:                               &homeserver($uname,$udom));
                   6598:             if ($listing eq 'unknown_cmd') {
                   6599:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6600:                                   &homeserver($uname,$udom));
                   6601:             } else {
                   6602:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6603:             }
1.605     matthew  6604:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6605:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6606: 				  &homeserver($uname,$udom));
1.605     matthew  6607:                 @listing_results = split(/:/,$listing);
                   6608:             } else {
                   6609:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6610:             }
                   6611:             return @listing_results;
1.955     raeburn  6612:         } elsif(!$alternateRoot) {
1.800     albertel 6613:             my %allusers;
1.841     albertel 6614: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6615:  	    foreach my $tryserver (keys(%servers)) {
                   6616:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6617:                                   &escape($udom),$tryserver);
                   6618:                 if ($listing eq 'unknown_cmd') {
                   6619: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6620: 				      $udom, $tryserver);
                   6621:                 } else {
                   6622:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6623:                 }
1.841     albertel 6624: 		if ($listing eq 'unknown_cmd') {
                   6625: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6626: 				      $udom, $tryserver);
                   6627: 		    @listing_results = split(/:/,$listing);
                   6628: 		} else {
                   6629: 		    @listing_results =
                   6630: 			map { &unescape($_); } split(/:/,$listing);
                   6631: 		}
                   6632: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6633: 		    $listing_results[0] ne 'empty'       &&
                   6634: 		    $listing_results[0] ne 'con_lost') {
                   6635: 		    foreach my $line (@listing_results) {
                   6636: 			my ($entry) = split(/&/,$line,2);
                   6637: 			$allusers{$entry} = 1;
                   6638: 		    }
                   6639: 		}
1.253     stredwic 6640:             }
                   6641:             my $alluserstr='';
1.800     albertel 6642:             foreach my $user (sort(keys(%allusers))) {
                   6643:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6644:             }
                   6645:             $alluserstr=~s/:$//;
                   6646:             return split(/:/,$alluserstr);
                   6647:         } else {
1.800     albertel 6648:             return ('missing user name');
1.253     stredwic 6649:         }
1.955     raeburn  6650:     } elsif(!defined($getpropath)) {
1.841     albertel 6651:         my @all_domains = sort(&all_domains());
1.955     raeburn  6652:         foreach my $domain (@all_domains) {
                   6653:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6654:         }
                   6655:         return @all_domains;
                   6656:     } else {
1.800     albertel 6657:         return ('missing domain');
1.275     stredwic 6658:     }
                   6659: }
                   6660: 
                   6661: # --------------------------------------------- GetFileTimestamp
                   6662: # This function utilizes dirlist and returns the date stamp for
                   6663: # when it was last modified.  It will also return an error of -1
                   6664: # if an error occurs
                   6665: 
                   6666: sub GetFileTimestamp {
1.955     raeburn  6667:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6668:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6669:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6670:     my ($fileStat) = 
                   6671:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6672:                                  undef,$getuserdir);
1.275     stredwic 6673:     my @stats = split('&', $fileStat);
                   6674:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6675:         # @stats contains first the filename, then the stat output
                   6676:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6677:     } else {
                   6678:         return -1;
1.253     stredwic 6679:     }
1.26      www      6680: }
                   6681: 
1.712     albertel 6682: sub stat_file {
                   6683:     my ($uri) = @_;
1.787     albertel 6684:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6685: 
1.955     raeburn  6686:     my ($udom,$uname,$file);
1.712     albertel 6687:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6688: 	($udom,$uname,$file) =
1.811     albertel 6689: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6690: 	$file = 'userfiles/'.$file;
                   6691:     }
                   6692:     if ($uri =~ m-^/res/-) {
                   6693: 	($udom,$uname) = 
1.807     albertel 6694: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6695: 	$file = $uri;
                   6696:     }
                   6697: 
                   6698:     if (!$udom || !$uname || !$file) {
                   6699: 	# unable to handle the uri
                   6700: 	return ();
                   6701:     }
1.956     raeburn  6702:     my $getpropath;
                   6703:     if ($file =~ /^userfiles\//) {
                   6704:         $getpropath = 1;
                   6705:     }
1.955     raeburn  6706:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6707:     my @stats = split('&', $result);
1.721     banghart 6708:     
1.712     albertel 6709:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6710: 	shift(@stats); #filename is first
                   6711: 	return @stats;
                   6712:     }
                   6713:     return ();
                   6714: }
                   6715: 
1.26      www      6716: # -------------------------------------------------------- Value of a Condition
                   6717: 
1.713     albertel 6718: # gets the value of a specific preevaluated condition
                   6719: #    stored in the string  $env{user.state.<cid>}
                   6720: # or looks up a condition reference in the bighash and if if hasn't
                   6721: # already been evaluated recurses into docondval to get the value of
                   6722: # the condition, then memoizing it to 
                   6723: #   $env{user.state.<cid>.<condition>}
1.40      www      6724: sub directcondval {
                   6725:     my $number=shift;
1.620     albertel 6726:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6727: 	&Apache::lonuserstate::evalstate();
                   6728:     }
1.713     albertel 6729:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6730: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6731:     } elsif ($number =~ /^_/) {
                   6732: 	my $sub_condition;
                   6733: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6734: 		&GDBM_READER(),0640)) {
                   6735: 	    $sub_condition=$bighash{'conditions'.$number};
                   6736: 	    untie(%bighash);
                   6737: 	}
                   6738: 	my $value = &docondval($sub_condition);
1.949     raeburn  6739: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6740: 	return $value;
                   6741:     }
1.620     albertel 6742:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6743:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6744:     } else {
                   6745:        return 2;
                   6746:     }
                   6747: }
                   6748: 
1.713     albertel 6749: # get the collection of conditions for this resource
1.26      www      6750: sub condval {
                   6751:     my $condidx=shift;
1.54      www      6752:     my $allpathcond='';
1.713     albertel 6753:     foreach my $cond (split(/\|/,$condidx)) {
                   6754: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6755: 	    $allpathcond.=
                   6756: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6757: 	}
1.191     harris41 6758:     }
1.54      www      6759:     $allpathcond=~s/\|$//;
1.713     albertel 6760:     return &docondval($allpathcond);
                   6761: }
                   6762: 
                   6763: #evaluates an expression of conditions
                   6764: sub docondval {
                   6765:     my ($allpathcond) = @_;
                   6766:     my $result=0;
                   6767:     if ($env{'request.course.id'}
                   6768: 	&& defined($allpathcond)) {
                   6769: 	my $operand='|';
                   6770: 	my @stack;
                   6771: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6772: 	    if ($chunk eq '(') {
                   6773: 		push @stack,($operand,$result);
                   6774: 	    } elsif ($chunk eq ')') {
                   6775: 		my $before=pop @stack;
                   6776: 		if (pop @stack eq '&') {
                   6777: 		    $result=$result>$before?$before:$result;
                   6778: 		} else {
                   6779: 		    $result=$result>$before?$result:$before;
                   6780: 		}
                   6781: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6782: 		$operand=$chunk;
                   6783: 	    } else {
                   6784: 		my $new=directcondval($chunk);
                   6785: 		if ($operand eq '&') {
                   6786: 		    $result=$result>$new?$new:$result;
                   6787: 		} else {
                   6788: 		    $result=$result>$new?$result:$new;
                   6789: 		}
                   6790: 	    }
                   6791: 	}
1.26      www      6792:     }
                   6793:     return $result;
1.421     albertel 6794: }
                   6795: 
                   6796: # ---------------------------------------------------- Devalidate courseresdata
                   6797: 
                   6798: sub devalidatecourseresdata {
                   6799:     my ($coursenum,$coursedomain)=@_;
                   6800:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6801:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6802: }
                   6803: 
1.763     www      6804: 
1.200     www      6805: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6806: #
                   6807: #  Parameters:
                   6808: #      $coursenum    - Number of the course.
                   6809: #      $coursedomain - Domain at which the course was created.
                   6810: #  Returns:
                   6811: #     A hash of the course parameters along (I think) with timestamps
                   6812: #     and version info.
1.877     foxr     6813: 
1.624     albertel 6814: sub get_courseresdata {
                   6815:     my ($coursenum,$coursedomain)=@_;
1.200     www      6816:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6817:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6818:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6819:     my %dumpreply;
1.417     albertel 6820:     unless (defined($cached)) {
1.624     albertel 6821: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6822: 	$result=\%dumpreply;
1.251     albertel 6823: 	my ($tmp) = keys(%dumpreply);
                   6824: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6825: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6826: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6827: 	    return $tmp;
1.416     albertel 6828: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6829: 	    $result=undef;
1.599     albertel 6830: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6831: 	}
                   6832:     }
1.624     albertel 6833:     return $result;
                   6834: }
                   6835: 
1.633     albertel 6836: sub devalidateuserresdata {
                   6837:     my ($uname,$udom)=@_;
                   6838:     my $hashid="$udom:$uname";
                   6839:     &devalidate_cache_new('userres',$hashid);
                   6840: }
                   6841: 
1.624     albertel 6842: sub get_userresdata {
                   6843:     my ($uname,$udom)=@_;
                   6844:     #most student don\'t have any data set, check if there is some data
                   6845:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6846: 
                   6847:     my $hashid="$udom:$uname";
                   6848:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6849:     if (!defined($cached)) {
                   6850: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6851: 	$result=\%resourcedata;
                   6852: 	&do_cache_new('userres',$hashid,$result,600);
                   6853:     }
                   6854:     my ($tmp)=keys(%$result);
                   6855:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6856: 	return $result;
                   6857:     }
                   6858:     #error 2 occurs when the .db doesn't exist
                   6859:     if ($tmp!~/error: 2 /) {
1.672     albertel 6860: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6861: 		 " Trying to get resource data for ".
                   6862: 		 $uname." at ".$udom.": ".
                   6863: 		 $tmp."</font>");
                   6864:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6865: 	#&EXT_cache_set($udom,$uname);
                   6866: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6867: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6868:     }
                   6869:     return $tmp;
                   6870: }
1.879     foxr     6871: #----------------------------------------------- resdata - return resource data
                   6872: #  Purpose:
                   6873: #    Return resource data for either users or for a course.
                   6874: #  Parameters:
                   6875: #     $name      - Course/user name.
                   6876: #     $domain    - Name of the domain the user/course is registered on.
                   6877: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6878: #     @which     - Array of names of resources desired.
                   6879: #  Returns:
                   6880: #     The value of the first reasource in @which that is found in the
                   6881: #     resource hash.
                   6882: #  Exceptional Conditions:
                   6883: #     If the $type passed in is not valid (not the string 'course' or 
                   6884: #     'user', an undefined  reference is returned.
                   6885: #     If none of the resources are found, an undef is returned
1.624     albertel 6886: sub resdata {
                   6887:     my ($name,$domain,$type,@which)=@_;
                   6888:     my $result;
                   6889:     if ($type eq 'course') {
                   6890: 	$result=&get_courseresdata($name,$domain);
                   6891:     } elsif ($type eq 'user') {
                   6892: 	$result=&get_userresdata($name,$domain);
                   6893:     }
                   6894:     if (!ref($result)) { return $result; }    
1.251     albertel 6895:     foreach my $item (@which) {
1.927     albertel 6896: 	if (defined($result->{$item->[0]})) {
                   6897: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6898: 	}
1.250     albertel 6899:     }
1.291     albertel 6900:     return undef;
1.200     www      6901: }
                   6902: 
1.379     matthew  6903: #
                   6904: # EXT resource caching routines
                   6905: #
                   6906: 
                   6907: sub clear_EXT_cache_status {
1.383     albertel 6908:     &delenv('cache.EXT.');
1.379     matthew  6909: }
                   6910: 
                   6911: sub EXT_cache_status {
                   6912:     my ($target_domain,$target_user) = @_;
1.383     albertel 6913:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6914:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6915:         # We know already the user has no data
                   6916:         return 1;
                   6917:     } else {
                   6918:         return 0;
                   6919:     }
                   6920: }
                   6921: 
                   6922: sub EXT_cache_set {
                   6923:     my ($target_domain,$target_user) = @_;
1.383     albertel 6924:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6925:     #&appenv({$cachename => time});
1.379     matthew  6926: }
                   6927: 
1.28      www      6928: # --------------------------------------------------------- Value of a Variable
1.58      www      6929: sub EXT {
1.715     albertel 6930: 
1.395     albertel 6931:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6932:     unless ($varname) { return ''; }
1.218     albertel 6933:     #get real user name/domain, courseid and symb
                   6934:     my $courseid;
1.359     albertel 6935:     my $publicuser;
1.427     www      6936:     if ($symbparm) {
                   6937: 	$symbparm=&get_symb_from_alias($symbparm);
                   6938:     }
1.218     albertel 6939:     if (!($uname && $udom)) {
1.790     albertel 6940:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6941:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6942:     } else {
1.620     albertel 6943: 	$courseid=$env{'request.course.id'};
1.218     albertel 6944:     }
1.48      www      6945:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6946:     my $rest;
1.320     albertel 6947:     if (defined($therest[0])) {
1.48      www      6948:        $rest=join('.',@therest);
                   6949:     } else {
                   6950:        $rest='';
                   6951:     }
1.320     albertel 6952: 
1.57      www      6953:     my $qualifierrest=$qualifier;
                   6954:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6955:     my $spacequalifierrest=$space;
                   6956:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6957:     if ($realm eq 'user') {
1.48      www      6958: # --------------------------------------------------------------- user.resource
                   6959: 	if ($space eq 'resource') {
1.651     albertel 6960: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6961: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6962: 		 &&
1.744     albertel 6963: 		 ($symbparm eq &symbread()) ) {	
                   6964: 		# if we are in the middle of processing the resource the
                   6965: 		# get the value we are planning on committing
                   6966:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6967:                     return $Apache::lonhomework::results{$qualifierrest};
                   6968:                 } else {
                   6969:                     return $Apache::lonhomework::history{$qualifierrest};
                   6970:                 }
1.335     albertel 6971: 	    } else {
1.359     albertel 6972: 		my %restored;
1.620     albertel 6973: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6974: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6975: 		} else {
                   6976: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6977: 		}
1.335     albertel 6978: 		return $restored{$qualifierrest};
                   6979: 	    }
1.48      www      6980: # ----------------------------------------------------------------- user.access
                   6981:         } elsif ($space eq 'access') {
1.218     albertel 6982: 	    # FIXME - not supporting calls for a specific user
1.48      www      6983:             return &allowed($qualifier,$rest);
                   6984: # ------------------------------------------ user.preferences, user.environment
                   6985:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6986: 	    if (($uname eq $env{'user.name'}) &&
                   6987: 		($udom eq $env{'user.domain'})) {
                   6988: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6989: 	    } else {
1.359     albertel 6990: 		my %returnhash;
                   6991: 		if (!$publicuser) {
                   6992: 		    %returnhash=&userenvironment($udom,$uname,
                   6993: 						 $qualifierrest);
                   6994: 		}
1.218     albertel 6995: 		return $returnhash{$qualifierrest};
                   6996: 	    }
1.48      www      6997: # ----------------------------------------------------------------- user.course
                   6998:         } elsif ($space eq 'course') {
1.218     albertel 6999: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7000:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7001: # ------------------------------------------------------------------- user.role
                   7002:         } elsif ($space eq 'role') {
1.218     albertel 7003: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7004:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7005:             if ($qualifier eq 'value') {
                   7006: 		return $role;
                   7007:             } elsif ($qualifier eq 'extent') {
                   7008:                 return $where;
                   7009:             }
                   7010: # ----------------------------------------------------------------- user.domain
                   7011:         } elsif ($space eq 'domain') {
1.218     albertel 7012:             return $udom;
1.48      www      7013: # ------------------------------------------------------------------- user.name
                   7014:         } elsif ($space eq 'name') {
1.218     albertel 7015:             return $uname;
1.48      www      7016: # ---------------------------------------------------- Any other user namespace
1.29      www      7017:         } else {
1.359     albertel 7018: 	    my %reply;
                   7019: 	    if (!$publicuser) {
                   7020: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7021: 	    }
                   7022: 	    return $reply{$qualifierrest};
1.48      www      7023:         }
1.236     www      7024:     } elsif ($realm eq 'query') {
                   7025: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7026:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7027: 						[$spacequalifierrest]);
1.620     albertel 7028: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7029:    } elsif ($realm eq 'request') {
1.48      www      7030: # ------------------------------------------------------------- request.browser
                   7031:         if ($space eq 'browser') {
1.430     www      7032: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7033: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7034: 		    return 1;
                   7035: 		} else {
                   7036: 		    return 0;
                   7037: 		}
                   7038: 	    } else {
1.620     albertel 7039: 		return $env{'browser.'.$qualifier};
1.430     www      7040: 	    }
1.57      www      7041: # ------------------------------------------------------------ request.filename
                   7042:         } else {
1.620     albertel 7043:             return $env{'request.'.$spacequalifierrest};
1.29      www      7044:         }
1.28      www      7045:     } elsif ($realm eq 'course') {
1.48      www      7046: # ---------------------------------------------------------- course.description
1.620     albertel 7047:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7048:     } elsif ($realm eq 'resource') {
1.165     www      7049: 
1.620     albertel 7050: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7051: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7052: 	}
1.693     albertel 7053: 
                   7054: 	if ($space eq 'title') {
                   7055: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7056: 	    return &gettitle($symbparm);
                   7057: 	}
                   7058: 	
                   7059: 	if ($space eq 'map') {
                   7060: 	    my ($map) = &decode_symb($symbparm);
                   7061: 	    return &symbread($map);
                   7062: 	}
1.905     albertel 7063: 	if ($space eq 'filename') {
                   7064: 	    if ($symbparm) {
                   7065: 		return &clutter((&decode_symb($symbparm))[2]);
                   7066: 	    }
                   7067: 	    return &hreflocation('',$env{'request.filename'});
                   7068: 	}
1.693     albertel 7069: 
                   7070: 	my ($section, $group, @groups);
1.593     albertel 7071: 	my ($courselevelm,$courselevel);
1.539     albertel 7072: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7073: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7074: 
1.218     albertel 7075: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7076: 
1.60      www      7077: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7078: 	    my $symbp=$symbparm;
1.735     albertel 7079: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7080: 
                   7081: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7082: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7083: 
1.620     albertel 7084: 	    if (($env{'user.name'} eq $uname) &&
                   7085: 		($env{'user.domain'} eq $udom)) {
                   7086: 		$section=$env{'request.course.sec'};
1.733     raeburn  7087:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7088:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7089: 	    } else {
1.539     albertel 7090: 		if (! defined($usection)) {
1.551     albertel 7091: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7092: 		} else {
                   7093: 		    $section = $usection;
                   7094: 		}
1.733     raeburn  7095:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7096: 	    }
                   7097: 
                   7098: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7099: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7100: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7101: 
1.593     albertel 7102: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7103: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7104: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7105: 
1.60      www      7106: # ----------------------------------------------------------- first, check user
1.624     albertel 7107: 
                   7108: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7109: 				       ([$courselevelr,'resource'],
                   7110: 					[$courselevelm,'map'     ],
                   7111: 					[$courselevel, 'course'  ]));
1.931     albertel 7112: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7113: 
1.594     albertel 7114: # ------------------------------------------------ second, check some of course
1.684     raeburn  7115:             my $coursereply;
1.691     raeburn  7116:             if (@groups > 0) {
                   7117:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7118:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7119:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7120:             }
1.96      www      7121: 
1.684     raeburn  7122: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7123: 				  $env{'course.'.$courseid.'.domain'},
                   7124: 				  'course',
                   7125: 				  ([$seclevelr,   'resource'],
                   7126: 				   [$seclevelm,   'map'     ],
                   7127: 				   [$seclevel,    'course'  ],
                   7128: 				   [$courselevelr,'resource']));
                   7129: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7130: 
1.60      www      7131: # ------------------------------------------------------ third, check map parms
1.218     albertel 7132: 	    my %parmhash=();
                   7133: 	    my $thisparm='';
                   7134: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7135: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7136: 		    &GDBM_READER(),0640)) {
1.218     albertel 7137: 		$thisparm=$parmhash{$symbparm};
                   7138: 		untie(%parmhash);
                   7139: 	    }
1.927     albertel 7140: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7141: 	}
1.594     albertel 7142: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7143: 
1.218     albertel 7144: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7145: 	my $filename;
                   7146: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7147: 	if ($symbparm) {
1.409     www      7148: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7149: 	} else {
1.620     albertel 7150: 	    $filename=$env{'request.filename'};
1.282     albertel 7151: 	}
                   7152: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7153: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7154: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7155: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7156: 
1.927     albertel 7157: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7158: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7159: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7160: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7161: 				     $env{'course.'.$courseid.'.domain'},
                   7162: 				     'course',
1.927     albertel 7163: 				     ([$courselevelm,'map'   ],
                   7164: 				      [$courselevel, 'course']));
                   7165: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7166: 	}
1.145     www      7167: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7168: 	unless ($space eq '0') {
1.336     albertel 7169: 	    my @parts=split(/_/,$space);
                   7170: 	    my $id=pop(@parts);
                   7171: 	    my $part=join('_',@parts);
                   7172: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7173: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7174: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7175: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7176: 	}
1.395     albertel 7177: 	if ($recurse) { return undef; }
                   7178: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7179: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7180: # ---------------------------------------------------- Any other user namespace
                   7181:     } elsif ($realm eq 'environment') {
                   7182: # ----------------------------------------------------------------- environment
1.620     albertel 7183: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7184: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7185: 	} else {
1.770     albertel 7186: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7187: 		return '';
                   7188: 	    }
1.219     albertel 7189: 	    my %returnhash=&userenvironment($udom,$uname,
                   7190: 					    $spacequalifierrest);
                   7191: 	    return $returnhash{$spacequalifierrest};
                   7192: 	}
1.28      www      7193:     } elsif ($realm eq 'system') {
1.48      www      7194: # ----------------------------------------------------------------- system.time
                   7195: 	if ($space eq 'time') {
                   7196: 	    return time;
                   7197:         }
1.696     albertel 7198:     } elsif ($realm eq 'server') {
                   7199: # ----------------------------------------------------------------- system.time
                   7200: 	if ($space eq 'name') {
                   7201: 	    return $ENV{'SERVER_NAME'};
                   7202:         }
1.28      www      7203:     }
1.48      www      7204:     return '';
1.61      www      7205: }
                   7206: 
1.927     albertel 7207: sub get_reply {
                   7208:     my ($reply_value) = @_;
1.940     raeburn  7209:     if (ref($reply_value) eq 'ARRAY') {
                   7210:         if (wantarray) {
                   7211: 	    return @$reply_value;
                   7212:         }
                   7213:         return $reply_value->[0];
                   7214:     } else {
                   7215:         return $reply_value;
1.927     albertel 7216:     }
                   7217: }
                   7218: 
1.691     raeburn  7219: sub check_group_parms {
                   7220:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7221:     my @groupitems = ();
                   7222:     my $resultitem;
1.927     albertel 7223:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7224:     foreach my $group (@{$groups}) {
                   7225:         foreach my $level (@levels) {
1.927     albertel 7226:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7227:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7228:         }
                   7229:     }
                   7230:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7231:                             $env{'course.'.$courseid.'.domain'},
                   7232:                                      'course',@groupitems);
                   7233:     return $coursereply;
                   7234: }
                   7235: 
                   7236: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7237:     my ($courseid,@groups) = @_;
                   7238:     @groups = sort(@groups);
1.691     raeburn  7239:     return @groups;
                   7240: }
                   7241: 
1.395     albertel 7242: sub packages_tab_default {
                   7243:     my ($uri,$varname)=@_;
                   7244:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7245: 
                   7246:     my (@extension,@specifics,$do_default);
                   7247:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7248: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7249: 	if ($pack_type eq 'default') {
                   7250: 	    $do_default=1;
                   7251: 	} elsif ($pack_type eq 'extension') {
                   7252: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7253: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7254: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7255: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7256: 	}
                   7257:     }
                   7258:     # first look for a package that matches the requested part id
                   7259:     foreach my $package (@specifics) {
                   7260: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7261: 	next if ($pack_part ne $part);
                   7262: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7263: 	    return $packagetab{"$pack_type&$name&default"};
                   7264: 	}
                   7265:     }
                   7266:     # look for any possible matching non extension_ package
                   7267:     foreach my $package (@specifics) {
                   7268: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7269: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7270: 	    return $packagetab{"$pack_type&$name&default"};
                   7271: 	}
1.585     albertel 7272: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7273: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7274: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7275: 	}
                   7276:     }
1.738     albertel 7277:     # look for any posible extension_ match
                   7278:     foreach my $package (@extension) {
                   7279: 	my ($package,$pack_type)=@{$package};
                   7280: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7281: 	    return $packagetab{"$pack_type&$name&default"};
                   7282: 	}
                   7283: 	if (defined($packagetab{$package."&$name&default"})) {
                   7284: 	    return $packagetab{$package."&$name&default"};
                   7285: 	}
                   7286:     }
                   7287:     # look for a global default setting
                   7288:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7289: 	return $packagetab{"default&$name&default"};
                   7290:     }
1.395     albertel 7291:     return undef;
                   7292: }
                   7293: 
1.334     albertel 7294: sub add_prefix_and_part {
                   7295:     my ($prefix,$part)=@_;
                   7296:     my $keyroot;
                   7297:     if (defined($prefix) && $prefix !~ /^__/) {
                   7298: 	# prefix that has a part already
                   7299: 	$keyroot=$prefix;
                   7300:     } elsif (defined($prefix)) {
                   7301: 	# prefix that is missing a part
                   7302: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7303:     } else {
                   7304: 	# no prefix at all
                   7305: 	if (defined($part)) { $keyroot='_'.$part; }
                   7306:     }
                   7307:     return $keyroot;
                   7308: }
                   7309: 
1.71      www      7310: # ---------------------------------------------------------------- Get metadata
                   7311: 
1.599     albertel 7312: my %metaentry;
1.71      www      7313: sub metadata {
1.176     www      7314:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7315:     $uri=&declutter($uri);
1.288     albertel 7316:     # if it is a non metadata possible uri return quickly
1.529     albertel 7317:     if (($uri eq '') || 
                   7318: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7319: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7320:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7321: 	return undef;
                   7322:     }
                   7323:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7324: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7325: 	return undef;
1.288     albertel 7326:     }
1.73      www      7327:     my $filename=$uri;
                   7328:     $uri=~s/\.meta$//;
1.172     www      7329: #
                   7330: # Is the metadata already cached?
1.177     www      7331: # Look at timestamp of caching
1.172     www      7332: # Everything is cached by the main uri, libraries are never directly cached
                   7333: #
1.428     albertel 7334:     if (!defined($liburi)) {
1.599     albertel 7335: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7336: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7337:     }
                   7338:     {
1.172     www      7339: #
                   7340: # Is this a recursive call for a library?
                   7341: #
1.599     albertel 7342: #	if (! exists($metacache{$uri})) {
                   7343: #	    $metacache{$uri}={};
                   7344: #	}
1.924     albertel 7345: 	my $cachetime = 60*60;
1.171     www      7346:         if ($liburi) {
                   7347: 	    $liburi=&declutter($liburi);
                   7348:             $filename=$liburi;
1.401     bowersj2 7349:         } else {
1.599     albertel 7350: 	    &devalidate_cache_new('meta',$uri);
                   7351: 	    undef(%metaentry);
1.401     bowersj2 7352: 	}
1.140     www      7353:         my %metathesekeys=();
1.73      www      7354:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7355: 	my $metastring;
1.924     albertel 7356: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7357: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7358: 	    $metastring = 
1.929     albertel 7359: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7360: 					  ('grade_target' => 'meta'));
                   7361: 	    $cachetime = 1; # only want this cached in the child not long term
                   7362: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7363: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7364: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7365: 	    $metastring=&getfile($file);
1.489     albertel 7366: 	}
1.208     albertel 7367:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7368:         my $token;
1.140     www      7369:         undef %metathesekeys;
1.71      www      7370:         while ($token=$parser->get_token) {
1.339     albertel 7371: 	    if ($token->[0] eq 'S') {
                   7372: 		if (defined($token->[2]->{'package'})) {
1.172     www      7373: #
                   7374: # This is a package - get package info
                   7375: #
1.339     albertel 7376: 		    my $package=$token->[2]->{'package'};
                   7377: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7378: 		    if (defined($token->[2]->{'id'})) { 
                   7379: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7380: 		    }
1.599     albertel 7381: 		    if ($metaentry{':packages'}) {
                   7382: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7383: 		    } else {
1.599     albertel 7384: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7385: 		    }
1.736     albertel 7386: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7387: 			my $part=$keyroot;
                   7388: 			$part=~s/^\_//;
1.736     albertel 7389: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7390: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7391: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7392: 			    # ignore package.tab specified default values
                   7393:                             # here &package_tab_default() will fetch those
                   7394: 			    if ($subp eq 'default') { next; }
1.736     albertel 7395: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7396: 			    my $unikey;
                   7397: 			    if ($pack =~ /_0$/) {
                   7398: 				$unikey='parameter_0_'.$name;
                   7399: 				$part=0;
                   7400: 			    } else {
                   7401: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7402: 			    }
1.339     albertel 7403: 			    if ($subp eq 'display') {
                   7404: 				$value.=' [Part: '.$part.']';
                   7405: 			    }
1.599     albertel 7406: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7407: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7408: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7409: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7410: 			    }
1.599     albertel 7411: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7412: 				$metaentry{':'.$unikey}=
                   7413: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7414: 			    }
1.339     albertel 7415: 			}
                   7416: 		    }
                   7417: 		} else {
1.172     www      7418: #
                   7419: # This is not a package - some other kind of start tag
1.339     albertel 7420: #
                   7421: 		    my $entry=$token->[1];
                   7422: 		    my $unikey;
                   7423: 		    if ($entry eq 'import') {
                   7424: 			$unikey='';
                   7425: 		    } else {
                   7426: 			$unikey=$entry;
                   7427: 		    }
                   7428: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7429: 
                   7430: 		    if (defined($token->[2]->{'id'})) { 
                   7431: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7432: 		    }
1.175     www      7433: 
1.339     albertel 7434: 		    if ($entry eq 'import') {
1.175     www      7435: #
                   7436: # Importing a library here
1.339     albertel 7437: #
                   7438: 			if ($depthcount<20) {
                   7439: 			    my $location=$parser->get_text('/import');
                   7440: 			    my $dir=$filename;
                   7441: 			    $dir=~s|[^/]*$||;
                   7442: 			    $location=&filelocation($dir,$location);
1.736     albertel 7443: 			    my $metadata = 
                   7444: 				&metadata($uri,'keys', $location,$unikey,
                   7445: 					  $depthcount+1);
                   7446: 			    foreach my $meta (split(',',$metadata)) {
                   7447: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7448: 				$metathesekeys{$meta}=1;
1.339     albertel 7449: 			    }
                   7450: 			}
                   7451: 		    } else { 
                   7452: 			
                   7453: 			if (defined($token->[2]->{'name'})) { 
                   7454: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7455: 			}
                   7456: 			$metathesekeys{$unikey}=1;
1.736     albertel 7457: 			foreach my $param (@{$token->[3]}) {
                   7458: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7459: 				$token->[2]->{$param};
1.339     albertel 7460: 			}
                   7461: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7462: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7463: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7464: 		 # only ws inside the tag, and not in default, so use default
                   7465: 		 # as value
1.599     albertel 7466: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7467: 			} elsif ( $internaltext =~ /\S/ ) {
                   7468: 		  # something interesting inside the tag
                   7469: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7470: 			} else {
1.908     albertel 7471: 		  # no interesting values, don't set a default
1.339     albertel 7472: 			}
1.172     www      7473: # end of not-a-package not-a-library import
1.339     albertel 7474: 		    }
1.172     www      7475: # end of not-a-package start tag
1.339     albertel 7476: 		}
1.172     www      7477: # the next is the end of "start tag"
1.339     albertel 7478: 	    }
                   7479: 	}
1.483     albertel 7480: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7481: 	$extension = lc($extension);
                   7482: 	if ($extension eq 'htm') { $extension='html'; }
                   7483: 
1.737     albertel 7484: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7485: 	    #no specific packages #how's our extension
                   7486: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7487: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7488: 					 \%metathesekeys);
                   7489: 	}
1.883     albertel 7490: 
                   7491: 	if (!exists($metaentry{':packages'})
                   7492: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7493: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7494: 		#no specific packages well let's get default then
                   7495: 		if ($key!~/^default&/) { next; }
1.488     albertel 7496: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7497: 					     \%metathesekeys);
                   7498: 	    }
                   7499: 	}
1.338     www      7500: # are there custom rights to evaluate
1.599     albertel 7501: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7502: 
1.338     www      7503:     #
                   7504:     # Importing a rights file here
1.339     albertel 7505:     #
                   7506: 	    unless ($depthcount) {
1.599     albertel 7507: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7508: 		my $dir=$filename;
                   7509: 		$dir=~s|[^/]*$||;
                   7510: 		$location=&filelocation($dir,$location);
1.736     albertel 7511: 		my $rights_metadata =
                   7512: 		    &metadata($uri,'keys',$location,'_rights',
                   7513: 			      $depthcount+1);
                   7514: 		foreach my $rights (split(',',$rights_metadata)) {
                   7515: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7516: 		    $metathesekeys{$rights}=1;
1.339     albertel 7517: 		}
                   7518: 	    }
                   7519: 	}
1.737     albertel 7520: 	# uniqifiy package listing
                   7521: 	my %seen;
                   7522: 	my @uniq_packages =
                   7523: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7524: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7525: 
                   7526: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7527: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7528: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7529: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7530: # this is the end of "was not already recently cached
1.71      www      7531:     }
1.599     albertel 7532:     return $metaentry{':'.$what};
1.261     albertel 7533: }
                   7534: 
1.488     albertel 7535: sub metadata_create_package_def {
1.483     albertel 7536:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7537:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7538:     if ($subp eq 'default') { next; }
                   7539:     
1.599     albertel 7540:     if (defined($metaentry{':packages'})) {
                   7541: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7542:     } else {
1.599     albertel 7543: 	$metaentry{':packages'}=$package;
1.483     albertel 7544:     }
                   7545:     my $value=$packagetab{$key};
                   7546:     my $unikey;
                   7547:     $unikey='parameter_0_'.$name;
1.599     albertel 7548:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7549:     $$metathesekeys{$unikey}=1;
1.599     albertel 7550:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7551: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7552:     }
1.599     albertel 7553:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7554: 	$metaentry{':'.$unikey}=
                   7555: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7556:     }
                   7557: }
                   7558: 
1.261     albertel 7559: sub metadata_generate_part0 {
                   7560:     my ($metadata,$metacache,$uri) = @_;
                   7561:     my %allnames;
1.737     albertel 7562:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7563: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7564: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7565: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7566: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7567: 	    $allnames{$name}=$part;
                   7568: 	  }
                   7569: 	}
                   7570:     }
                   7571:     foreach my $name (keys(%allnames)) {
                   7572:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7573:       my $key=":parameter_0_$name";
1.261     albertel 7574:       $$metacache{"$key.part"}='0';
                   7575:       $$metacache{"$key.name"}=$name;
1.428     albertel 7576:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7577: 					   $allnames{$name}.'_'.$name.
                   7578: 					   '.type'};
1.428     albertel 7579:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7580: 			     '.display'};
1.644     www      7581:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7582:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7583:       $$metacache{"$key.display"}=$olddis;
                   7584:     }
1.71      www      7585: }
                   7586: 
1.764     albertel 7587: # ------------------------------------------------------ Devalidate title cache
                   7588: 
                   7589: sub devalidate_title_cache {
                   7590:     my ($url)=@_;
                   7591:     if (!$env{'request.course.id'}) { return; }
                   7592:     my $symb=&symbread($url);
                   7593:     if (!$symb) { return; }
                   7594:     my $key=$env{'request.course.id'}."\0".$symb;
                   7595:     &devalidate_cache_new('title',$key);
                   7596: }
                   7597: 
1.301     www      7598: # ------------------------------------------------- Get the title of a resource
                   7599: 
                   7600: sub gettitle {
                   7601:     my $urlsymb=shift;
                   7602:     my $symb=&symbread($urlsymb);
1.534     albertel 7603:     if ($symb) {
1.620     albertel 7604: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7605: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7606: 	if (defined($cached)) { 
                   7607: 	    return $result;
                   7608: 	}
1.534     albertel 7609: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7610: 	my $title='';
1.907     albertel 7611: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7612: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7613: 	} else {
                   7614: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7615: 		    &GDBM_READER(),0640)) {
                   7616: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7617: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7618: 		untie(%bighash);
                   7619: 	    }
1.534     albertel 7620: 	}
                   7621: 	$title=~s/\&colon\;/\:/gs;
                   7622: 	if ($title) {
1.599     albertel 7623: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7624: 	}
                   7625: 	$urlsymb=$url;
                   7626:     }
                   7627:     my $title=&metadata($urlsymb,'title');
                   7628:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7629:     return $title;
1.301     www      7630: }
1.613     albertel 7631: 
1.614     albertel 7632: sub get_slot {
                   7633:     my ($which,$cnum,$cdom)=@_;
                   7634:     if (!$cnum || !$cdom) {
1.790     albertel 7635: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7636: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7637: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7638:     }
1.703     albertel 7639:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7640:     my %slotinfo;
                   7641:     if (exists($remembered{$key})) {
                   7642: 	$slotinfo{$which} = $remembered{$key};
                   7643:     } else {
                   7644: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7645: 	&Apache::lonhomework::showhash(%slotinfo);
                   7646: 	my ($tmp)=keys(%slotinfo);
                   7647: 	if ($tmp=~/^error:/) { return (); }
                   7648: 	$remembered{$key} = $slotinfo{$which};
                   7649:     }
1.616     albertel 7650:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7651: 	return %{$slotinfo{$which}};
                   7652:     }
                   7653:     return $slotinfo{$which};
1.614     albertel 7654: }
1.31      www      7655: # ------------------------------------------------- Update symbolic store links
                   7656: 
                   7657: sub symblist {
                   7658:     my ($mapname,%newhash)=@_;
1.438     www      7659:     $mapname=&deversion(&declutter($mapname));
1.31      www      7660:     my %hash;
1.620     albertel 7661:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7662:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7663:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7664: 	    foreach my $url (keys %newhash) {
                   7665: 		next if ($url eq 'last_known'
                   7666: 			 && $env{'form.no_update_last_known'});
                   7667: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7668: 						    $newhash{$url}->[1],
                   7669: 						    $newhash{$url}->[0]);
1.191     harris41 7670:             }
1.31      www      7671:             if (untie(%hash)) {
                   7672: 		return 'ok';
                   7673:             }
                   7674:         }
                   7675:     }
                   7676:     return 'error';
1.212     www      7677: }
                   7678: 
                   7679: # --------------------------------------------------------------- Verify a symb
                   7680: 
                   7681: sub symbverify {
1.510     www      7682:     my ($symb,$thisurl)=@_;
                   7683:     my $thisfn=$thisurl;
1.439     www      7684:     $thisfn=&declutter($thisfn);
1.215     www      7685: # direct jump to resource in page or to a sequence - will construct own symbs
                   7686:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7687: # check URL part
1.409     www      7688:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7689: 
1.431     www      7690:     unless ($url eq $thisfn) { return 0; }
1.213     www      7691: 
1.216     www      7692:     $symb=&symbclean($symb);
1.510     www      7693:     $thisurl=&deversion($thisurl);
1.439     www      7694:     $thisfn=&deversion($thisfn);
1.213     www      7695: 
                   7696:     my %bighash;
                   7697:     my $okay=0;
1.431     www      7698: 
1.620     albertel 7699:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7700:                             &GDBM_READER(),0640)) {
1.510     www      7701:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7702:         unless ($ids) { 
1.510     www      7703:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7704:         }
                   7705:         if ($ids) {
                   7706: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7707: 	    foreach my $id (split(/\,/,$ids)) {
                   7708: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7709:                if (
                   7710:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7711:    eq $symb) { 
1.620     albertel 7712: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7713: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7714: 		       $okay=1; 
                   7715: 		   }
                   7716: 	       }
1.216     www      7717: 	   }
                   7718:         }
1.213     www      7719: 	untie(%bighash);
                   7720:     }
                   7721:     return $okay;
1.31      www      7722: }
                   7723: 
1.210     www      7724: # --------------------------------------------------------------- Clean-up symb
                   7725: 
                   7726: sub symbclean {
                   7727:     my $symb=shift;
1.568     albertel 7728:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7729: # remove version from map
                   7730:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7731: 
1.210     www      7732: # remove version from URL
                   7733:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7734: 
1.507     www      7735: # remove wrapper
                   7736: 
1.510     www      7737:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7738:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7739:     return $symb;
1.409     www      7740: }
                   7741: 
                   7742: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7743: 
                   7744: sub encode_symb {
                   7745:     my ($map,$resid,$url)=@_;
                   7746:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7747: }
1.409     www      7748: 
                   7749: sub decode_symb {
1.568     albertel 7750:     my $symb=shift;
                   7751:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7752:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7753:     return (&fixversion($map),$resid,&fixversion($url));
                   7754: }
                   7755: 
                   7756: sub fixversion {
                   7757:     my $fn=shift;
1.609     banghart 7758:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7759:     my %bighash;
                   7760:     my $uri=&clutter($fn);
1.620     albertel 7761:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7762: # is this cached?
1.599     albertel 7763:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7764:     if (defined($cached)) { return $result; }
                   7765: # unfortunately not cached, or expired
1.620     albertel 7766:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7767: 	    &GDBM_READER(),0640)) {
                   7768:  	if ($bighash{'version_'.$uri}) {
                   7769:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7770:  	    unless (($version eq 'mostrecent') || 
                   7771: 		    ($version==&getversion($uri))) {
1.440     www      7772:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7773:  	    }
                   7774:  	}
                   7775:  	untie %bighash;
1.413     www      7776:     }
1.599     albertel 7777:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7778: }
                   7779: 
                   7780: sub deversion {
                   7781:     my $url=shift;
                   7782:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7783:     return $url;
1.210     www      7784: }
                   7785: 
1.31      www      7786: # ------------------------------------------------------ Return symb list entry
                   7787: 
                   7788: sub symbread {
1.249     www      7789:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7790:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7791:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7792: # no filename provided? try from environment
1.44      www      7793:     unless ($thisfn) {
1.620     albertel 7794:         if ($env{'request.symb'}) {
                   7795: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7796: 	}
1.620     albertel 7797: 	$thisfn=$env{'request.filename'};
1.44      www      7798:     }
1.569     albertel 7799:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7800: # is that filename actually a symb? Verify, clean, and return
                   7801:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7802: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7803: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7804: 	}
1.242     www      7805:     }
1.44      www      7806:     $thisfn=declutter($thisfn);
1.31      www      7807:     my %hash;
1.37      www      7808:     my %bighash;
                   7809:     my $syval='';
1.620     albertel 7810:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7811:         my $targetfn = $thisfn;
1.609     banghart 7812:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7813:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7814:         }
1.687     albertel 7815: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7816: 	    $targetfn=$1;
                   7817: 	}
1.620     albertel 7818:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7819:                       &GDBM_READER(),0640)) {
1.481     raeburn  7820: 	    $syval=$hash{$targetfn};
1.37      www      7821:             untie(%hash);
                   7822:         }
                   7823: # ---------------------------------------------------------- There was an entry
                   7824:         if ($syval) {
1.601     albertel 7825: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7826: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7827: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7828: 		    #return $env{$cache_str}='';
1.601     albertel 7829: 		#}    
                   7830: 		#$syval.=$1;
                   7831: 	    #}
1.37      www      7832:         } else {
                   7833: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7834:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7835:                             &GDBM_READER(),0640)) {
1.37      www      7836: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7837:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7838:               unless ($ids) { 
                   7839:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7840:               }
                   7841:               unless ($ids) {
                   7842: # alias?
                   7843: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7844:               }
1.37      www      7845:               if ($ids) {
                   7846: # ------------------------------------------------------------------- Has ID(s)
                   7847:                  my @possibilities=split(/\,/,$ids);
1.39      www      7848:                  if ($#possibilities==0) {
                   7849: # ----------------------------------------------- There is only one possibility
1.37      www      7850: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7851: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7852: 						    $resid,$thisfn);
1.249     www      7853:                  } elsif (!$donotrecurse) {
1.39      www      7854: # ------------------------------------------ There is more than one possibility
                   7855:                      my $realpossible=0;
1.800     albertel 7856:                      foreach my $id (@possibilities) {
                   7857: 			 my $file=$bighash{'src_'.$id};
1.39      www      7858:                          if (&allowed('bre',$file)) {
1.800     albertel 7859:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7860:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7861: 				$realpossible++;
1.626     albertel 7862:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7863: 						    $resid,$thisfn);
1.39      www      7864:                             }
                   7865: 			 }
1.191     harris41 7866:                      }
1.39      www      7867: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7868:                  } else {
                   7869:                      $syval='';
1.37      www      7870:                  }
                   7871: 	      }
                   7872:               untie(%bighash)
1.481     raeburn  7873:            }
1.31      www      7874:         }
1.62      www      7875:         if ($syval) {
1.620     albertel 7876: 	    return $env{$cache_str}=$syval;
1.62      www      7877:         }
1.31      www      7878:     }
1.949     raeburn  7879:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7880:     return $env{$cache_str}='';
1.31      www      7881: }
                   7882: 
                   7883: # ---------------------------------------------------------- Return random seed
                   7884: 
1.32      www      7885: sub numval {
                   7886:     my $txt=shift;
                   7887:     $txt=~tr/A-J/0-9/;
                   7888:     $txt=~tr/a-j/0-9/;
                   7889:     $txt=~tr/K-T/0-9/;
                   7890:     $txt=~tr/k-t/0-9/;
                   7891:     $txt=~tr/U-Z/0-5/;
                   7892:     $txt=~tr/u-z/0-5/;
                   7893:     $txt=~s/\D//g;
1.564     albertel 7894:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7895:     return int($txt);
1.368     albertel 7896: }
                   7897: 
1.484     albertel 7898: sub numval2 {
                   7899:     my $txt=shift;
                   7900:     $txt=~tr/A-J/0-9/;
                   7901:     $txt=~tr/a-j/0-9/;
                   7902:     $txt=~tr/K-T/0-9/;
                   7903:     $txt=~tr/k-t/0-9/;
                   7904:     $txt=~tr/U-Z/0-5/;
                   7905:     $txt=~tr/u-z/0-5/;
                   7906:     $txt=~s/\D//g;
                   7907:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7908:     my $total;
                   7909:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7910:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7911:     return int($total);
                   7912: }
                   7913: 
1.575     albertel 7914: sub numval3 {
                   7915:     use integer;
                   7916:     my $txt=shift;
                   7917:     $txt=~tr/A-J/0-9/;
                   7918:     $txt=~tr/a-j/0-9/;
                   7919:     $txt=~tr/K-T/0-9/;
                   7920:     $txt=~tr/k-t/0-9/;
                   7921:     $txt=~tr/U-Z/0-5/;
                   7922:     $txt=~tr/u-z/0-5/;
                   7923:     $txt=~s/\D//g;
                   7924:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7925:     my $total;
                   7926:     foreach my $val (@txts) { $total+=$val; }
                   7927:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7928:     return $total;
                   7929: }
                   7930: 
1.675     albertel 7931: sub digest {
                   7932:     my ($data)=@_;
                   7933:     my $digest=&Digest::MD5::md5($data);
                   7934:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7935:     my ($e,$f);
                   7936:     {
                   7937:         use integer;
                   7938:         $e=($a+$b);
                   7939:         $f=($c+$d);
                   7940:         if ($_64bit) {
                   7941:             $e=(($e<<32)>>32);
                   7942:             $f=(($f<<32)>>32);
                   7943:         }
                   7944:     }
                   7945:     if (wantarray) {
                   7946: 	return ($e,$f);
                   7947:     } else {
                   7948: 	my $g;
                   7949: 	{
                   7950: 	    use integer;
                   7951: 	    $g=($e+$f);
                   7952: 	    if ($_64bit) {
                   7953: 		$g=(($g<<32)>>32);
                   7954: 	    }
                   7955: 	}
                   7956: 	return $g;
                   7957:     }
                   7958: }
                   7959: 
1.368     albertel 7960: sub latest_rnd_algorithm_id {
1.675     albertel 7961:     return '64bit5';
1.366     albertel 7962: }
1.32      www      7963: 
1.503     albertel 7964: sub get_rand_alg {
                   7965:     my ($courseid)=@_;
1.790     albertel 7966:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7967:     if ($courseid) {
1.620     albertel 7968: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7969:     }
                   7970:     return &latest_rnd_algorithm_id();
                   7971: }
                   7972: 
1.562     albertel 7973: sub validCODE {
                   7974:     my ($CODE)=@_;
                   7975:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7976:     return 0;
                   7977: }
                   7978: 
1.491     albertel 7979: sub getCODE {
1.620     albertel 7980:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7981:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7982: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7983: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7984: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7985:     }
                   7986:     return undef;
                   7987: }
                   7988: 
1.31      www      7989: sub rndseed {
1.155     albertel 7990:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7991:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7992:     if (!defined($symb)) {
1.366     albertel 7993: 	unless ($symb=$wsymb) { return time; }
                   7994:     }
                   7995:     if (!$courseid) { $courseid=$wcourseid; }
                   7996:     if (!$domain) { $domain=$wdomain; }
                   7997:     if (!$username) { $username=$wusername }
1.503     albertel 7998:     my $which=&get_rand_alg();
1.803     albertel 7999: 
1.491     albertel 8000:     if (defined(&getCODE())) {
1.675     albertel 8001: 	if ($which eq '64bit5') {
                   8002: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8003: 	} elsif ($which eq '64bit4') {
1.575     albertel 8004: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8005: 	} else {
                   8006: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8007: 	}
1.675     albertel 8008:     } elsif ($which eq '64bit5') {
                   8009: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8010:     } elsif ($which eq '64bit4') {
                   8011: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8012:     } elsif ($which eq '64bit3') {
                   8013: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8014:     } elsif ($which eq '64bit2') {
                   8015: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8016:     } elsif ($which eq '64bit') {
                   8017: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8018:     }
                   8019:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8020: }
                   8021: 
                   8022: sub rndseed_32bit {
                   8023:     my ($symb,$courseid,$domain,$username)=@_;
                   8024:     {
                   8025: 	use integer;
                   8026: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8027: 	my $symbseed=numval($symb) << 22;
                   8028: 	my $namechck=unpack("%32C*",$username) << 17;
                   8029: 	my $nameseed=numval($username) << 12;
                   8030: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8031: 	my $courseseed=unpack("%32C*",$courseid);
                   8032: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8034: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8035: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8036: 	return $num;
                   8037:     }
                   8038: }
                   8039: 
                   8040: sub rndseed_64bit {
                   8041:     my ($symb,$courseid,$domain,$username)=@_;
                   8042:     {
                   8043: 	use integer;
                   8044: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8045: 	my $symbseed=numval($symb) << 10;
                   8046: 	my $namechck=unpack("%32S*",$username);
                   8047: 	
                   8048: 	my $nameseed=numval($username) << 21;
                   8049: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8050: 	my $courseseed=unpack("%32S*",$courseid);
                   8051: 	
                   8052: 	my $num1=$symbchck+$symbseed+$namechck;
                   8053: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8055: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8056: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8057: 	return "$num1,$num2";
1.155     albertel 8058:     }
1.366     albertel 8059: }
                   8060: 
1.443     albertel 8061: sub rndseed_64bit2 {
                   8062:     my ($symb,$courseid,$domain,$username)=@_;
                   8063:     {
                   8064: 	use integer;
                   8065: 	# strings need to be an even # of cahracters long, it it is odd the
                   8066:         # last characters gets thrown away
                   8067: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8068: 	my $symbseed=numval($symb) << 10;
                   8069: 	my $namechck=unpack("%32S*",$username.' ');
                   8070: 	
                   8071: 	my $nameseed=numval($username) << 21;
1.501     albertel 8072: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8073: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8074: 	
                   8075: 	my $num1=$symbchck+$symbseed+$namechck;
                   8076: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8077: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8078: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8079: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8080: 	return "$num1,$num2";
                   8081:     }
                   8082: }
                   8083: 
                   8084: sub rndseed_64bit3 {
                   8085:     my ($symb,$courseid,$domain,$username)=@_;
                   8086:     {
                   8087: 	use integer;
                   8088: 	# strings need to be an even # of cahracters long, it it is odd the
                   8089:         # last characters gets thrown away
                   8090: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8091: 	my $symbseed=numval2($symb) << 10;
                   8092: 	my $namechck=unpack("%32S*",$username.' ');
                   8093: 	
                   8094: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8095: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8096: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8097: 	
                   8098: 	my $num1=$symbchck+$symbseed+$namechck;
                   8099: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8101: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8103: 	
1.503     albertel 8104: 	return "$num1:$num2";
1.443     albertel 8105:     }
                   8106: }
                   8107: 
1.575     albertel 8108: sub rndseed_64bit4 {
                   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=numval3($symb) << 10;
                   8116: 	my $namechck=unpack("%32S*",$username.' ');
                   8117: 	
                   8118: 	my $nameseed=numval3($username) << 21;
                   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 :$num1:$num2:$_64bit");
1.575     albertel 8126: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8127: 	
                   8128: 	return "$num1:$num2";
                   8129:     }
                   8130: }
                   8131: 
1.675     albertel 8132: sub rndseed_64bit5 {
                   8133:     my ($symb,$courseid,$domain,$username)=@_;
                   8134:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8135:     return "$num1:$num2";
                   8136: }
                   8137: 
1.366     albertel 8138: sub rndseed_CODE_64bit {
                   8139:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8140:     {
1.366     albertel 8141: 	use integer;
1.443     albertel 8142: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8143: 	my $symbseed=numval2($symb);
1.491     albertel 8144: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8145: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8146: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8147: 	my $num1=$symbseed+$CODEchck;
                   8148: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8149: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8150: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8151: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8152: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8153: 	return "$num1:$num2";
1.366     albertel 8154:     }
                   8155: }
                   8156: 
1.575     albertel 8157: sub rndseed_CODE_64bit4 {
                   8158:     my ($symb,$courseid,$domain,$username)=@_;
                   8159:     {
                   8160: 	use integer;
                   8161: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8162: 	my $symbseed=numval3($symb);
                   8163: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8164: 	my $CODEseed=numval3(&getCODE());
                   8165: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8166: 	my $num1=$symbseed+$CODEchck;
                   8167: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8168: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8169: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8170: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8171: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8172: 	return "$num1:$num2";
                   8173:     }
                   8174: }
                   8175: 
1.675     albertel 8176: sub rndseed_CODE_64bit5 {
                   8177:     my ($symb,$courseid,$domain,$username)=@_;
                   8178:     my $code = &getCODE();
                   8179:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8180:     return "$num1:$num2";
                   8181: }
                   8182: 
1.366     albertel 8183: sub setup_random_from_rndseed {
                   8184:     my ($rndseed)=@_;
1.503     albertel 8185:     if ($rndseed =~/([,:])/) {
                   8186: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8187: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8188:     } else {
                   8189: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8190:     }
1.36      albertel 8191: }
                   8192: 
1.474     albertel 8193: sub latest_receipt_algorithm_id {
1.835     albertel 8194:     return 'receipt3';
1.474     albertel 8195: }
                   8196: 
1.480     www      8197: sub recunique {
                   8198:     my $fucourseid=shift;
                   8199:     my $unique;
1.835     albertel 8200:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8201: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8202: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8203:     } else {
                   8204: 	$unique=$perlvar{'lonReceipt'};
                   8205:     }
                   8206:     return unpack("%32C*",$unique);
                   8207: }
                   8208: 
                   8209: sub recprefix {
                   8210:     my $fucourseid=shift;
                   8211:     my $prefix;
1.835     albertel 8212:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8213: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8214: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8215:     } else {
                   8216: 	$prefix=$perlvar{'lonHostID'};
                   8217:     }
                   8218:     return unpack("%32C*",$prefix);
                   8219: }
                   8220: 
1.76      www      8221: sub ireceipt {
1.474     albertel 8222:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8223: 
                   8224:     my $return =&recprefix($fucourseid).'-';
                   8225: 
                   8226:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8227: 	$env{'request.state'} eq 'construct') {
                   8228: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8229: 	return $return;
                   8230:     }
                   8231: 
1.76      www      8232:     my $cuname=unpack("%32C*",$funame);
                   8233:     my $cudom=unpack("%32C*",$fudom);
                   8234:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8235:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8236:     my $cunique=&recunique($fucourseid);
1.474     albertel 8237:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8238:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8239: 
1.790     albertel 8240: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8241: 			       
                   8242: 	$return.= ($cunique%$cuname+
                   8243: 		   $cunique%$cudom+
                   8244: 		   $cusymb%$cuname+
                   8245: 		   $cusymb%$cudom+
                   8246: 		   $cucourseid%$cuname+
                   8247: 		   $cucourseid%$cudom+
                   8248: 		   $cpart%$cuname+
                   8249: 		   $cpart%$cudom);
                   8250:     } else {
                   8251: 	$return.= ($cunique%$cuname+
                   8252: 		   $cunique%$cudom+
                   8253: 		   $cusymb%$cuname+
                   8254: 		   $cusymb%$cudom+
                   8255: 		   $cucourseid%$cuname+
                   8256: 		   $cucourseid%$cudom);
                   8257:     }
                   8258:     return $return;
1.76      www      8259: }
                   8260: 
                   8261: sub receipt {
1.474     albertel 8262:     my ($part)=@_;
1.790     albertel 8263:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8264:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8265: }
1.260     ng       8266: 
1.790     albertel 8267: sub whichuser {
                   8268:     my ($passedsymb)=@_;
                   8269:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8270:     if (defined($env{'form.grade_symb'})) {
                   8271: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8272: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8273: 	if (!$allowed &&
                   8274: 	    exists($env{'request.course.sec'}) &&
                   8275: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8276: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8277: 			      '/'.$env{'request.course.sec'});
                   8278: 	}
                   8279: 	if ($allowed) {
                   8280: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8281: 	    $courseid=$tmp_courseid;
                   8282: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8283: 	    ($name)=&get_env_multiple('form.grade_username');
                   8284: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8285: 	}
                   8286:     }
                   8287:     if (!$passedsymb) {
                   8288: 	$symb=&symbread();
                   8289:     } else {
                   8290: 	$symb=$passedsymb;
                   8291:     }
                   8292:     $courseid=$env{'request.course.id'};
                   8293:     $domain=$env{'user.domain'};
                   8294:     $name=$env{'user.name'};
                   8295:     if ($name eq 'public' && $domain eq 'public') {
                   8296: 	if (!defined($env{'form.username'})) {
                   8297: 	    $env{'form.username'}.=time.rand(10000000);
                   8298: 	}
                   8299: 	$name.=$env{'form.username'};
                   8300:     }
                   8301:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8302: 
                   8303: }
                   8304: 
1.36      albertel 8305: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8306: # returns either the contents of the file or 
                   8307: # -1 if the file doesn't exist
1.481     raeburn  8308: #
                   8309: # if the target is a file that was uploaded via DOCS, 
                   8310: # a check will be made to see if a current copy exists on the local server,
                   8311: # if it does this will be served, otherwise a copy will be retrieved from
                   8312: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8313: # the local server.   
1.472     albertel 8314: 
1.36      albertel 8315: sub getfile {
1.538     albertel 8316:     my ($file) = @_;
1.609     banghart 8317:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8318:     &repcopy($file);
                   8319:     return &readfile($file);
                   8320: }
                   8321: 
                   8322: sub repcopy_userfile {
                   8323:     my ($file)=@_;
1.609     banghart 8324:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8325:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8326:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8327: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8328:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8329:     if (-e "$file") {
1.828     www      8330: # we already have a local copy, check it out
1.538     albertel 8331: 	my @fileinfo = stat($file);
1.828     www      8332: 	my $rtncode;
                   8333: 	my $info;
1.538     albertel 8334: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8335: 	if ($lwpresp ne 'ok') {
1.828     www      8336: # there is no such file anymore, even though we had a local copy
1.482     albertel 8337: 	    if ($rtncode eq '404') {
1.538     albertel 8338: 		unlink($file);
1.482     albertel 8339: 	    }
                   8340: 	    return -1;
                   8341: 	}
                   8342: 	if ($info < $fileinfo[9]) {
1.828     www      8343: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8344: 	    return 'ok';
1.828     www      8345: 	} else {
                   8346: # the file is outdated, get rid of it
                   8347: 	    unlink($file);
1.482     albertel 8348: 	}
1.828     www      8349:     }
                   8350: # one way or the other, at this point, we don't have the file
                   8351: # construct the correct path for the file
                   8352:     my @parts = ($cdom,$cnum); 
                   8353:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8354: 	push @parts, split(/\//,$1);
                   8355:     }
                   8356:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8357:     foreach my $part (@parts) {
                   8358: 	$path .= '/'.$part;
                   8359: 	if (!-e $path) {
                   8360: 	    mkdir($path,0770);
1.482     albertel 8361: 	}
                   8362:     }
1.828     www      8363: # now the path exists for sure
                   8364: # get a user agent
                   8365:     my $ua=new LWP::UserAgent;
                   8366:     my $transferfile=$file.'.in.transfer';
                   8367: # FIXME: this should flock
                   8368:     if (-e $transferfile) { return 'ok'; }
                   8369:     my $request;
                   8370:     $uri=~s/^\///;
1.976.4.1  raeburn  8371:     my $homeserver = &homeserver($cnum,$cdom);
                   8372:     my $protocol = $protocol{$homeserver};
                   8373:     $protocol = 'http' if ($protocol ne 'https');
                   8374:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8375:     my $response=$ua->request($request,$transferfile);
                   8376: # did it work?
                   8377:     if ($response->is_error()) {
                   8378: 	unlink($transferfile);
                   8379: 	&logthis("Userfile repcopy failed for $uri");
                   8380: 	return -1;
                   8381:     }
                   8382: # worked, rename the transfer file
                   8383:     rename($transferfile,$file);
1.607     raeburn  8384:     return 'ok';
1.481     raeburn  8385: }
                   8386: 
1.517     albertel 8387: sub tokenwrapper {
                   8388:     my $uri=shift;
1.976.4.1  raeburn  8389:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8390:     $uri=~s|^/||;
1.620     albertel 8391:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8392:     my $token=$1;
1.552     albertel 8393:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8394:     if ($udom && $uname && $file) {
                   8395: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8396:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.4.1  raeburn  8397:         my $homeserver = &homeserver($uname,$udom);
                   8398:         my $protocol = $protocol{$homeserver};
                   8399:         $protocol = 'http' if ($protocol ne 'https');
                   8400:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8401:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8402:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8403:     } else {
                   8404:         return '/adm/notfound.html';
                   8405:     }
                   8406: }
                   8407: 
1.828     www      8408: # call with reqtype HEAD: get last modification time
                   8409: # call with reqtype GET: get the file contents
                   8410: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8411: #
1.481     raeburn  8412: sub getuploaded {
                   8413:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8414:     $uri=~s/^\///;
1.976.4.1  raeburn  8415:     my $homeserver = &homeserver($cnum,$cdom);
                   8416:     my $protocol = $protocol{$homeserver};
                   8417:     $protocol = 'http' if ($protocol ne 'https');
                   8418:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8419:     my $ua=new LWP::UserAgent;
                   8420:     my $request=new HTTP::Request($reqtype,$uri);
                   8421:     my $response=$ua->request($request);
                   8422:     $$rtncode = $response->code;
1.482     albertel 8423:     if (! $response->is_success()) {
                   8424: 	return 'failed';
                   8425:     }      
                   8426:     if ($reqtype eq 'HEAD') {
1.486     www      8427: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8428:     } elsif ($reqtype eq 'GET') {
                   8429: 	$$info = $response->content;
1.472     albertel 8430:     }
1.482     albertel 8431:     return 'ok';
1.36      albertel 8432: }
                   8433: 
1.481     raeburn  8434: sub readfile {
                   8435:     my $file = shift;
                   8436:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8437:     my $fh;
                   8438:     open($fh,"<$file");
                   8439:     my $a='';
1.800     albertel 8440:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8441:     return $a;
                   8442: }
                   8443: 
1.36      albertel 8444: sub filelocation {
1.590     banghart 8445:     my ($dir,$file) = @_;
                   8446:     my $location;
                   8447:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8448: 
                   8449:     if ($file =~ m-^/adm/-) {
                   8450: 	$file=~s-^/adm/wrapper/-/-;
                   8451: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8452:     }
1.882     albertel 8453: 
1.590     banghart 8454:     if ($file=~m:^/~:) { # is a contruction space reference
                   8455:         $location = $file;
                   8456:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8457:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8458: 	# is a correct contruction space reference
                   8459:         $location = $file;
1.956     raeburn  8460:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8461:         $location = $file;
1.609     banghart 8462:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8463:         my ($udom,$uname,$filename)=
1.811     albertel 8464:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8465:         my $home=&homeserver($uname,$udom);
                   8466:         my $is_me=0;
                   8467:         my @ids=&current_machine_ids();
                   8468:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8469:         if ($is_me) {
1.955     raeburn  8470:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8471:         } else {
                   8472:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8473:   	      $udom.'/'.$uname.'/'.$filename;
                   8474:         }
1.882     albertel 8475:     } elsif ($file =~ m-^/adm/-) {
                   8476: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8477:     } else {
                   8478:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8479:         $file=~s:^/res/:/:;
                   8480:         if ( !( $file =~ m:^/:) ) {
                   8481:             $location = $dir. '/'.$file;
                   8482:         } else {
                   8483:             $location = '/home/httpd/html/res'.$file;
                   8484:         }
1.59      albertel 8485:     }
1.590     banghart 8486:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8487:     while ($location=~m{/\.\./}) {
                   8488: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8489: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8490: 	} else {
                   8491: 	    $location=~ s{/\.\./}{/}g;
                   8492: 	}
                   8493:     } #remove dir/..
1.590     banghart 8494:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8495:     return $location;
1.46      www      8496: }
1.36      albertel 8497: 
1.46      www      8498: sub hreflocation {
                   8499:     my ($dir,$file)=@_;
1.976.4.1  raeburn  8500:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8501: 	$file=filelocation($dir,$file);
1.700     albertel 8502:     } elsif ($file=~m-^/adm/-) {
                   8503: 	$file=~s-^/adm/wrapper/-/-;
                   8504: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8505:     }
                   8506:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8507: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8508:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8509: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8510:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8511: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8512: 	    -/uploaded/$1/$2/-x;
1.46      www      8513:     }
1.913     albertel 8514:     if ($file=~ m{^/userfiles/}) {
                   8515: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8516:     }
1.462     albertel 8517:     return $file;
1.465     albertel 8518: }
                   8519: 
                   8520: sub current_machine_domains {
1.853     albertel 8521:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8522: }
                   8523: 
                   8524: sub machine_domains {
                   8525:     my ($hostname) = @_;
1.465     albertel 8526:     my @domains;
1.838     albertel 8527:     my %hostname = &all_hostnames();
1.465     albertel 8528:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8529: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8530: 	if ($hostname eq $name) {
1.844     albertel 8531: 	    push(@domains,&host_domain($id));
1.465     albertel 8532: 	}
                   8533:     }
                   8534:     return @domains;
                   8535: }
                   8536: 
                   8537: sub current_machine_ids {
1.853     albertel 8538:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8539: }
                   8540: 
                   8541: sub machine_ids {
                   8542:     my ($hostname) = @_;
                   8543:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8544:     my @ids;
1.888     albertel 8545:     my %name_to_host = &all_names();
1.889     albertel 8546:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8547: 	return @{ $name_to_host{$hostname} };
                   8548:     }
                   8549:     return;
1.31      www      8550: }
                   8551: 
1.824     raeburn  8552: sub additional_machine_domains {
                   8553:     my @domains;
                   8554:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8555:     while( my $line = <$fh>) {
                   8556:         $line =~ s/\s//g;
                   8557:         push(@domains,$line);
                   8558:     }
                   8559:     return @domains;
                   8560: }
                   8561: 
                   8562: sub default_login_domain {
                   8563:     my $domain = $perlvar{'lonDefDomain'};
                   8564:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8565:     foreach my $posdom (&current_machine_domains(),
                   8566:                         &additional_machine_domains()) {
                   8567:         if (lc($posdom) eq lc($testdomain)) {
                   8568:             $domain=$posdom;
                   8569:             last;
                   8570:         }
                   8571:     }
                   8572:     return $domain;
                   8573: }
                   8574: 
1.31      www      8575: # ------------------------------------------------------------- Declutters URLs
                   8576: 
                   8577: sub declutter {
                   8578:     my $thisfn=shift;
1.569     albertel 8579:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8580:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8581:     $thisfn=~s/^\///;
1.697     albertel 8582:     $thisfn=~s|^adm/wrapper/||;
                   8583:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8584:     $thisfn=~s/^res\///;
1.235     www      8585:     $thisfn=~s/\?.+$//;
1.268     www      8586:     return $thisfn;
                   8587: }
                   8588: 
                   8589: # ------------------------------------------------------------- Clutter up URLs
                   8590: 
                   8591: sub clutter {
                   8592:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8593:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8594: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8595:        $thisfn='/res'.$thisfn; 
                   8596:     }
1.694     albertel 8597:     if ($thisfn !~m|/adm|) {
1.695     albertel 8598: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8599: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8600: 	} else {
                   8601: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8602: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8603: 	    if ($embstyle eq 'ssi'
                   8604: 		|| ($embstyle eq 'hdn')
                   8605: 		|| ($embstyle eq 'rat')
                   8606: 		|| ($embstyle eq 'prv')
                   8607: 		|| ($embstyle eq 'ign')) {
                   8608: 		#do nothing with these
                   8609: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8610: 		|| ($embstyle eq 'emb')
                   8611: 		|| ($embstyle eq 'wrp')) {
                   8612: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8613: 	    } elsif ($embstyle eq 'unk'
                   8614: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8615: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8616: 	    } else {
1.718     www      8617: #		&logthis("Got a blank emb style");
1.695     albertel 8618: 	    }
1.694     albertel 8619: 	}
                   8620:     }
1.31      www      8621:     return $thisfn;
1.12      www      8622: }
                   8623: 
1.787     albertel 8624: sub clutter_with_no_wrapper {
                   8625:     my $uri = &clutter(shift);
                   8626:     if ($uri =~ m-^/adm/-) {
                   8627: 	$uri =~ s-^/adm/wrapper/-/-;
                   8628: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8629:     }
                   8630:     return $uri;
                   8631: }
                   8632: 
1.557     albertel 8633: sub freeze_escape {
                   8634:     my ($value)=@_;
                   8635:     if (ref($value)) {
                   8636: 	$value=&nfreeze($value);
                   8637: 	return '__FROZEN__'.&escape($value);
                   8638:     }
                   8639:     return &escape($value);
                   8640: }
                   8641: 
1.11      www      8642: 
1.557     albertel 8643: sub thaw_unescape {
                   8644:     my ($value)=@_;
                   8645:     if ($value =~ /^__FROZEN__/) {
                   8646: 	substr($value,0,10,undef);
                   8647: 	$value=&unescape($value);
                   8648: 	return &thaw($value);
                   8649:     }
                   8650:     return &unescape($value);
                   8651: }
                   8652: 
1.436     albertel 8653: sub correct_line_ends {
                   8654:     my ($result)=@_;
                   8655:     $$result =~s/\r\n/\n/mg;
                   8656:     $$result =~s/\r/\n/mg;
1.415     albertel 8657: }
1.1       albertel 8658: # ================================================================ Main Program
                   8659: 
1.184     www      8660: sub goodbye {
1.204     albertel 8661:    &logthis("Starting Shut down");
1.443     albertel 8662: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8663:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8664: #converted
1.599     albertel 8665: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8666:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8667: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8668: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8669: #1.1 only
1.870     albertel 8670: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8671: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8672: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8673: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8674:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8675:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8676:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8677:    &flushcourselogs();
                   8678:    &logthis("Shutting down");
                   8679: }
                   8680: 
1.852     albertel 8681: sub get_dns {
1.869     albertel 8682:     my ($url,$func,$ignore_cache) = @_;
                   8683:     if (!$ignore_cache) {
                   8684: 	my ($content,$cached)=
                   8685: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8686: 	if ($cached) {
                   8687: 	    &$func($content);
                   8688: 	    return;
                   8689: 	}
                   8690:     }
                   8691: 
                   8692:     my %alldns;
1.852     albertel 8693:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8694:     foreach my $dns (<$config>) {
                   8695: 	next if ($dns !~ /^\^(\S*)/x);
1.976.4.1  raeburn  8696:         my $line = $1;
                   8697:         my ($host,$protocol) = split(/:/,$line);
                   8698:         if ($protocol ne 'https') {
                   8699:             $protocol = 'http';
                   8700:         }
                   8701: 	$alldns{$host} = $protocol;
1.869     albertel 8702:     }
                   8703:     while (%alldns) {
                   8704: 	my ($dns) = keys(%alldns);
1.852     albertel 8705: 	my $ua=new LWP::UserAgent;
1.976.4.1  raeburn  8706: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8707: 	my $response=$ua->request($request);
1.976.4.1  raeburn  8708:         delete($alldns{$dns});
1.852     albertel 8709: 	next if ($response->is_error());
                   8710: 	my @content = split("\n",$response->content);
1.869     albertel 8711: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8712: 	&$func(\@content);
1.869     albertel 8713: 	return;
1.852     albertel 8714:     }
                   8715:     close($config);
1.871     albertel 8716:     my $which = (split('/',$url))[3];
                   8717:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8718:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8719:     my @content = <$config>;
                   8720:     &$func(\@content);
                   8721:     return;
1.852     albertel 8722: }
1.327     albertel 8723: # ------------------------------------------------------------ Read domain file
                   8724: {
1.852     albertel 8725:     my $loaded;
1.846     albertel 8726:     my %domain;
                   8727: 
1.852     albertel 8728:     sub parse_domain_tab {
                   8729: 	my ($lines) = @_;
                   8730: 	foreach my $line (@$lines) {
                   8731: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8732: 
1.846     albertel 8733: 	    chomp($line);
1.852     albertel 8734: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8735: 	    my %this_domain;
                   8736: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8737: 			       'lang_def', 'city', 'longi', 'lati',
                   8738: 			       'primary') {
                   8739: 		$this_domain{$field} = shift(@elements);
                   8740: 	    }
                   8741: 	    $domain{$name} = \%this_domain;
1.852     albertel 8742: 	}
                   8743:     }
1.864     albertel 8744: 
                   8745:     sub reset_domain_info {
                   8746: 	undef($loaded);
                   8747: 	undef(%domain);
                   8748:     }
                   8749: 
1.852     albertel 8750:     sub load_domain_tab {
1.869     albertel 8751: 	my ($ignore_cache) = @_;
                   8752: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8753: 	my $fh;
                   8754: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8755: 	    my @lines = <$fh>;
                   8756: 	    &parse_domain_tab(\@lines);
1.448     albertel 8757: 	}
1.852     albertel 8758: 	close($fh);
                   8759: 	$loaded = 1;
1.327     albertel 8760:     }
1.846     albertel 8761: 
                   8762:     sub domain {
1.852     albertel 8763: 	&load_domain_tab() if (!$loaded);
                   8764: 
1.846     albertel 8765: 	my ($name,$what) = @_;
                   8766: 	return if ( !exists($domain{$name}) );
                   8767: 
                   8768: 	if (!$what) {
                   8769: 	    return $domain{$name}{'description'};
                   8770: 	}
                   8771: 	return $domain{$name}{$what};
                   8772:     }
1.974     raeburn  8773: 
                   8774:     sub domain_info {
                   8775:         &load_domain_tab() if (!$loaded);
                   8776:         return %domain;
                   8777:     }
                   8778: 
1.327     albertel 8779: }
                   8780: 
                   8781: 
1.1       albertel 8782: # ------------------------------------------------------------- Read hosts file
                   8783: {
1.838     albertel 8784:     my %hostname;
1.844     albertel 8785:     my %hostdom;
1.845     albertel 8786:     my %libserv;
1.852     albertel 8787:     my $loaded;
1.888     albertel 8788:     my %name_to_host;
1.852     albertel 8789: 
                   8790:     sub parse_hosts_tab {
                   8791: 	my ($file) = @_;
                   8792: 	foreach my $configline (@$file) {
                   8793: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8794: 	    next if ($configline =~ /^\^/);
                   8795: 	    chomp($configline);
1.968     raeburn  8796: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8797: 	    $name=~s/\s//g;
                   8798: 	    if ($id && $domain && $role && $name) {
                   8799: 		$hostname{$id}=$name;
1.888     albertel 8800: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8801: 		$hostdom{$id}=$domain;
                   8802: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8803:                 if (defined($protocol)) {
                   8804:                     if ($protocol eq 'https') {
                   8805:                         $protocol{$id} = $protocol;
                   8806:                     } else {
                   8807:                         $protocol{$id} = 'http'; 
                   8808:                     }
1.968     raeburn  8809:                 } else {
1.969     raeburn  8810:                     $protocol{$id} = 'http';
1.968     raeburn  8811:                 }
1.852     albertel 8812: 	    }
                   8813: 	}
                   8814:     }
1.864     albertel 8815:     
                   8816:     sub reset_hosts_info {
1.897     albertel 8817: 	&purge_remembered();
1.864     albertel 8818: 	&reset_domain_info();
                   8819: 	&reset_hosts_ip_info();
1.892     albertel 8820: 	undef(%name_to_host);
1.864     albertel 8821: 	undef(%hostname);
                   8822: 	undef(%hostdom);
                   8823: 	undef(%libserv);
                   8824: 	undef($loaded);
                   8825:     }
1.1       albertel 8826: 
1.852     albertel 8827:     sub load_hosts_tab {
1.869     albertel 8828: 	my ($ignore_cache) = @_;
                   8829: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8830: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8831: 	my @config = <$config>;
                   8832: 	&parse_hosts_tab(\@config);
                   8833: 	close($config);
                   8834: 	$loaded=1;
1.1       albertel 8835:     }
1.852     albertel 8836: 
1.838     albertel 8837:     sub hostname {
1.852     albertel 8838: 	&load_hosts_tab() if (!$loaded);
                   8839: 
1.838     albertel 8840: 	my ($lonid) = @_;
                   8841: 	return $hostname{$lonid};
                   8842:     }
1.845     albertel 8843: 
1.838     albertel 8844:     sub all_hostnames {
1.852     albertel 8845: 	&load_hosts_tab() if (!$loaded);
                   8846: 
1.838     albertel 8847: 	return %hostname;
                   8848:     }
1.845     albertel 8849: 
1.888     albertel 8850:     sub all_names {
                   8851: 	&load_hosts_tab() if (!$loaded);
                   8852: 
                   8853: 	return %name_to_host;
                   8854:     }
                   8855: 
1.974     raeburn  8856:     sub all_host_domain {
                   8857:         &load_hosts_tab() if (!$loaded);
                   8858:         return %hostdom;
                   8859:     }
                   8860: 
1.845     albertel 8861:     sub is_library {
1.852     albertel 8862: 	&load_hosts_tab() if (!$loaded);
                   8863: 
1.845     albertel 8864: 	return exists($libserv{$_[0]});
                   8865:     }
                   8866: 
                   8867:     sub all_library {
1.852     albertel 8868: 	&load_hosts_tab() if (!$loaded);
                   8869: 
1.845     albertel 8870: 	return %libserv;
                   8871:     }
                   8872: 
1.841     albertel 8873:     sub get_servers {
1.852     albertel 8874: 	&load_hosts_tab() if (!$loaded);
                   8875: 
1.841     albertel 8876: 	my ($domain,$type) = @_;
                   8877: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8878: 	                                          : %hostname;
                   8879: 	my %result;
1.842     albertel 8880: 	if (ref($domain) eq 'ARRAY') {
                   8881: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8882: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8883: 		    $result{$host} = $hostname;
                   8884: 		}
                   8885: 	    }
                   8886: 	} else {
                   8887: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8888: 		if ($hostdom{$host} eq $domain) {
                   8889: 		    $result{$host} = $hostname;
                   8890: 		}
1.841     albertel 8891: 	    }
                   8892: 	}
                   8893: 	return %result;
                   8894:     }
1.845     albertel 8895: 
1.844     albertel 8896:     sub host_domain {
1.852     albertel 8897: 	&load_hosts_tab() if (!$loaded);
                   8898: 
1.844     albertel 8899: 	my ($lonid) = @_;
                   8900: 	return $hostdom{$lonid};
                   8901:     }
                   8902: 
1.841     albertel 8903:     sub all_domains {
1.852     albertel 8904: 	&load_hosts_tab() if (!$loaded);
                   8905: 
1.841     albertel 8906: 	my %seen;
                   8907: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8908: 	return @uniq;
                   8909:     }
1.1       albertel 8910: }
                   8911: 
1.847     albertel 8912: { 
                   8913:     my %iphost;
1.856     albertel 8914:     my %name_to_ip;
                   8915:     my %lonid_to_ip;
1.869     albertel 8916: 
1.847     albertel 8917:     sub get_hosts_from_ip {
                   8918: 	my ($ip) = @_;
                   8919: 	my %iphosts = &get_iphost();
                   8920: 	if (ref($iphosts{$ip})) {
                   8921: 	    return @{$iphosts{$ip}};
                   8922: 	}
                   8923: 	return;
1.839     albertel 8924:     }
1.864     albertel 8925:     
                   8926:     sub reset_hosts_ip_info {
                   8927: 	undef(%iphost);
                   8928: 	undef(%name_to_ip);
                   8929: 	undef(%lonid_to_ip);
                   8930:     }
1.856     albertel 8931: 
                   8932:     sub get_host_ip {
                   8933: 	my ($lonid) = @_;
                   8934: 	if (exists($lonid_to_ip{$lonid})) {
                   8935: 	    return $lonid_to_ip{$lonid};
                   8936: 	}
                   8937: 	my $name=&hostname($lonid);
                   8938:    	my $ip = gethostbyname($name);
                   8939: 	return if (!$ip || length($ip) ne 4);
                   8940: 	$ip=inet_ntoa($ip);
                   8941: 	$name_to_ip{$name}   = $ip;
                   8942: 	$lonid_to_ip{$lonid} = $ip;
                   8943: 	return $ip;
                   8944:     }
1.847     albertel 8945:     
                   8946:     sub get_iphost {
1.869     albertel 8947: 	my ($ignore_cache) = @_;
1.894     albertel 8948: 
1.869     albertel 8949: 	if (!$ignore_cache) {
                   8950: 	    if (%iphost) {
                   8951: 		return %iphost;
                   8952: 	    }
                   8953: 	    my ($ip_info,$cached)=
                   8954: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8955: 	    if ($cached) {
                   8956: 		%iphost      = %{$ip_info->[0]};
                   8957: 		%name_to_ip  = %{$ip_info->[1]};
                   8958: 		%lonid_to_ip = %{$ip_info->[2]};
                   8959: 		return %iphost;
                   8960: 	    }
                   8961: 	}
1.894     albertel 8962: 
                   8963: 	# get yesterday's info for fallback
                   8964: 	my %old_name_to_ip;
                   8965: 	my ($ip_info,$cached)=
                   8966: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8967: 	if ($cached) {
                   8968: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8969: 	}
                   8970: 
1.888     albertel 8971: 	my %name_to_host = &all_names();
                   8972: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8973: 	    my $ip;
                   8974: 	    if (!exists($name_to_ip{$name})) {
                   8975: 		$ip = gethostbyname($name);
                   8976: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8977: 		    if (defined($old_name_to_ip{$name})) {
                   8978: 			$ip = $old_name_to_ip{$name};
                   8979: 			&logthis("Can't find $name defaulting to old $ip");
                   8980: 		    } else {
                   8981: 			&logthis("Name $name no IP found");
                   8982: 			next;
                   8983: 		    }
                   8984: 		} else {
                   8985: 		    $ip=inet_ntoa($ip);
1.847     albertel 8986: 		}
                   8987: 		$name_to_ip{$name} = $ip;
                   8988: 	    } else {
                   8989: 		$ip = $name_to_ip{$name};
1.653     albertel 8990: 	    }
1.888     albertel 8991: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8992: 		$lonid_to_ip{$id} = $ip;
                   8993: 	    }
                   8994: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8995: 	}
1.869     albertel 8996: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8997: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8998: 				      48*60*60);
1.869     albertel 8999: 
1.847     albertel 9000: 	return %iphost;
1.598     albertel 9001:     }
                   9002: }
                   9003: 
1.862     albertel 9004: BEGIN {
                   9005: 
                   9006: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9007:     unless ($readit) {
                   9008: {
                   9009:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9010:     %perlvar = (%perlvar,%{$configvars});
                   9011: }
                   9012: 
                   9013: 
1.1       albertel 9014: # ------------------------------------------------------ Read spare server file
                   9015: {
1.448     albertel 9016:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9017: 
                   9018:     while (my $configline=<$config>) {
                   9019:        chomp($configline);
1.284     matthew  9020:        if ($configline) {
1.784     albertel 9021: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9022: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9023: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9024:        }
                   9025:     }
1.448     albertel 9026:     close($config);
1.1       albertel 9027: }
1.11      www      9028: # ------------------------------------------------------------ Read permissions
                   9029: {
1.448     albertel 9030:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9031: 
                   9032:     while (my $configline=<$config>) {
1.448     albertel 9033: 	chomp($configline);
                   9034: 	if ($configline) {
                   9035: 	    my ($role,$perm)=split(/ /,$configline);
                   9036: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9037: 	}
1.11      www      9038:     }
1.448     albertel 9039:     close($config);
1.11      www      9040: }
                   9041: 
                   9042: # -------------------------------------------- Read plain texts for permissions
                   9043: {
1.448     albertel 9044:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9045: 
                   9046:     while (my $configline=<$config>) {
1.448     albertel 9047: 	chomp($configline);
                   9048: 	if ($configline) {
1.742     raeburn  9049: 	    my ($short,@plain)=split(/:/,$configline);
                   9050:             %{$prp{$short}} = ();
                   9051: 	    if (@plain > 0) {
                   9052:                 $prp{$short}{'std'} = $plain[0];
                   9053:                 for (my $i=1; $i<@plain; $i++) {
                   9054:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9055:                 }
                   9056:             }
1.448     albertel 9057: 	}
1.135     www      9058:     }
1.448     albertel 9059:     close($config);
1.135     www      9060: }
                   9061: 
                   9062: # ---------------------------------------------------------- Read package table
                   9063: {
1.448     albertel 9064:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9065: 
                   9066:     while (my $configline=<$config>) {
1.483     albertel 9067: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9068: 	chomp($configline);
                   9069: 	my ($short,$plain)=split(/:/,$configline);
                   9070: 	my ($pack,$name)=split(/\&/,$short);
                   9071: 	if ($plain ne '') {
                   9072: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9073: 	    $packagetab{$short}=$plain; 
                   9074: 	}
1.11      www      9075:     }
1.448     albertel 9076:     close($config);
1.329     matthew  9077: }
                   9078: 
                   9079: # ------------- set up temporary directory
                   9080: {
                   9081:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9082: 
1.11      www      9083: }
                   9084: 
1.794     albertel 9085: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9086: 				'compress_threshold'=> 20_000,
                   9087:  			        });
1.185     www      9088: 
1.281     www      9089: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9090: $dumpcount=0;
1.958     www      9091: $locknum=0;
1.22      www      9092: 
1.163     harris41 9093: &logtouch();
1.672     albertel 9094: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9095: $readit=1;
1.564     albertel 9096:     {
                   9097: 	use integer;
                   9098: 	my $test=(2**32)+1;
1.568     albertel 9099: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9100: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9101:     }
1.195     www      9102: }
1.1       albertel 9103: }
1.179     www      9104: 
1.1       albertel 9105: 1;
1.191     harris41 9106: __END__
                   9107: 
1.243     albertel 9108: =pod
                   9109: 
1.191     harris41 9110: =head1 NAME
                   9111: 
1.243     albertel 9112: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9113: 
                   9114: =head1 SYNOPSIS
                   9115: 
1.243     albertel 9116: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9117: 
                   9118:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9119: 
1.243     albertel 9120: Common parameters:
                   9121: 
                   9122: =over 4
                   9123: 
                   9124: =item *
                   9125: 
                   9126: $uname : an internal username (if $cname expecting a course Id specifically)
                   9127: 
                   9128: =item *
                   9129: 
                   9130: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9131: 
                   9132: =item *
                   9133: 
                   9134: $symb : a resource instance identifier
                   9135: 
                   9136: =item *
                   9137: 
                   9138: $namespace : the name of a .db file that contains the data needed or
                   9139: being set.
                   9140: 
                   9141: =back
                   9142: 
1.394     bowersj2 9143: =head1 OVERVIEW
1.191     harris41 9144: 
1.394     bowersj2 9145: lonnet provides subroutines which interact with the
                   9146: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9147: about classes, users, and resources.
1.243     albertel 9148: 
                   9149: For many of these objects you can also use this to store data about
                   9150: them or modify them in various ways.
1.191     harris41 9151: 
1.394     bowersj2 9152: =head2 Symbs
1.191     harris41 9153: 
1.394     bowersj2 9154: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9155: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9156: map, the resource number of the resource in the map, and the URL of
                   9157: the resource itself. The latter is somewhat redundant, but might help
                   9158: if maps change.
                   9159: 
                   9160: An example is
                   9161: 
                   9162:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9163: 
                   9164: The respective map entry is
                   9165: 
                   9166:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9167:   title="Problem 2">
                   9168:  </resource>
                   9169: 
                   9170: Symbs are used by the random number generator, as well as to store and
                   9171: restore data specific to a certain instance of for example a problem.
                   9172: 
                   9173: =head2 Storing And Retrieving Data
                   9174: 
                   9175: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9176: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9177: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9178: is is the non-critical message twin of cstore. These functions are for
                   9179: handlers to store a perl hash to a user's permanent data space in an
                   9180: easy manner, and to retrieve it again on another call. It is expected
                   9181: that a handler would use this once at the beginning to retrieve data,
                   9182: and then again once at the end to send only the new data back.
                   9183: 
                   9184: The data is stored in the user's data directory on the user's
                   9185: homeserver under the ID of the course.
                   9186: 
                   9187: The hash that is returned by restore will have all of the previous
                   9188: value for all of the elements of the hash.
                   9189: 
                   9190: Example:
                   9191: 
                   9192:  #creating a hash
                   9193:  my %hash;
                   9194:  $hash{'foo'}='bar';
                   9195: 
                   9196:  #storing it
                   9197:  &Apache::lonnet::cstore(\%hash);
                   9198: 
                   9199:  #changing a value
                   9200:  $hash{'foo'}='notbar';
                   9201: 
                   9202:  #adding a new value
                   9203:  $hash{'bar'}='foo';
                   9204:  &Apache::lonnet::cstore(\%hash);
                   9205: 
                   9206:  #retrieving the hash
                   9207:  my %history=&Apache::lonnet::restore();
                   9208: 
                   9209:  #print the hash
                   9210:  foreach my $key (sort(keys(%history))) {
                   9211:    print("\%history{$key} = $history{$key}");
                   9212:  }
                   9213: 
                   9214: Will print out:
1.191     harris41 9215: 
1.394     bowersj2 9216:  %history{1:foo} = bar
                   9217:  %history{1:keys} = foo:timestamp
                   9218:  %history{1:timestamp} = 990455579
                   9219:  %history{2:bar} = foo
                   9220:  %history{2:foo} = notbar
                   9221:  %history{2:keys} = foo:bar:timestamp
                   9222:  %history{2:timestamp} = 990455580
                   9223:  %history{bar} = foo
                   9224:  %history{foo} = notbar
                   9225:  %history{timestamp} = 990455580
                   9226:  %history{version} = 2
                   9227: 
                   9228: Note that the special hash entries C<keys>, C<version> and
                   9229: C<timestamp> were added to the hash. C<version> will be equal to the
                   9230: total number of versions of the data that have been stored. The
                   9231: C<timestamp> attribute will be the UNIX time the hash was
                   9232: stored. C<keys> is available in every historical section to list which
                   9233: keys were added or changed at a specific historical revision of a
                   9234: hash.
                   9235: 
                   9236: B<Warning>: do not store the hash that restore returns directly. This
                   9237: will cause a mess since it will restore the historical keys as if the
                   9238: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9239: 
1.394     bowersj2 9240: Calling convention:
1.191     harris41 9241: 
1.394     bowersj2 9242:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9243:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9244: 
1.394     bowersj2 9245: For more detailed information, see lonnet specific documentation.
1.191     harris41 9246: 
1.394     bowersj2 9247: =head1 RETURN MESSAGES
1.191     harris41 9248: 
1.394     bowersj2 9249: =over 4
1.191     harris41 9250: 
1.394     bowersj2 9251: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9252: 
1.394     bowersj2 9253: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9254: when the connection is brought back up
1.191     harris41 9255: 
1.394     bowersj2 9256: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9257: for later delivery
1.191     harris41 9258: 
1.967     bisitz   9259: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9260: 
1.394     bowersj2 9261: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9262: that was requested
1.191     harris41 9263: 
1.243     albertel 9264: =back
1.191     harris41 9265: 
1.243     albertel 9266: =head1 PUBLIC SUBROUTINES
1.191     harris41 9267: 
1.243     albertel 9268: =head2 Session Environment Functions
1.191     harris41 9269: 
1.243     albertel 9270: =over 4
1.191     harris41 9271: 
1.394     bowersj2 9272: =item * 
                   9273: X<appenv()>
1.949     raeburn  9274: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9275: the user envirnoment file, and will be restored for each access this
1.620     albertel 9276: user makes during this session, also modifies the %env for the current
1.949     raeburn  9277: process. Optional rolesarrayref - if defined contains a reference to an array
                   9278: of roles which are exempt from the restriction on modifying user.role entries 
                   9279: in the user's environment.db and in %env.    
1.191     harris41 9280: 
                   9281: =item *
1.394     bowersj2 9282: X<delenv()>
1.976.4.1  raeburn  9283: B<delenv($delthis,$regexp)>: removes all items from the session
                   9284: environment file that begin with $delthis. If the
                   9285: optional second arg - $regexp - is true, $delthis is treated as a
                   9286: regular expression, otherwise \Q$delthis\E is used.
                   9287: The values are also deleted from the current processes %env.
1.191     harris41 9288: 
1.795     albertel 9289: =item * get_env_multiple($name) 
                   9290: 
                   9291: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9292: values may be defined and end up as an array ref.
                   9293: 
                   9294: returns an array of values
                   9295: 
1.243     albertel 9296: =back
                   9297: 
                   9298: =head2 User Information
1.191     harris41 9299: 
1.243     albertel 9300: =over 4
1.191     harris41 9301: 
                   9302: =item *
1.394     bowersj2 9303: X<queryauthenticate()>
                   9304: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9305: authentication scheme
                   9306: 
                   9307: =item *
1.394     bowersj2 9308: X<authenticate()>
                   9309: B<authenticate($uname,$upass,$udom)>: try to
                   9310: authenticate user from domain's lib servers (first use the current
                   9311: one). C<$upass> should be the users password.
1.191     harris41 9312: 
                   9313: =item *
1.394     bowersj2 9314: X<homeserver()>
                   9315: B<homeserver($uname,$udom)>: find the server which has
                   9316: the user's directory and files (there must be only one), this caches
                   9317: the answer, and also caches if there is a borken connection.
1.191     harris41 9318: 
                   9319: =item *
1.394     bowersj2 9320: X<idget()>
                   9321: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9322: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9323: username, and only 1 username per ID in a specific domain) (returns
                   9324: hash: id=>name,id=>name)
1.191     harris41 9325: 
                   9326: =item *
1.394     bowersj2 9327: X<idrget()>
                   9328: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9329: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9330: 
                   9331: =item *
1.394     bowersj2 9332: X<idput()>
                   9333: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9334: 
                   9335: =item *
1.394     bowersj2 9336: X<rolesinit()>
                   9337: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9338: 
                   9339: =item *
1.551     albertel 9340: X<getsection()>
                   9341: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9342: course $cname, return section name/number or '' for "not in course"
                   9343: and '-1' for "no section"
                   9344: 
                   9345: =item *
1.394     bowersj2 9346: X<userenvironment()>
                   9347: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9348: passed in @what from the requested user's environment, returns a hash
                   9349: 
1.858     raeburn  9350: =item * 
                   9351: X<userlog_query()>
1.859     albertel 9352: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9353: activity.log file. %filters defines filters applied when parsing the
                   9354: log file. These can be start or end timestamps, or the type of action
                   9355: - log to look for Login or Logout events, check for Checkin or
                   9356: Checkout, role for role selection. The response is in the form
                   9357: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9358: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9359: 
1.243     albertel 9360: =back
                   9361: 
                   9362: =head2 User Roles
                   9363: 
                   9364: =over 4
                   9365: 
                   9366: =item *
                   9367: 
1.810     raeburn  9368: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9369:  F: full access
                   9370:  U,I,K: authentication modes (cxx only)
                   9371:  '': forbidden
                   9372:  1: user needs to choose course
                   9373:  2: browse allowed
1.766     albertel 9374:  A: passphrase authentication needed
1.243     albertel 9375: 
                   9376: =item *
                   9377: 
                   9378: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9379: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9380: and course level
                   9381: 
                   9382: =item *
                   9383: 
1.976.4.2! raeburn  9384: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
        !          9385: (rolesplain.tab); plain text explanation of a user role term.
        !          9386: $type is Course (default) or Community.
        !          9387: If $forcedefault evaluates to true, text returned will be default
        !          9388: text for $type. Otherwise, if this is a course, the text returned
        !          9389: will be a custom name for the role (if defined in the course's
        !          9390: environment).  If no custom name is defined the default is returned.
1.243     albertel 9391: 
1.832     raeburn  9392: =item *
                   9393: 
1.935     raeburn  9394: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9395: All arguments are optional. Returns a hash of a roles, either for
                   9396: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9397: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9398: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9399: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9400: For each key, value is set to colon-separated start and end times for
                   9401: the role.  If no username and domain are specified, will default to
1.934     raeburn  9402: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9403: of role statuses (active, future or previous), roles 
                   9404: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9405: to restrict the list of roles reported. If no array ref is 
                   9406: provided for types, will default to return only active roles.
1.834     albertel 9407: 
1.243     albertel 9408: =back
                   9409: 
                   9410: =head2 User Modification
                   9411: 
                   9412: =over 4
                   9413: 
                   9414: =item *
                   9415: 
1.957     raeburn  9416: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9417: user for the level given by URL.  Optional start and end dates (leave empty
                   9418: string or zero for "no date")
1.191     harris41 9419: 
                   9420: =item *
                   9421: 
1.243     albertel 9422: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9423: change a users, password, possible return values are: ok,
                   9424: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9425: refused
1.191     harris41 9426: 
                   9427: =item *
                   9428: 
1.243     albertel 9429: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9430: 
                   9431: =item *
                   9432: 
1.963     raeburn  9433: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9434:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9435: modify user
1.191     harris41 9436: 
                   9437: =item *
                   9438: 
1.286     matthew  9439: modifystudent
                   9440: 
1.957     raeburn  9441: modify a student's enrollment and identification information.
1.286     matthew  9442: The course id is resolved based on the current users environment.  
                   9443: This means the envoking user must be a course coordinator or otherwise
                   9444: associated with a course.
                   9445: 
1.297     matthew  9446: This call is essentially a wrapper for lonnet::modifyuser and
                   9447: lonnet::modify_student_enrollment
1.286     matthew  9448: 
                   9449: Inputs: 
                   9450: 
                   9451: =over 4
                   9452: 
1.957     raeburn  9453: =item B<$udom> Student's loncapa domain
1.286     matthew  9454: 
1.957     raeburn  9455: =item B<$uname> Student's loncapa login name
1.286     matthew  9456: 
1.964     bisitz   9457: =item B<$uid> Student/Employee ID
1.286     matthew  9458: 
1.957     raeburn  9459: =item B<$umode> Student's authentication mode
1.286     matthew  9460: 
1.957     raeburn  9461: =item B<$upass> Student's password
1.286     matthew  9462: 
1.957     raeburn  9463: =item B<$first> Student's first name
1.286     matthew  9464: 
1.957     raeburn  9465: =item B<$middle> Student's middle name
1.286     matthew  9466: 
1.957     raeburn  9467: =item B<$last> Student's last name
1.286     matthew  9468: 
1.957     raeburn  9469: =item B<$gene> Student's generation
1.286     matthew  9470: 
1.957     raeburn  9471: =item B<$usec> Student's section in course
1.286     matthew  9472: 
                   9473: =item B<$end> Unix time of the roles expiration
                   9474: 
                   9475: =item B<$start> Unix time of the roles start date
                   9476: 
                   9477: =item B<$forceid> If defined, allow $uid to be changed
                   9478: 
                   9479: =item B<$desiredhome> server to use as home server for student
                   9480: 
1.957     raeburn  9481: =item B<$email> Student's permanent e-mail address
                   9482: 
                   9483: =item B<$type> Type of enrollment (auto or manual)
                   9484: 
1.963     raeburn  9485: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9486: 
                   9487: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9488: 
1.963     raeburn  9489: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9490: 
1.963     raeburn  9491: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9492: 
1.963     raeburn  9493: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9494: 
1.286     matthew  9495: =back
1.297     matthew  9496: 
                   9497: =item *
                   9498: 
                   9499: modify_student_enrollment
                   9500: 
                   9501: Change a students enrollment status in a class.  The environment variable
                   9502: 'role.request.course' must be defined for this function to proceed.
                   9503: 
                   9504: Inputs:
                   9505: 
                   9506: =over 4
                   9507: 
                   9508: =item $udom, students domain
                   9509: 
                   9510: =item $uname, students name
                   9511: 
                   9512: =item $uid, students user id
                   9513: 
                   9514: =item $first, students first name
                   9515: 
                   9516: =item $middle
                   9517: 
                   9518: =item $last
                   9519: 
                   9520: =item $gene
                   9521: 
                   9522: =item $usec
                   9523: 
                   9524: =item $end
                   9525: 
                   9526: =item $start
                   9527: 
1.957     raeburn  9528: =item $type
                   9529: 
                   9530: =item $locktype
                   9531: 
                   9532: =item $cid
                   9533: 
                   9534: =item $selfenroll
                   9535: 
                   9536: =item $context
                   9537: 
1.297     matthew  9538: =back
                   9539: 
1.191     harris41 9540: 
                   9541: =item *
                   9542: 
1.243     albertel 9543: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9544: custom role; give a custom role to a user for the level given by URL.  Specify
                   9545: name and domain of role author, and role name
1.191     harris41 9546: 
                   9547: =item *
                   9548: 
1.243     albertel 9549: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9550: 
                   9551: =item *
                   9552: 
1.243     albertel 9553: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9554: 
                   9555: =back
                   9556: 
                   9557: =head2 Course Infomation
                   9558: 
                   9559: =over 4
1.191     harris41 9560: 
                   9561: =item *
                   9562: 
1.631     albertel 9563: coursedescription($courseid) : returns a hash of information about the
                   9564: specified course id, including all environment settings for the
                   9565: course, the description of the course will be in the hash under the
                   9566: key 'description'
1.191     harris41 9567: 
                   9568: =item *
                   9569: 
1.624     albertel 9570: resdata($name,$domain,$type,@which) : request for current parameter
                   9571: setting for a specific $type, where $type is either 'course' or 'user',
                   9572: @what should be a list of parameters to ask about. This routine caches
                   9573: answers for 5 minutes.
1.243     albertel 9574: 
1.877     foxr     9575: =item *
                   9576: 
                   9577: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9578: data base, returning a hash that is keyed by the resource name and has
                   9579: values that are the resource value.  I believe that the timestamps and
                   9580: versions are also returned.
                   9581: 
                   9582: 
1.243     albertel 9583: =back
                   9584: 
                   9585: =head2 Course Modification
                   9586: 
                   9587: =over 4
1.191     harris41 9588: 
                   9589: =item *
                   9590: 
1.243     albertel 9591: writecoursepref($courseid,%prefs) : write preferences (environment
                   9592: database) for a course
1.191     harris41 9593: 
                   9594: =item *
                   9595: 
1.243     albertel 9596: createcourse($udom,$description,$url) : make/modify course
                   9597: 
                   9598: =back
                   9599: 
                   9600: =head2 Resource Subroutines
                   9601: 
                   9602: =over 4
1.191     harris41 9603: 
                   9604: =item *
                   9605: 
1.243     albertel 9606: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9607: 
                   9608: =item *
                   9609: 
1.243     albertel 9610: repcopy($filename) : subscribes to the requested file, and attempts to
                   9611: replicate from the owning library server, Might return
1.607     raeburn  9612: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9613: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9614: resource. Expects the local filesystem pathname
                   9615: (/home/httpd/html/res/....)
                   9616: 
                   9617: =back
                   9618: 
                   9619: =head2 Resource Information
                   9620: 
                   9621: =over 4
1.191     harris41 9622: 
                   9623: =item *
                   9624: 
1.243     albertel 9625: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9626: a vairety of different possible values, $varname should be a request
                   9627: string, and the other parameters can be used to specify who and what
                   9628: one is asking about.
                   9629: 
                   9630: Possible values for $varname are environment.lastname (or other item
                   9631: from the envirnment hash), user.name (or someother aspect about the
                   9632: user), resource.0.maxtries (or some other part and parameter of a
                   9633: resource)
1.204     albertel 9634: 
                   9635: =item *
                   9636: 
1.243     albertel 9637: directcondval($number) : get current value of a condition; reads from a state
                   9638: string
1.204     albertel 9639: 
                   9640: =item *
                   9641: 
1.243     albertel 9642: condval($condidx) : value of condition index based on state
1.204     albertel 9643: 
                   9644: =item *
                   9645: 
1.243     albertel 9646: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9647: resource's metadata, $what should be either a specific key, or either
                   9648: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9649: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9650: 
                   9651: this function automatically caches all requests
1.191     harris41 9652: 
                   9653: =item *
                   9654: 
1.243     albertel 9655: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9656: network of library servers; returns file handle of where SQL and regex results
                   9657: will be stored for query
1.191     harris41 9658: 
                   9659: =item *
                   9660: 
1.243     albertel 9661: symbread($filename) : return symbolic list entry (filename argument optional);
                   9662: returns the data handle
1.191     harris41 9663: 
                   9664: =item *
                   9665: 
1.243     albertel 9666: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9667: a possible symb for the URL in $thisfn, and if is an encryypted
                   9668: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9669: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9670: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9671: 
1.191     harris41 9672: 
                   9673: =item *
                   9674: 
1.243     albertel 9675: symbclean($symb) : removes versions numbers from a symb, returns the
                   9676: cleaned symb
1.191     harris41 9677: 
                   9678: =item *
                   9679: 
1.243     albertel 9680: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9681: course map, user must be in a course for it to work.
1.191     harris41 9682: 
                   9683: =item *
                   9684: 
1.243     albertel 9685: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9686: 
                   9687: =item *
                   9688: 
1.243     albertel 9689: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9690: a random seed, all arguments are optional, if they aren't sent it uses the
                   9691: environment to derive them. Note: if symb isn't sent and it can't get one
                   9692: from &symbread it will use the current time as its return value
1.191     harris41 9693: 
                   9694: =item *
                   9695: 
1.243     albertel 9696: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9697: unfakeable, receipt
1.191     harris41 9698: 
                   9699: =item *
                   9700: 
1.620     albertel 9701: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9702: 
                   9703: =item *
                   9704: 
1.243     albertel 9705: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9706: 
                   9707: =item *
                   9708: 
1.243     albertel 9709: 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 9710: 
                   9711: =item *
                   9712: 
1.243     albertel 9713: 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 9714: 
                   9715: =item *
                   9716: 
1.243     albertel 9717: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9718: 
                   9719: =item *
                   9720: 
1.243     albertel 9721: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9722: forcing spreadsheet to reevaluate the resource scores next time.
                   9723: 
                   9724: =back
                   9725: 
                   9726: =head2 Storing/Retreiving Data
                   9727: 
                   9728: =over 4
1.191     harris41 9729: 
                   9730: =item *
                   9731: 
1.243     albertel 9732: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9733: for this url; hashref needs to be given and should be a \%hashname; the
                   9734: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9735: be derived from the env
1.191     harris41 9736: 
                   9737: =item *
                   9738: 
1.243     albertel 9739: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9740: uses critical subroutine
1.191     harris41 9741: 
                   9742: =item *
                   9743: 
1.243     albertel 9744: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9745: all args are optional
1.191     harris41 9746: 
                   9747: =item *
                   9748: 
1.717     albertel 9749: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9750: dumps the complete (or key matching regexp) namespace into a hash
                   9751: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9752: normally &store()ed into
                   9753: 
                   9754: $range should be either an integer '100' (give me the first 100
                   9755:                                            matching records)
                   9756:               or be  two integers sperated by a - with no spaces
                   9757:                  '30-50' (give me the 30th through the 50th matching
                   9758:                           records)
                   9759: 
                   9760: 
                   9761: =item *
                   9762: 
                   9763: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9764: replaces a &store() version of data with a replacement set of data
                   9765: for a particular resource in a namespace passed in the $storehash hash 
                   9766: reference
                   9767: 
                   9768: =item *
                   9769: 
1.243     albertel 9770: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9771: works very similar to store/cstore, but all data is stored in a
                   9772: temporary location and can be reset using tmpreset, $storehash should
                   9773: be a hash reference, returns nothing on success
1.191     harris41 9774: 
                   9775: =item *
                   9776: 
1.243     albertel 9777: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9778: similar to restore, but all data is stored in a temporary location and
                   9779: can be reset using tmpreset. Returns a hash of values on success,
                   9780: error string otherwise.
1.191     harris41 9781: 
                   9782: =item *
                   9783: 
1.243     albertel 9784: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9785: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9786: 
                   9787: =item *
                   9788: 
1.243     albertel 9789: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9790: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9791: 
                   9792: =item *
                   9793: 
1.243     albertel 9794: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9795: namesp ($udom and $uname are optional)
1.191     harris41 9796: 
                   9797: =item *
                   9798: 
1.702     albertel 9799: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9800: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9801: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9802: 
1.702     albertel 9803: $range should be either an integer '100' (give me the first 100
                   9804:                                            matching records)
                   9805:               or be  two integers sperated by a - with no spaces
                   9806:                  '30-50' (give me the 30th through the 50th matching
                   9807:                           records)
1.449     matthew  9808: =item *
                   9809: 
                   9810: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9811: $store can be a scalar, an array reference, or if the amount to be 
                   9812: incremented is > 1, a hash reference.
                   9813: 
                   9814: ($udom and $uname are optional)
1.191     harris41 9815: 
                   9816: =item *
                   9817: 
1.243     albertel 9818: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9819: ($udom and $uname are optional)
1.191     harris41 9820: 
                   9821: =item *
                   9822: 
1.243     albertel 9823: cput($namespace,$storehash,$udom,$uname) : critical put
                   9824: ($udom and $uname are optional)
1.191     harris41 9825: 
                   9826: =item *
                   9827: 
1.748     albertel 9828: newput($namespace,$storehash,$udom,$uname) :
                   9829: 
                   9830: Attempts to store the items in the $storehash, but only if they don't
                   9831: currently exist, if this succeeds you can be certain that you have 
                   9832: successfully created a new key value pair in the $namespace db.
                   9833: 
                   9834: 
                   9835: Args:
                   9836:  $namespace: name of database to store values to
                   9837:  $storehash: hashref to store to the db
                   9838:  $udom: (optional) domain of user containing the db
                   9839:  $uname: (optional) name of user caontaining the db
                   9840: 
                   9841: Returns:
                   9842:  'ok' -> succeeded in storing all keys of $storehash
                   9843:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9844:                         least <key> already existed in the db (other
                   9845:                         requested keys may also already exist)
1.967     bisitz   9846:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9847:  'con_lost' -> unable to contact request server
                   9848:  'refused' -> action was not allowed by remote machine
                   9849: 
                   9850: 
                   9851: =item *
                   9852: 
1.243     albertel 9853: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9854: reference filled in from namesp (encrypts the return communication)
                   9855: ($udom and $uname are optional)
1.191     harris41 9856: 
                   9857: =item *
                   9858: 
1.243     albertel 9859: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9860: critical subroutine
                   9861: 
1.806     raeburn  9862: =item *
                   9863: 
1.860     raeburn  9864: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9865: array reference filled in from namespace found in domain level on either
                   9866: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9867: 
                   9868: =item *
                   9869: 
1.860     raeburn  9870: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9871: domain level either on specified domain server ($uhome) or primary domain 
                   9872: server ($udom and $uhome are optional)
1.806     raeburn  9873: 
1.943     raeburn  9874: =item * 
                   9875: 
                   9876: get_domain_defaults($target_domain) : returns hash with defaults for
                   9877: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9878: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9879: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9880: Values are retrieved from cache (if current), or from domain's configuration.db
                   9881: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9882: or lonTabs/domain.tab. 
                   9883: 
                   9884: %domdefaults = &get_auth_defaults($target_domain);
                   9885: 
1.243     albertel 9886: =back
                   9887: 
                   9888: =head2 Network Status Functions
                   9889: 
                   9890: =over 4
1.191     harris41 9891: 
                   9892: =item *
                   9893: 
                   9894: dirlist($uri) : return directory list based on URI
                   9895: 
                   9896: =item *
                   9897: 
1.243     albertel 9898: spareserver() : find server with least workload from spare.tab
                   9899: 
                   9900: =back
                   9901: 
                   9902: =head2 Apache Request
                   9903: 
                   9904: =over 4
1.191     harris41 9905: 
                   9906: =item *
                   9907: 
1.243     albertel 9908: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9909: localhost, posts hash
                   9910: 
                   9911: =back
                   9912: 
                   9913: =head2 Data to String to Data
                   9914: 
                   9915: =over 4
1.191     harris41 9916: 
                   9917: =item *
                   9918: 
1.243     albertel 9919: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9920: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9921: 
                   9922: =item *
                   9923: 
1.243     albertel 9924: hashref2str($hashref) : convert a hashref into a string complete with
                   9925: escaping and '=' and '&' separators, supports elements that are
                   9926: arrayrefs and hashrefs
1.191     harris41 9927: 
                   9928: =item *
                   9929: 
1.243     albertel 9930: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9931: with escaping and '&' separators, supports elements that are arrayrefs
                   9932: and hashrefs
1.191     harris41 9933: 
                   9934: =item *
                   9935: 
1.243     albertel 9936: str2hash($string) : convert string to hash using unescaping and
                   9937: splitting on '=' and '&', supports elements that are arrayrefs and
                   9938: hashrefs
1.191     harris41 9939: 
                   9940: =item *
                   9941: 
1.243     albertel 9942: str2array($string) : convert string to hash using unescaping and
                   9943: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9944: 
                   9945: =back
                   9946: 
                   9947: =head2 Logging Routines
                   9948: 
                   9949: =over 4
                   9950: 
                   9951: These routines allow one to make log messages in the lonnet.log and
                   9952: lonnet.perm logfiles.
1.191     harris41 9953: 
                   9954: =item *
                   9955: 
1.243     albertel 9956: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9957: 
                   9958: =item *
                   9959: 
1.243     albertel 9960: logthis() : append message to the normal lonnet.log file, it gets
                   9961: preiodically rolled over and deleted.
1.191     harris41 9962: 
                   9963: =item *
                   9964: 
1.243     albertel 9965: logperm() : append a permanent message to lonnet.perm.log, this log
                   9966: file never gets deleted by any automated portion of the system, only
                   9967: messages of critical importance should go in here.
                   9968: 
                   9969: =back
                   9970: 
                   9971: =head2 General File Helper Routines
                   9972: 
                   9973: =over 4
1.191     harris41 9974: 
                   9975: =item *
                   9976: 
1.481     raeburn  9977: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9978: (a) files in /uploaded
                   9979:   (i) If a local copy of the file exists - 
                   9980:       compares modification date of local copy with last-modified date for 
                   9981:       definitive version stored on home server for course. If local copy is 
                   9982:       stale, requests a new version from the home server and stores it. 
                   9983:       If the original has been removed from the home server, then local copy 
                   9984:       is unlinked.
                   9985:   (ii) If local copy does not exist -
                   9986:       requests the file from the home server and stores it. 
                   9987:   
                   9988:   If $caller is 'uploadrep':  
                   9989:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9990:     for request for files originally uploaded via DOCS. 
                   9991:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9992:   
                   9993:   Otherwise:
                   9994:      This indicates a call from the content generation phase of the request.
                   9995:      -  returns the entire contents of the file or -1.
                   9996:      
                   9997: (b) files in /res
                   9998:    - returns the entire contents of a file or -1; 
                   9999:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10000: 
1.712     albertel 10001: 
                   10002: =item *
                   10003: 
                   10004: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10005:                   reference
                   10006: 
                   10007: returns either a stat() list of data about the file or an empty list
                   10008: if the file doesn't exist or couldn't find out about it (connection
                   10009: problems or user unknown)
                   10010: 
1.191     harris41 10011: =item *
                   10012: 
1.243     albertel 10013: filelocation($dir,$file) : returns file system location of a file
                   10014: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10015: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10016: and a file of ../bob will become /a/bob)
1.191     harris41 10017: 
                   10018: =item *
                   10019: 
                   10020: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10021: filelocation except for hrefs
                   10022: 
                   10023: =item *
                   10024: 
                   10025: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10026: 
1.243     albertel 10027: =back
                   10028: 
1.608     albertel 10029: =head2 Usererfile file routines (/uploaded*)
                   10030: 
                   10031: =over 4
                   10032: 
                   10033: =item *
                   10034: 
                   10035: userfileupload(): main rotine for putting a file in a user or course's
                   10036:                   filespace, arguments are,
                   10037: 
1.620     albertel 10038:  formname - required - this is the name of the element in $env where the
1.608     albertel 10039:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10040:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10041:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10042:  coursedoc - if true, store the file in the course of the active role
                   10043:              of the current user
                   10044:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10045:          if undefined, it will be placed in "unknown"
                   10046: 
                   10047:  (This routine calls clean_filename() to remove any dangerous
                   10048:  characters from the filename, and then calls finuserfileupload() to
                   10049:  complete the transaction)
                   10050: 
                   10051:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10052:  and /adm/notfound.html if unsuccessful
                   10053: 
                   10054: =item *
                   10055: 
                   10056: clean_filename(): routine for cleaing a filename up for storage in
                   10057:                  userfile space, argument is:
                   10058: 
                   10059:  filename - proposed filename
                   10060: 
                   10061: returns: the new clean filename
                   10062: 
                   10063: =item *
                   10064: 
                   10065: finishuserfileupload(): routine that creaes and sends the file to
                   10066: userspace, probably shouldn't be called directly
                   10067: 
                   10068:   docuname: username or courseid of destination for the file
                   10069:   docudom: domain of user/course of destination for the file
                   10070:   formname: same as for userfileupload()
                   10071:   fname: filename (inculding subdirectories) for the file
                   10072: 
                   10073:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10074:  and /adm/notfound.html if unsuccessful
                   10075: 
                   10076: =item *
                   10077: 
                   10078: renameuserfile(): renames an existing userfile to a new name
                   10079: 
                   10080:   Args:
                   10081:    docuname: username or courseid of destination for the file
                   10082:    docudom: domain of user/course of destination for the file
                   10083:    old: current file name (including any subdirs under userfiles)
                   10084:    new: desired file name (including any subdirs under userfiles)
                   10085: 
                   10086: =item *
                   10087: 
                   10088: mkdiruserfile(): creates a directory is a userfiles dir
                   10089: 
                   10090:   Args:
                   10091:    docuname: username or courseid of destination for the file
                   10092:    docudom: domain of user/course of destination for the file
                   10093:    dir: dir to create (including any subdirs under userfiles)
                   10094: 
                   10095: =item *
                   10096: 
                   10097: removeuserfile(): removes a file that exists in userfiles
                   10098: 
                   10099:   Args:
                   10100:    docuname: username or courseid of destination for the file
                   10101:    docudom: domain of user/course of destination for the file
                   10102:    fname: filname to delete (including any subdirs under userfiles)
                   10103: 
                   10104: =item *
                   10105: 
                   10106: removeuploadedurl(): convience function for removeuserfile()
                   10107: 
                   10108:   Args:
                   10109:    url:  a full /uploaded/... url to delete
                   10110: 
1.747     albertel 10111: =item * 
                   10112: 
                   10113: get_portfile_permissions():
                   10114:   Args:
                   10115:     domain: domain of user or course contain the portfolio files
                   10116:     user: name of user or num of course contain the portfolio files
                   10117:   Returns:
                   10118:     hashref of a dump of the proper file_permissions.db
                   10119:    
                   10120: 
                   10121: =item * 
                   10122: 
                   10123: get_access_controls():
                   10124: 
                   10125: Args:
                   10126:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10127:   group: (optional) the group you want the files associated with
                   10128:   file: (optional) the file you want access info on
                   10129: 
                   10130: Returns:
1.749     raeburn  10131:     a hash (keys are file names) of hashes containing
                   10132:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10133:         values are XML containing access control settings (see below) 
1.747     albertel 10134: 
                   10135: Internal notes:
                   10136: 
1.749     raeburn  10137:  access controls are stored in file_permissions.db as key=value pairs.
                   10138:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10139:         where scope -> public,guest,course,group,domains or users.
                   10140:               end -> UNIX time for end of access (0 -> no end date)
                   10141:               start -> UNIX time for start of access
                   10142: 
                   10143:     value -> XML description of access control
                   10144:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10145:             <start></start>
                   10146:             <end></end>
                   10147: 
                   10148:             <password></password>  for scope type = guest
                   10149: 
                   10150:             <domain></domain>     for scope type = course or group
                   10151:             <number></number>
                   10152:             <roles id="">
                   10153:              <role></role>
                   10154:              <access></access>
                   10155:              <section></section>
                   10156:              <group></group>
                   10157:             </roles>
                   10158: 
                   10159:             <dom></dom>         for scope type = domains
                   10160: 
                   10161:             <users>             for scope type = users
                   10162:              <user>
                   10163:               <uname></uname>
                   10164:               <udom></udom>
                   10165:              </user>
                   10166:             </users>
                   10167:            </scope> 
                   10168:               
                   10169:  Access data is also aggregated for each file in an additional key=value pair:
                   10170:  key -> path to file/file_name\0accesscontrol 
                   10171:  value -> reference to hash
                   10172:           hash contains key = value pairs
                   10173:           where key = uniqueID:scope_end_start
                   10174:                 value = UNIX time record was last updated
                   10175: 
                   10176:           Used to improve speed of look-ups of access controls for each file.  
                   10177:  
                   10178:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10179: 
                   10180: modify_access_controls():
                   10181: 
                   10182: Modifies access controls for a portfolio file
                   10183: Args
                   10184: 1. file name
                   10185: 2. reference to hash of required changes,
                   10186: 3. domain
                   10187: 4. username
                   10188:   where domain,username are the domain of the portfolio owner 
                   10189:   (either a user or a course) 
                   10190: 
                   10191: Returns:
                   10192: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10193: 2. result of deletions ('ok' or 'error', with error message).
                   10194: 3. reference to hash of any new or updated access controls.
                   10195: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10196:    key = integer (inbound ID)
                   10197:    value = uniqueID  
1.747     albertel 10198: 
1.608     albertel 10199: =back
                   10200: 
1.243     albertel 10201: =head2 HTTP Helper Routines
                   10202: 
                   10203: =over 4
                   10204: 
1.191     harris41 10205: =item *
                   10206: 
                   10207: escape() : unpack non-word characters into CGI-compatible hex codes
                   10208: 
                   10209: =item *
                   10210: 
                   10211: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10212: 
1.243     albertel 10213: =back
                   10214: 
                   10215: =head1 PRIVATE SUBROUTINES
                   10216: 
                   10217: =head2 Underlying communication routines (Shouldn't call)
                   10218: 
                   10219: =over 4
                   10220: 
                   10221: =item *
                   10222: 
                   10223: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10224: 
                   10225: =item *
                   10226: 
                   10227: reply() : uses subreply to send a message to remote machine, logs all failures
                   10228: 
                   10229: =item *
                   10230: 
                   10231: critical() : passes a critical message to another server; if cannot
                   10232: get through then place message in connection buffer directory and
                   10233: returns con_delayed, if incapable of saving message, returns
                   10234: con_failed
                   10235: 
                   10236: =item *
                   10237: 
                   10238: reconlonc() : tries to reconnect lonc client processes.
                   10239: 
                   10240: =back
                   10241: 
                   10242: =head2 Resource Access Logging
                   10243: 
                   10244: =over 4
                   10245: 
                   10246: =item *
                   10247: 
                   10248: flushcourselogs() : flush (save) buffer logs and access logs
                   10249: 
                   10250: =item *
                   10251: 
                   10252: courselog($what) : save message for course in hash
                   10253: 
                   10254: =item *
                   10255: 
                   10256: courseacclog($what) : save message for course using &courselog().  Perform
                   10257: special processing for specific resource types (problems, exams, quizzes, etc).
                   10258: 
1.191     harris41 10259: =item *
                   10260: 
                   10261: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10262: as a PerlChildExitHandler
1.243     albertel 10263: 
                   10264: =back
                   10265: 
                   10266: =head2 Other
                   10267: 
                   10268: =over 4
                   10269: 
                   10270: =item *
                   10271: 
                   10272: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10273: 
                   10274: =back
                   10275: 
                   10276: =cut
1.877     foxr     10277: 

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