File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1232: download - view: text, annotated - select for diffs
Wed Jul 31 17:37:18 2013 UTC (10 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- In &EXT(), check $qualifier is null, when retrieving: &EXT("resource.$space")
  $space = title, map or filename,  in case this is a multi-part problem
  with a part ID matching $space.
- Add two additional &EXT() items -- resource.maptitle, resource.visibleparts
  (a) return title (in Course) and (b) comma-separated list of parts available to
  current user, respectively.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1232 2013/07/31 17:37:18 raeburn Exp $
    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: #
   28: ###
   29: 
   30: =pod
   31: 
   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: 
   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: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     if (($r->user() eq '') && ($apache >= 2.4)) {
  638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  639:             $r->user($disk_env{'user.name'});
  640:         } else {
  641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  642:         }
  643:     }
  644:     return $handle;
  645: }
  646: 
  647: sub timed_flock {
  648:     my ($file,$lock_type) = @_;
  649:     my $failed=0;
  650:     eval {
  651: 	local $SIG{__DIE__}='DEFAULT';
  652: 	local $SIG{ALRM}=sub {
  653: 	    $failed=1;
  654: 	    die("failed lock");
  655: 	};
  656: 	alarm(13);
  657: 	flock($file,$lock_type);
  658: 	alarm(0);
  659:     };
  660:     if ($failed) {
  661: 	return undef;
  662:     } else {
  663: 	return 1;
  664:     }
  665: }
  666: 
  667: # ---------------------------------------------------------- Append Environment
  668: 
  669: sub appenv {
  670:     my ($newenv,$roles) = @_;
  671:     if (ref($newenv) eq 'HASH') {
  672:         foreach my $key (keys(%{$newenv})) {
  673:             my $refused = 0;
  674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  675:                 $refused = 1;
  676:                 if (ref($roles) eq 'ARRAY') {
  677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  679:                         $refused = 0;
  680:                     }
  681:                 }
  682:             }
  683:             if ($refused) {
  684:                 &logthis("<font color=\"blue\">WARNING: ".
  685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  686:                          .'</font>');
  687: 	        delete($newenv->{$key});
  688:             } else {
  689:                 $env{$key}=$newenv->{$key};
  690:             }
  691:         }
  692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  693:         if ($opened
  694: 	    && &timed_flock($env_file,LOCK_EX)
  695: 	    &&
  696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  698: 	    while (my ($key,$value) = each(%{$newenv})) {
  699: 	        $disk_env{$key} = $value;
  700: 	    }
  701: 	    untie(%disk_env);
  702:         }
  703:     }
  704:     return 'ok';
  705: }
  706: # ----------------------------------------------------- Delete from Environment
  707: 
  708: sub delenv {
  709:     my ($delthis,$regexp,$roles) = @_;
  710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  711:         my $refused = 1;
  712:         if (ref($roles) eq 'ARRAY') {
  713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  714:             if (grep(/^\Q$role\E$/,@{$roles})) {
  715:                 $refused = 0;
  716:             }
  717:         }
  718:         if ($refused) {
  719:             &logthis("<font color=\"blue\">WARNING: ".
  720:                      "Attempt to delete from environment ".$delthis);
  721:             return 'error';
  722:         }
  723:     }
  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  725:     if ($opened
  726: 	&& &timed_flock($env_file,LOCK_EX)
  727: 	&&
  728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  730: 	foreach my $key (keys(%disk_env)) {
  731: 	    if ($regexp) {
  732:                 if ($key=~/^$delthis/) {
  733:                     delete($env{$key});
  734:                     delete($disk_env{$key});
  735:                 } 
  736:             } else {
  737:                 if ($key=~/^\Q$delthis\E/) {
  738: 		    delete($env{$key});
  739: 		    delete($disk_env{$key});
  740: 	        }
  741:             }
  742: 	}
  743: 	untie(%disk_env);
  744:     }
  745:     return 'ok';
  746: }
  747: 
  748: sub get_env_multiple {
  749:     my ($name) = @_;
  750:     my @values;
  751:     if (defined($env{$name})) {
  752:         # exists is it an array
  753:         if (ref($env{$name})) {
  754:             @values=@{ $env{$name} };
  755:         } else {
  756:             $values[0]=$env{$name};
  757:         }
  758:     }
  759:     return(@values);
  760: }
  761: 
  762: # ------------------------------------------------------------------- Locking
  763: 
  764: sub set_lock {
  765:     my ($text)=@_;
  766:     $locknum++;
  767:     my $id=$$.'-'.$locknum;
  768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  769:              'session.lock.'.$id => $text});
  770:     return $id;
  771: }
  772: 
  773: sub get_locks {
  774:     my $num=0;
  775:     my %texts=();
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           $num++;
  779:           $texts{$lock}=$env{'session.lock.'.$lock};
  780:        }
  781:    }
  782:    return ($num,%texts);
  783: }
  784: 
  785: sub remove_lock {
  786:     my ($id)=@_;
  787:     my $newlocks='';
  788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  789:        if (($lock=~/\w/) && ($lock ne $id)) {
  790:           $newlocks.=','.$lock;
  791:        }
  792:     }
  793:     &appenv({'session.locks' => $newlocks});
  794:     &delenv('session.lock.'.$id);
  795: }
  796: 
  797: sub remove_all_locks {
  798:     my $activelocks=$env{'session.locks'};
  799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  800:        if ($lock=~/\w/) {
  801:           &remove_lock($lock);
  802:        }
  803:     }
  804: }
  805: 
  806: 
  807: # ------------------------------------------ Find out current server userload
  808: sub userload {
  809:     my $numusers=0;
  810:     {
  811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  812: 	my $filename;
  813: 	my $curtime=time;
  814: 	while ($filename=readdir(LONIDS)) {
  815: 	    next if ($filename eq '.' || $filename eq '..');
  816: 	    next if ($filename =~ /publicuser_\d+\.id/);
  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  819: 	}
  820: 	closedir(LONIDS);
  821:     }
  822:     my $userloadpercent=0;
  823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  824:     if ($maxuserload) {
  825: 	$userloadpercent=100*$numusers/$maxuserload;
  826:     }
  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  828:     return $userloadpercent;
  829: }
  830: 
  831: # ------------------------------ Find server with least workload from spare.tab
  832: 
  833: sub spareserver {
  834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  835:     my $spare_server;
  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  838:                                                      :  $userloadpercent;
  839:     my ($uint_dom,$remotesessions);
  840:     if (($udom ne '') && (&domain($udom) ne '')) {
  841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  844:         $remotesessions = $udomdefaults{'remotesessions'};
  845:     }
  846:     my $spareshash = &this_host_spares($udom);
  847:     if (ref($spareshash) eq 'HASH') {
  848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  850:                 if ($uint_dom) {
  851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  852:                                                  $try_server));
  853:                 }
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     if ($uint_dom) {
  865:                         next unless (&spare_can_host($udom,$uint_dom,
  866:                                                      $remotesessions,$try_server));
  867:                     }
  868: 	            ($spare_server, $lowest_load) =
  869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  870:                 }
  871: 	    }
  872:         }
  873:     }
  874: 
  875:     if (!$want_server_name) {
  876:         my $protocol = 'http';
  877:         if ($protocol{$spare_server} eq 'https') {
  878:             $protocol = $protocol{$spare_server};
  879:         }
  880:         if (defined($spare_server)) {
  881:             my $hostname = &hostname($spare_server);
  882:             if (defined($hostname)) {
  883: 	        $spare_server = $protocol.'://'.$hostname;
  884:             }
  885:         }
  886:     }
  887:     return $spare_server;
  888: }
  889: 
  890: sub compare_server_load {
  891:     my ($try_server, $spare_server, $lowest_load) = @_;
  892: 
  893:     my $loadans     = &reply('load',    $try_server);
  894:     my $userloadans = &reply('userload',$try_server);
  895: 
  896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  898:     }
  899: 
  900:     my $load;
  901:     if ($loadans =~ /\d/) {
  902: 	if ($userloadans =~ /\d/) {
  903: 	    #both are numbers, pick the bigger one
  904: 	    $load = ($loadans > $userloadans) ? $loadans 
  905: 		                              : $userloadans;
  906: 	} else {
  907: 	    $load = $loadans;
  908: 	}
  909:     } else {
  910: 	$load = $userloadans;
  911:     }
  912: 
  913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  914: 	$spare_server = $try_server;
  915: 	$lowest_load  = $load;
  916:     }
  917:     return ($spare_server,$lowest_load);
  918: }
  919: 
  920: # --------------------------- ask offload servers if user already has a session
  921: sub find_existing_session {
  922:     my ($udom,$uname) = @_;
  923:     my $spareshash = &this_host_spares($udom);
  924:     if (ref($spareshash) eq 'HASH') {
  925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  928:             }
  929:         }
  930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  933:             }
  934:         }
  935:     }
  936:     return;
  937: }
  938: 
  939: # -------------------------------- ask if server already has a session for user
  940: sub has_user_session {
  941:     my ($lonid,$udom,$uname) = @_;
  942:     my $result = &reply(join(':','userhassession',
  943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  944:     return 1 if ($result eq 'ok');
  945: 
  946:     return 0;
  947: }
  948: 
  949: # --------- determine least loaded server in a user's domain which allows login
  950: 
  951: sub choose_server {
  952:     my ($udom,$checkloginvia) = @_;
  953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  954:     my %servers = &get_servers($udom);
  955:     my $lowest_load = 30000;
  956:     my ($login_host,$hostname,$portal_path,$isredirect);
  957:     foreach my $lonhost (keys(%servers)) {
  958:         my $loginvia;
  959:         if ($checkloginvia) {
  960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  961:             if ($loginvia) {
  962:                 my ($server,$path) = split(/:/,$loginvia);
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($server, $login_host, $lowest_load);
  965:                 if ($login_host eq $server) {
  966:                     $portal_path = $path;
  967:                     $isredirect = 1;
  968:                 }
  969:             } else {
  970:                 ($login_host, $lowest_load) =
  971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  972:                 if ($login_host eq $lonhost) {
  973:                     $portal_path = '';
  974:                     $isredirect = ''; 
  975:                 }
  976:             }
  977:         } else {
  978:             ($login_host, $lowest_load) =
  979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  980:         }
  981:     }
  982:     if ($login_host ne '') {
  983:         $hostname = &hostname($login_host);
  984:     }
  985:     return ($login_host,$hostname,$portal_path,$isredirect);
  986: }
  987: 
  988: # --------------------------------------------- Try to change a user's password
  989: 
  990: sub changepass {
  991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  992:     $currentpass = &escape($currentpass);
  993:     $newpass     = &escape($newpass);
  994:     my $lonhost = $perlvar{'lonHostID'};
  995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  996: 		       $server);
  997:     if (! $answer) {
  998: 	&logthis("No reply on password change request to $server ".
  999: 		 "by $uname in domain $udom.");
 1000:     } elsif ($answer =~ "^ok") {
 1001:         &logthis("$uname in $udom successfully changed their password ".
 1002: 		 "on $server.");
 1003:     } elsif ($answer =~ "^pwchange_failure") {
 1004: 	&logthis("$uname in $udom was unable to change their password ".
 1005: 		 "on $server.  The action was blocked by either lcpasswd ".
 1006: 		 "or pwchange");
 1007:     } elsif ($answer =~ "^non_authorized") {
 1008:         &logthis("$uname in $udom did not get their password correct when ".
 1009: 		 "attempting to change it on $server.");
 1010:     } elsif ($answer =~ "^auth_mode_error") {
 1011:         &logthis("$uname in $udom attempted to change their password despite ".
 1012: 		 "not being locally or internally authenticated on $server.");
 1013:     } elsif ($answer =~ "^unknown_user") {
 1014:         &logthis("$uname in $udom attempted to change their password ".
 1015: 		 "on $server but were unable to because $server is not ".
 1016: 		 "their home server.");
 1017:     } elsif ($answer =~ "^refused") {
 1018: 	&logthis("$server refused to change $uname in $udom password because ".
 1019: 		 "it was sent an unencrypted request to change the password.");
 1020:     } elsif ($answer =~ "invalid_client") {
 1021:         &logthis("$server refused to change $uname in $udom password because ".
 1022:                  "it was a reset by e-mail originating from an invalid server.");
 1023:     }
 1024:     return $answer;
 1025: }
 1026: 
 1027: # ----------------------- Try to determine user's current authentication scheme
 1028: 
 1029: sub queryauthenticate {
 1030:     my ($uname,$udom)=@_;
 1031:     my $uhome=&homeserver($uname,$udom);
 1032:     if (!$uhome) {
 1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1034: 	return 'no_host';
 1035:     }
 1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1039:     }
 1040:     return $answer;
 1041: }
 1042: 
 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
 1044: 
 1045: sub authenticate {
 1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1047:     $upass=&escape($upass);
 1048:     $uname= &LONCAPA::clean_username($uname);
 1049:     my $uhome=&homeserver($uname,$udom,1);
 1050:     my $newhome;
 1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: # Maybe the machine was offline and only re-appeared again recently?
 1053:         &reconlonc();
 1054: # One more
 1055: 	$uhome=&homeserver($uname,$udom,1);
 1056:         if (($uhome eq 'no_host') && $checkdefauth) {
 1057:             if (defined(&domain($udom,'primary'))) {
 1058:                 $newhome=&domain($udom,'primary');
 1059:             }
 1060:             if ($newhome ne '') {
 1061:                 $uhome = $newhome;
 1062:             }
 1063:         }
 1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1066: 	    return 'no_host';
 1067:         }
 1068:     }
 1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1070:     if ($answer eq 'authorized') {
 1071:         if ($newhome) {
 1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1073:             return 'no_account_on_host'; 
 1074:         } else {
 1075:             &logthis("User $uname at $udom authorized by $uhome");
 1076:             return $uhome;
 1077:         }
 1078:     }
 1079:     if ($answer eq 'non_authorized') {
 1080: 	&logthis("User $uname at $udom rejected by $uhome");
 1081: 	return 'no_host'; 
 1082:     }
 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1084:     return 'no_host';
 1085: }
 1086: 
 1087: sub can_host_session {
 1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1089:     my $canhost = 1;
 1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1091:     if (ref($remotesessions) eq 'HASH') {
 1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1094:                 $canhost = 0;
 1095:             } else {
 1096:                 $canhost = 1;
 1097:             }
 1098:         }
 1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1101:                 $canhost = 1;
 1102:             } else {
 1103:                 $canhost = 0;
 1104:             }
 1105:         }
 1106:         if ($canhost) {
 1107:             if ($remotesessions->{'version'} ne '') {
 1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1109:                 if ($reqmajor ne '' && $reqminor ne '') {
 1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1111:                         my $major = $1;
 1112:                         my $minor = $2;
 1113:                         if (($major < $reqmajor ) ||
 1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1115:                             $canhost = 0;
 1116:                         }
 1117:                     } else {
 1118:                         $canhost = 0;
 1119:                     }
 1120:                 }
 1121:             }
 1122:         }
 1123:     }
 1124:     if ($canhost) {
 1125:         if (ref($hostedsessions) eq 'HASH') {
 1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1129:                 if (($uint_dom ne '') && 
 1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1131:                     $canhost = 0;
 1132:                 } else {
 1133:                     $canhost = 1;
 1134:                 }
 1135:             }
 1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1137:                 if (($uint_dom ne '') && 
 1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1139:                     $canhost = 1;
 1140:                 } else {
 1141:                     $canhost = 0;
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     return $canhost;
 1147: }
 1148: 
 1149: sub spare_can_host {
 1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1151:     my $canhost=1;
 1152:     my @intdoms;
 1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1154:     if (ref($internet_names) eq 'ARRAY') {
 1155:         @intdoms = @{$internet_names};
 1156:     }
 1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1163:                                      $remotesessions,
 1164:                                      $defdomdefaults{'hostedsessions'});
 1165:     }
 1166:     return $canhost;
 1167: }
 1168: 
 1169: sub this_host_spares {
 1170:     my ($dom) = @_;
 1171:     my ($dom_in_use,$lonhost_in_use,$result);
 1172:     my @hosts = &current_machine_ids();
 1173:     foreach my $lonhost (@hosts) {
 1174:         if (&host_domain($lonhost) eq $dom) {
 1175:             $dom_in_use = $dom;
 1176:             $lonhost_in_use = $lonhost;
 1177:             last;
 1178:         }
 1179:     }
 1180:     if ($dom_in_use ne '') {
 1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1182:     }
 1183:     if (ref($result) ne 'HASH') {
 1184:         $lonhost_in_use = $perlvar{'lonHostID'};
 1185:         $dom_in_use = &host_domain($lonhost_in_use);
 1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1187:         if (ref($result) ne 'HASH') {
 1188:             $result = \%spareid;
 1189:         }
 1190:     }
 1191:     return $result;
 1192: }
 1193: 
 1194: sub spares_for_offload  {
 1195:     my ($dom_in_use,$lonhost_in_use) = @_;
 1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1197:     if (defined($cached)) {
 1198:         return $result;
 1199:     } else {
 1200:         my $cachetime = 60*60*24;
 1201:         my %domconfig =
 1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return;
 1212: }
 1213: 
 1214: sub get_lonbalancer_config {
 1215:     my ($servers) = @_;
 1216:     my ($currbalancer,$currtargets);
 1217:     if (ref($servers) eq 'HASH') {
 1218:         foreach my $server (keys(%{$servers})) {
 1219:             my %what = (
 1220:                          spareid => 1,
 1221:                          perlvar => 1,
 1222:                        );
 1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1224:             if ($result eq 'ok') {
 1225:                 if (ref($returnhash) eq 'HASH') {
 1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1228:                             $currbalancer = $server;
 1229:                             $currtargets = {};
 1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1233:                                 }
 1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1236:                                 }
 1237:                             }
 1238:                             last;
 1239:                         }
 1240:                     }
 1241:                 }
 1242:             }
 1243:         }
 1244:     }
 1245:     return ($currbalancer,$currtargets);
 1246: }
 1247: 
 1248: sub check_loadbalancing {
 1249:     my ($uname,$udom) = @_;
 1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1251:         $rule_in_effect,$offloadto,$otherserver);
 1252:     my $lonhost = $perlvar{'lonHostID'};
 1253:     my @hosts = &current_machine_ids();
 1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1257:     my $serverhomedom = &host_domain($lonhost);
 1258: 
 1259:     my $cachetime = 60*60*24;
 1260: 
 1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1262:         $dom_in_use = $udom;
 1263:         $homeintdom = 1;
 1264:     } else {
 1265:         $dom_in_use = $serverhomedom;
 1266:     }
 1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1268:     unless (defined($cached)) {
 1269:         my %domconfig =
 1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1273:         }
 1274:     }
 1275:     if (ref($result) eq 'HASH') {
 1276:         ($is_balancer,$currtargets,$currrules) = 
 1277:             &check_balancer_result($result,@hosts);
 1278:         if ($is_balancer) {
 1279:             if (ref($currrules) eq 'HASH') {
 1280:                 if ($homeintdom) {
 1281:                     if ($uname ne '') {
 1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1288:                             }
 1289:                         }
 1290:                         if ($rule_in_effect eq '') {
 1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1292:                             if ($userenv{'inststatus'} ne '') {
 1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1294:                                 my ($othertitle,$usertypes,$types) =
 1295:                                     &Apache::loncommon::sorted_inst_types($udom);
 1296:                                 if (ref($types) eq 'ARRAY') {
 1297:                                     foreach my $type (@{$types}) {
 1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1299:                                             if (exists($currrules->{$type})) {
 1300:                                                 $rule_in_effect = $currrules->{$type};
 1301:                                             }
 1302:                                         }
 1303:                                     }
 1304:                                 }
 1305:                             } else {
 1306:                                 if (exists($currrules->{'default'})) {
 1307:                                     $rule_in_effect = $currrules->{'default'};
 1308:                                 }
 1309:                             }
 1310:                         }
 1311:                     } else {
 1312:                         if (exists($currrules->{'default'})) {
 1313:                             $rule_in_effect = $currrules->{'default'};
 1314:                         }
 1315:                     }
 1316:                 } else {
 1317:                     if ($currrules->{'_LC_external'} ne '') {
 1318:                         $rule_in_effect = $currrules->{'_LC_external'};
 1319:                     }
 1320:                 }
 1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1322:                                                        $uname,$udom);
 1323:             }
 1324:         }
 1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1326:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1327:         unless (defined($cached)) {
 1328:             my %domconfig =
 1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1332:             }
 1333:         }
 1334:         if (ref($result) eq 'HASH') {
 1335:             ($is_balancer,$currtargets,$currrules) = 
 1336:                 &check_balancer_result($result,@hosts);
 1337:             if ($is_balancer) {
 1338:                 if (ref($currrules) eq 'HASH') {
 1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1341:                     }
 1342:                 }
 1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1344:                                                        $uname,$udom);
 1345:             }
 1346:         } else {
 1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1348:                 $is_balancer = 1;
 1349:                 $offloadto = &this_host_spares($dom_in_use);
 1350:             }
 1351:         }
 1352:     } else {
 1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1354:             $is_balancer = 1;
 1355:             $offloadto = &this_host_spares($dom_in_use);
 1356:         }
 1357:     }
 1358:     if ($is_balancer) {
 1359:         my $lowest_load = 30000;
 1360:         if (ref($offloadto) eq 'HASH') {
 1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1363:                     ($otherserver,$lowest_load) =
 1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1365:                 }
 1366:             }
 1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1368: 
 1369:             if (!$found_server) {
 1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1372:                         ($otherserver,$lowest_load) =
 1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1374:                     }
 1375:                 }
 1376:             }
 1377:         } elsif (ref($offloadto) eq 'ARRAY') {
 1378:             if (@{$offloadto} == 1) {
 1379:                 $otherserver = $offloadto->[0];
 1380:             } elsif (@{$offloadto} > 1) {
 1381:                 foreach my $try_server (@{$offloadto}) {
 1382:                     ($otherserver,$lowest_load) =
 1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1384:                 }
 1385:             }
 1386:         }
 1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1388:             $is_balancer = 0;
 1389:             if ($uname ne '' && $udom ne '') {
 1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1391:                     
 1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1393:                              'user.loadbalcheck.time' => time});
 1394:                 }
 1395:             }
 1396:         }
 1397:     }
 1398:     return ($is_balancer,$otherserver);
 1399: }
 1400: 
 1401: sub check_balancer_result {
 1402:     my ($result,@hosts) = @_;
 1403:     my ($is_balancer,$currtargets,$currrules);
 1404:     if (ref($result) eq 'HASH') {
 1405:         if ($result->{'lonhost'} ne '') {
 1406:             my $currbalancer = $result->{'lonhost'};
 1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1408:                 $is_balancer = 1;
 1409:                 $currtargets = $result->{'targets'};
 1410:                 $currrules = $result->{'rules'};
 1411:             }
 1412:         } else {
 1413:             foreach my $key (keys(%{$result})) {
 1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1415:                     (ref($result->{$key}) eq 'HASH')) {
 1416:                     $is_balancer = 1;
 1417:                     $currrules = $result->{$key}{'rules'};
 1418:                     $currtargets = $result->{$key}{'targets'};
 1419:                     last;
 1420:                 }
 1421:             }
 1422:         }
 1423:     }
 1424:     return ($is_balancer,$currtargets,$currrules);
 1425: }
 1426: 
 1427: sub get_loadbalancer_targets {
 1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1429:     my $offloadto;
 1430:     if ($rule_in_effect eq 'none') {
 1431:         return [$perlvar{'lonHostID'}];
 1432:     } elsif ($rule_in_effect eq '') {
 1433:         $offloadto = $currtargets;
 1434:     } else {
 1435:         if ($rule_in_effect eq 'homeserver') {
 1436:             my $homeserver = &homeserver($uname,$udom);
 1437:             if ($homeserver ne 'no_host') {
 1438:                 $offloadto = [$homeserver];
 1439:             }
 1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1441:             my %domconfig =
 1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1447:                     }
 1448:                 }
 1449:             } else {
 1450:                 my %servers = &internet_dom_servers($udom);
 1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1452:                 if (&hostname($remotebalancer) ne '') {
 1453:                     $offloadto = [$remotebalancer];
 1454:                 }
 1455:             }
 1456:         } elsif (&hostname($rule_in_effect) ne '') {
 1457:             $offloadto = [$rule_in_effect];
 1458:         }
 1459:     }
 1460:     return $offloadto;
 1461: }
 1462: 
 1463: sub internet_dom_servers {
 1464:     my ($dom) = @_;
 1465:     my (%uniqservers,%servers);
 1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1467:     my @machinedoms = &machine_domains($primaryserver);
 1468:     foreach my $mdom (@machinedoms) {
 1469:         my %currservers = %servers;
 1470:         my %server = &get_servers($mdom);
 1471:         %servers = (%currservers,%server);
 1472:     }
 1473:     my %by_hostname;
 1474:     foreach my $id (keys(%servers)) {
 1475:         push(@{$by_hostname{$servers{$id}}},$id);
 1476:     }
 1477:     foreach my $hostname (sort(keys(%by_hostname))) {
 1478:         if (@{$by_hostname{$hostname}} > 1) {
 1479:             my $match = 0;
 1480:             foreach my $id (@{$by_hostname{$hostname}}) {
 1481:                 if (&host_domain($id) eq $dom) {
 1482:                     $uniqservers{$id} = $hostname;
 1483:                     $match = 1;
 1484:                 }
 1485:             }
 1486:             unless ($match) {
 1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1488:             }
 1489:         } else {
 1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:         }
 1492:     }
 1493:     return %uniqservers;
 1494: }
 1495: 
 1496: # ---------------------- Find the homebase for a user from domain's lib servers
 1497: 
 1498: my %homecache;
 1499: sub homeserver {
 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
 1501:     my $index="$uname:$udom";
 1502: 
 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1504: 
 1505:     my %servers = &get_servers($udom,'library');
 1506:     foreach my $tryserver (keys(%servers)) {
 1507:         next if ($ignoreBadCache ne 'true' && 
 1508: 		 exists($badServerCache{$tryserver}));
 1509: 
 1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1511: 	if ($answer eq 'found') {
 1512: 	    delete($badServerCache{$tryserver}); 
 1513: 	    return $homecache{$index}=$tryserver;
 1514: 	} elsif ($answer eq 'no_host') {
 1515: 	    $badServerCache{$tryserver}=1;
 1516: 	}
 1517:     }    
 1518:     return 'no_host';
 1519: }
 1520: 
 1521: # ------------------------------------- Find the usernames behind a list of IDs
 1522: 
 1523: sub idget {
 1524:     my ($udom,@ids)=@_;
 1525:     my %returnhash=();
 1526:     
 1527:     my %servers = &get_servers($udom,'library');
 1528:     foreach my $tryserver (keys(%servers)) {
 1529: 	my $idlist=join('&',@ids);
 1530: 	$idlist=~tr/A-Z/a-z/; 
 1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1532: 	my @answer=();
 1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1534: 	    @answer=split(/\&/,$reply);
 1535: 	}                    ;
 1536: 	my $i;
 1537: 	for ($i=0;$i<=$#ids;$i++) {
 1538: 	    if ($answer[$i]) {
 1539: 		$returnhash{$ids[$i]}=$answer[$i];
 1540: 	    } 
 1541: 	}
 1542:     } 
 1543:     return %returnhash;
 1544: }
 1545: 
 1546: # ------------------------------------- Find the IDs behind a list of usernames
 1547: 
 1548: sub idrget {
 1549:     my ($udom,@unames)=@_;
 1550:     my %returnhash=();
 1551:     foreach my $uname (@unames) {
 1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1553:     }
 1554:     return %returnhash;
 1555: }
 1556: 
 1557: # ------------------------------- Store away a list of names and associated IDs
 1558: 
 1559: sub idput {
 1560:     my ($udom,%ids)=@_;
 1561:     my %servers=();
 1562:     foreach my $uname (keys(%ids)) {
 1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1564:         my $uhom=&homeserver($uname,$udom);
 1565:         if ($uhom ne 'no_host') {
 1566:             my $id=&escape($ids{$uname});
 1567:             $id=~tr/A-Z/a-z/;
 1568:             my $esc_unam=&escape($uname);
 1569: 	    if ($servers{$uhom}) {
 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1571:             } else {
 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
 1573:             }
 1574:         }
 1575:     }
 1576:     foreach my $server (keys(%servers)) {
 1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1578:     }
 1579: }
 1580: 
 1581: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1582: 
 1583: sub iddel {
 1584:     my ($udom,$idshashref,$uhome)=@_;
 1585:     my %result=();
 1586:     unless (ref($idshashref) eq 'HASH') {
 1587:         return %result;
 1588:     }
 1589:     my %servers=();
 1590:     while (my ($id,$uname) = each(%{$idshashref})) {
 1591:         my $uhom;
 1592:         if ($uhome) {
 1593:             $uhom = $uhome;
 1594:         } else {
 1595:             $uhom=&homeserver($uname,$udom);
 1596:         }
 1597:         if ($uhom ne 'no_host') {
 1598:             if ($servers{$uhom}) {
 1599:                 $servers{$uhom}.='&'.&escape($id);
 1600:             } else {
 1601:                 $servers{$uhom}=&escape($id);
 1602:             }
 1603:         }
 1604:     }
 1605:     foreach my $server (keys(%servers)) {
 1606:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1607:     }
 1608:     return %result;
 1609: }
 1610: 
 1611: # ------------------------------dump from db file owned by domainconfig user
 1612: sub dump_dom {
 1613:     my ($namespace, $udom, $regexp) = @_;
 1614: 
 1615:     $udom ||= $env{'user.domain'};
 1616: 
 1617:     return () unless $udom;
 1618: 
 1619:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1620: }
 1621: 
 1622: # ------------------------------------------ get items from domain db files   
 1623: 
 1624: sub get_dom {
 1625:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1626:     my $items='';
 1627:     foreach my $item (@$storearr) {
 1628:         $items.=&escape($item).'&';
 1629:     }
 1630:     $items=~s/\&$//;
 1631:     if (!$udom) {
 1632:         $udom=$env{'user.domain'};
 1633:         if (defined(&domain($udom,'primary'))) {
 1634:             $uhome=&domain($udom,'primary');
 1635:         } else {
 1636:             undef($uhome);
 1637:         }
 1638:     } else {
 1639:         if (!$uhome) {
 1640:             if (defined(&domain($udom,'primary'))) {
 1641:                 $uhome=&domain($udom,'primary');
 1642:             }
 1643:         }
 1644:     }
 1645:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1646:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1647:         my %returnhash;
 1648:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1649:             return %returnhash;
 1650:         }
 1651:         my @pairs=split(/\&/,$rep);
 1652:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1653:             return @pairs;
 1654:         }
 1655:         my $i=0;
 1656:         foreach my $item (@$storearr) {
 1657:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1658:             $i++;
 1659:         }
 1660:         return %returnhash;
 1661:     } else {
 1662:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1663:     }
 1664: }
 1665: 
 1666: # -------------------------------------------- put items in domain db files 
 1667: 
 1668: sub put_dom {
 1669:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:         if (defined(&domain($udom,'primary'))) {
 1673:             $uhome=&domain($udom,'primary');
 1674:         } else {
 1675:             undef($uhome);
 1676:         }
 1677:     } else {
 1678:         if (!$uhome) {
 1679:             if (defined(&domain($udom,'primary'))) {
 1680:                 $uhome=&domain($udom,'primary');
 1681:             }
 1682:         }
 1683:     } 
 1684:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1685:         my $items='';
 1686:         foreach my $item (keys(%$storehash)) {
 1687:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1688:         }
 1689:         $items=~s/\&$//;
 1690:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1691:     } else {
 1692:         &logthis("put_dom failed - no homeserver and/or domain");
 1693:     }
 1694: }
 1695: 
 1696: # --------------------- newput for items in db file owned by domainconfig user
 1697: sub newput_dom {
 1698:     my ($namespace,$storehash,$udom) = @_;
 1699:     my $result;
 1700:     if (!$udom) {
 1701:         $udom=$env{'user.domain'};
 1702:     }
 1703:     if ($udom) {
 1704:         my $uname = &get_domainconfiguser($udom);
 1705:         $result = &newput($namespace,$storehash,$udom,$uname);
 1706:     }
 1707:     return $result;
 1708: }
 1709: 
 1710: # --------------------- delete for items in db file owned by domainconfig user
 1711: sub del_dom {
 1712:     my ($namespace,$storearr,$udom)=@_;
 1713:     if (ref($storearr) eq 'ARRAY') {
 1714:         if (!$udom) {
 1715:             $udom=$env{'user.domain'};
 1716:         }
 1717:         if ($udom) {
 1718:             my $uname = &get_domainconfiguser($udom); 
 1719:             return &del($namespace,$storearr,$udom,$uname);
 1720:         }
 1721:     }
 1722: }
 1723: 
 1724: # ----------------------------------construct domainconfig user for a domain 
 1725: sub get_domainconfiguser {
 1726:     my ($udom) = @_;
 1727:     return $udom.'-domainconfig';
 1728: }
 1729: 
 1730: sub retrieve_inst_usertypes {
 1731:     my ($udom) = @_;
 1732:     my (%returnhash,@order);
 1733:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1734:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1735:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1736:         %returnhash = %{$domdefs{'inststatustypes'}};
 1737:         @order = @{$domdefs{'inststatusorder'}};
 1738:     } else {
 1739:         if (defined(&domain($udom,'primary'))) {
 1740:             my $uhome=&domain($udom,'primary');
 1741:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1742:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1743:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1744:                 return (\%returnhash,\@order);
 1745:             }
 1746:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1747:             my @pairs=split(/\&/,$hashitems);
 1748:             foreach my $item (@pairs) {
 1749:                 my ($key,$value)=split(/=/,$item,2);
 1750:                 $key = &unescape($key);
 1751:                 next if ($key =~ /^error: 2 /);
 1752:                 $returnhash{$key}=&thaw_unescape($value);
 1753:             }
 1754:             my @esc_order = split(/\&/,$orderitems);
 1755:             foreach my $item (@esc_order) {
 1756:                 push(@order,&unescape($item));
 1757:             }
 1758:         } else {
 1759:             &logthis("get_dom failed - no primary domain server for $udom");
 1760:         }
 1761:     }
 1762:     return (\%returnhash,\@order);
 1763: }
 1764: 
 1765: sub is_domainimage {
 1766:     my ($url) = @_;
 1767:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1768:         if (&domain($1) ne '') {
 1769:             return '1';
 1770:         }
 1771:     }
 1772:     return;
 1773: }
 1774: 
 1775: sub inst_directory_query {
 1776:     my ($srch) = @_;
 1777:     my $udom = $srch->{'srchdomain'};
 1778:     my %results;
 1779:     my $homeserver = &domain($udom,'primary');
 1780:     my $outcome;
 1781:     if ($homeserver ne '') {
 1782: 	my $queryid=&reply("querysend:instdirsearch:".
 1783: 			   &escape($srch->{'srchby'}).':'.
 1784: 			   &escape($srch->{'srchterm'}).':'.
 1785: 			   &escape($srch->{'srchtype'}),$homeserver);
 1786: 	my $host=&hostname($homeserver);
 1787: 	if ($queryid !~/^\Q$host\E\_/) {
 1788: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1789: 	    return;
 1790: 	}
 1791: 	my $response = &get_query_reply($queryid);
 1792: 	my $maxtries = 5;
 1793: 	my $tries = 1;
 1794: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1795: 	    $response = &get_query_reply($queryid);
 1796: 	    $tries ++;
 1797: 	}
 1798: 
 1799:         if (!&error($response) && $response ne 'refused') {
 1800:             if ($response eq 'unavailable') {
 1801:                 $outcome = $response;
 1802:             } else {
 1803:                 $outcome = 'ok';
 1804:                 my @matches = split(/\n/,$response);
 1805:                 foreach my $match (@matches) {
 1806:                     my ($key,$value) = split(/=/,$match);
 1807:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1808:                 }
 1809:             }
 1810:         }
 1811:     }
 1812:     return ($outcome,%results);
 1813: }
 1814: 
 1815: sub usersearch {
 1816:     my ($srch) = @_;
 1817:     my $dom = $srch->{'srchdomain'};
 1818:     my %results;
 1819:     my %libserv = &all_library();
 1820:     my $query = 'usersearch';
 1821:     foreach my $tryserver (keys(%libserv)) {
 1822:         if (&host_domain($tryserver) eq $dom) {
 1823:             my $host=&hostname($tryserver);
 1824:             my $queryid=
 1825:                 &reply("querysend:".&escape($query).':'.
 1826:                        &escape($srch->{'srchby'}).':'.
 1827:                        &escape($srch->{'srchtype'}).':'.
 1828:                        &escape($srch->{'srchterm'}),$tryserver);
 1829:             if ($queryid !~/^\Q$host\E\_/) {
 1830:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1831:                 next;
 1832:             }
 1833:             my $reply = &get_query_reply($queryid);
 1834:             my $maxtries = 1;
 1835:             my $tries = 1;
 1836:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1837:                 $reply = &get_query_reply($queryid);
 1838:                 $tries ++;
 1839:             }
 1840:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1841:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1842:             } else {
 1843:                 my @matches;
 1844:                 if ($reply =~ /\n/) {
 1845:                     @matches = split(/\n/,$reply);
 1846:                 } else {
 1847:                     @matches = split(/\&/,$reply);
 1848:                 }
 1849:                 foreach my $match (@matches) {
 1850:                     my ($uname,$udom,%userhash);
 1851:                     foreach my $entry (split(/:/,$match)) {
 1852:                         my ($key,$value) =
 1853:                             map {&unescape($_);} split(/=/,$entry);
 1854:                         $userhash{$key} = $value;
 1855:                         if ($key eq 'username') {
 1856:                             $uname = $value;
 1857:                         } elsif ($key eq 'domain') {
 1858:                             $udom = $value;
 1859:                         }
 1860:                     }
 1861:                     $results{$uname.':'.$udom} = \%userhash;
 1862:                 }
 1863:             }
 1864:         }
 1865:     }
 1866:     return %results;
 1867: }
 1868: 
 1869: sub get_instuser {
 1870:     my ($udom,$uname,$id) = @_;
 1871:     my $homeserver = &domain($udom,'primary');
 1872:     my ($outcome,%results);
 1873:     if ($homeserver ne '') {
 1874:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1875:                            &escape($id).':'.&escape($udom),$homeserver);
 1876:         my $host=&hostname($homeserver);
 1877:         if ($queryid !~/^\Q$host\E\_/) {
 1878:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1879:             return;
 1880:         }
 1881:         my $response = &get_query_reply($queryid);
 1882:         my $maxtries = 5;
 1883:         my $tries = 1;
 1884:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1885:             $response = &get_query_reply($queryid);
 1886:             $tries ++;
 1887:         }
 1888:         if (!&error($response) && $response ne 'refused') {
 1889:             if ($response eq 'unavailable') {
 1890:                 $outcome = $response;
 1891:             } else {
 1892:                 $outcome = 'ok';
 1893:                 my @matches = split(/\n/,$response);
 1894:                 foreach my $match (@matches) {
 1895:                     my ($key,$value) = split(/=/,$match);
 1896:                     $results{&unescape($key)} = &thaw_unescape($value);
 1897:                 }
 1898:             }
 1899:         }
 1900:     }
 1901:     my %userinfo;
 1902:     if (ref($results{$uname}) eq 'HASH') {
 1903:         %userinfo = %{$results{$uname}};
 1904:     } 
 1905:     return ($outcome,%userinfo);
 1906: }
 1907: 
 1908: sub inst_rulecheck {
 1909:     my ($udom,$uname,$id,$item,$rules) = @_;
 1910:     my %returnhash;
 1911:     if ($udom ne '') {
 1912:         if (ref($rules) eq 'ARRAY') {
 1913:             @{$rules} = map {&escape($_);} (@{$rules});
 1914:             my $rulestr = join(':',@{$rules});
 1915:             my $homeserver=&domain($udom,'primary');
 1916:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1917:                 my $response;
 1918:                 if ($item eq 'username') {                
 1919:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1920:                                               ':'.&escape($uname).':'.$rulestr,
 1921:                                               $homeserver));
 1922:                 } elsif ($item eq 'id') {
 1923:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1924:                                               ':'.&escape($id).':'.$rulestr,
 1925:                                               $homeserver));
 1926:                 } elsif ($item eq 'selfcreate') {
 1927:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1928:                                                &escape($udom).':'.&escape($uname).
 1929:                                               ':'.$rulestr,$homeserver));
 1930:                 }
 1931:                 if ($response ne 'refused') {
 1932:                     my @pairs=split(/\&/,$response);
 1933:                     foreach my $item (@pairs) {
 1934:                         my ($key,$value)=split(/=/,$item,2);
 1935:                         $key = &unescape($key);
 1936:                         next if ($key =~ /^error: 2 /);
 1937:                         $returnhash{$key}=&thaw_unescape($value);
 1938:                     }
 1939:                 }
 1940:             }
 1941:         }
 1942:     }
 1943:     return %returnhash;
 1944: }
 1945: 
 1946: sub inst_userrules {
 1947:     my ($udom,$check) = @_;
 1948:     my (%ruleshash,@ruleorder);
 1949:     if ($udom ne '') {
 1950:         my $homeserver=&domain($udom,'primary');
 1951:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1952:             my $response;
 1953:             if ($check eq 'id') {
 1954:                 $response=&reply('instidrules:'.&escape($udom),
 1955:                                  $homeserver);
 1956:             } elsif ($check eq 'email') {
 1957:                 $response=&reply('instemailrules:'.&escape($udom),
 1958:                                  $homeserver);
 1959:             } else {
 1960:                 $response=&reply('instuserrules:'.&escape($udom),
 1961:                                  $homeserver);
 1962:             }
 1963:             if (($response ne 'refused') && ($response ne 'error') && 
 1964:                 ($response ne 'unknown_cmd') && 
 1965:                 ($response ne 'no_such_host')) {
 1966:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1967:                 my @pairs=split(/\&/,$hashitems);
 1968:                 foreach my $item (@pairs) {
 1969:                     my ($key,$value)=split(/=/,$item,2);
 1970:                     $key = &unescape($key);
 1971:                     next if ($key =~ /^error: 2 /);
 1972:                     $ruleshash{$key}=&thaw_unescape($value);
 1973:                 }
 1974:                 my @esc_order = split(/\&/,$orderitems);
 1975:                 foreach my $item (@esc_order) {
 1976:                     push(@ruleorder,&unescape($item));
 1977:                 }
 1978:             }
 1979:         }
 1980:     }
 1981:     return (\%ruleshash,\@ruleorder);
 1982: }
 1983: 
 1984: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1985: 
 1986: sub get_domain_defaults {
 1987:     my ($domain) = @_;
 1988:     my $cachetime = 60*60*24;
 1989:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1990:     if (defined($cached)) {
 1991:         if (ref($result) eq 'HASH') {
 1992:             return %{$result};
 1993:         }
 1994:     }
 1995:     my %domdefaults;
 1996:     my %domconfig =
 1997:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1998:                                   'requestcourses','inststatus',
 1999:                                   'coursedefaults','usersessions',
 2000:                                   'requestauthor'],$domain);
 2001:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2002:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2003:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2004:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2005:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2006:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2007:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2008:     } else {
 2009:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2010:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2011:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2012:     }
 2013:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2014:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2015:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2016:         } else {
 2017:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2018:         }
 2019:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2020:         foreach my $item (@usertools) {
 2021:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2022:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2023:             }
 2024:         }
 2025:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2026:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2027:         }
 2028:     }
 2029:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2030:         foreach my $item ('official','unofficial','community') {
 2031:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2032:         }
 2033:     }
 2034:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2035:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2036:     }
 2037:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2038:         foreach my $item ('inststatustypes','inststatusorder') {
 2039:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2040:         }
 2041:     }
 2042:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2043:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2044:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2045:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2046:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2047:         }
 2048:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2049:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2050:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2051:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2052:         }
 2053:     }
 2054:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2055:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2056:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2057:         }
 2058:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2059:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2060:         }
 2061:     }
 2062:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2063:     return %domdefaults;
 2064: }
 2065: 
 2066: # --------------------------------------------------- Assign a key to a student
 2067: 
 2068: sub assign_access_key {
 2069: #
 2070: # a valid key looks like uname:udom#comments
 2071: # comments are being appended
 2072: #
 2073:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2074:     $kdom=
 2075:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2076:     $knum=
 2077:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     $udom=$env{'user.name'} unless (defined($udom));
 2083:     $uname=$env{'user.domain'} unless (defined($uname));
 2084:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2085:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2086:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2087:                                                   # assigned to this person
 2088:                                                   # - this should not happen,
 2089:                                                   # unless something went wrong
 2090:                                                   # the first time around
 2091: # ready to assign
 2092:         $logentry=$1.'; '.$logentry;
 2093:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2094:                                                  $kdom,$knum) eq 'ok') {
 2095: # key now belongs to user
 2096: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2097:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2098:                 &appenv({'environment.'.$envkey => $ckey});
 2099:                 return 'ok';
 2100:             } else {
 2101:                 return 
 2102:   'error: Count not permanently assign key, will need to be re-entered later.';
 2103: 	    }
 2104:         } else {
 2105:             return 'error: Could not assign key, try again later.';
 2106:         }
 2107:     } elsif (!$existing{$ckey}) {
 2108: # the key does not exist
 2109: 	return 'error: The key does not exist';
 2110:     } else {
 2111: # the key is somebody else's
 2112: 	return 'error: The key is already in use';
 2113:     }
 2114: }
 2115: 
 2116: # ------------------------------------------ put an additional comment on a key
 2117: 
 2118: sub comment_access_key {
 2119: #
 2120: # a valid key looks like uname:udom#comments
 2121: # comments are being appended
 2122: #
 2123:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2124:     $cdom=
 2125:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2126:     $cnum=
 2127:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2128:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2129:     if ($existing{$ckey}) {
 2130:         $existing{$ckey}.='; '.$logentry;
 2131: # ready to assign
 2132:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2133:                                                  $cdom,$cnum) eq 'ok') {
 2134: 	    return 'ok';
 2135:         } else {
 2136: 	    return 'error: Count not store comment.';
 2137:         }
 2138:     } else {
 2139: # the key does not exist
 2140: 	return 'error: The key does not exist';
 2141:     }
 2142: }
 2143: 
 2144: # ------------------------------------------------------ Generate a set of keys
 2145: 
 2146: sub generate_access_keys {
 2147:     my ($number,$cdom,$cnum,$logentry)=@_;
 2148:     $cdom=
 2149:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2150:     $cnum=
 2151:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2152:     unless (&allowed('mky',$cdom)) { return 0; }
 2153:     unless (($cdom) && ($cnum)) { return 0; }
 2154:     if ($number>10000) { return 0; }
 2155:     sleep(2); # make sure don't get same seed twice
 2156:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2157:     my $total=0;
 2158:     for (my $i=1;$i<=$number;$i++) {
 2159:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2160:                   sprintf("%lx",int(100000*rand)).'-'.
 2161:                   sprintf("%lx",int(100000*rand));
 2162:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2163:        $newkey=~s/0/h/g; # and also 0 and O
 2164:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2165:        if ($existing{$newkey}) {
 2166:            $i--;
 2167:        } else {
 2168: 	  if (&put('accesskeys',
 2169:               { $newkey => '# generated '.localtime().
 2170:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2171:                            '; '.$logentry },
 2172: 		   $cdom,$cnum) eq 'ok') {
 2173:               $total++;
 2174: 	  }
 2175:        }
 2176:     }
 2177:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2178:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2179:     return $total;
 2180: }
 2181: 
 2182: # ------------------------------------------------------- Validate an accesskey
 2183: 
 2184: sub validate_access_key {
 2185:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2186:     $cdom=
 2187:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2188:     $cnum=
 2189:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2190:     $udom=$env{'user.domain'} unless (defined($udom));
 2191:     $uname=$env{'user.name'} unless (defined($uname));
 2192:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2193:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2194: }
 2195: 
 2196: # ------------------------------------- Find the section of student in a course
 2197: sub devalidate_getsection_cache {
 2198:     my ($udom,$unam,$courseid)=@_;
 2199:     my $hashid="$udom:$unam:$courseid";
 2200:     &devalidate_cache_new('getsection',$hashid);
 2201: }
 2202: 
 2203: sub courseid_to_courseurl {
 2204:     my ($courseid) = @_;
 2205:     #already url style courseid
 2206:     return $courseid if ($courseid =~ m{^/});
 2207: 
 2208:     if (exists($env{'course.'.$courseid.'.num'})) {
 2209: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2210: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2211: 	return "/$cdom/$cnum";
 2212:     }
 2213: 
 2214:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2215:     if (exists($courseinfo{'num'})) {
 2216: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2217:     }
 2218: 
 2219:     return undef;
 2220: }
 2221: 
 2222: sub getsection {
 2223:     my ($udom,$unam,$courseid)=@_;
 2224:     my $cachetime=1800;
 2225: 
 2226:     my $hashid="$udom:$unam:$courseid";
 2227:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2228:     if (defined($cached)) { return $result; }
 2229: 
 2230:     my %Pending; 
 2231:     my %Expired;
 2232:     #
 2233:     # Each role can either have not started yet (pending), be active, 
 2234:     #    or have expired.
 2235:     #
 2236:     # If there is an active role, we are done.
 2237:     #
 2238:     # If there is more than one role which has not started yet, 
 2239:     #     choose the one which will start sooner
 2240:     # If there is one role which has not started yet, return it.
 2241:     #
 2242:     # If there is more than one expired role, choose the one which ended last.
 2243:     # If there is a role which has expired, return it.
 2244:     #
 2245:     $courseid = &courseid_to_courseurl($courseid);
 2246:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2247:     foreach my $key (keys(%roleshash)) {
 2248:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2249:         my $section=$1;
 2250:         if ($key eq $courseid.'_st') { $section=''; }
 2251:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2252:         my $now=time;
 2253:         if (defined($end) && $end && ($now > $end)) {
 2254:             $Expired{$end}=$section;
 2255:             next;
 2256:         }
 2257:         if (defined($start) && $start && ($now < $start)) {
 2258:             $Pending{$start}=$section;
 2259:             next;
 2260:         }
 2261:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2262:     }
 2263:     #
 2264:     # Presumedly there will be few matching roles from the above
 2265:     # loop and the sorting time will be negligible.
 2266:     if (scalar(keys(%Pending))) {
 2267:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2268:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2269:     } 
 2270:     if (scalar(keys(%Expired))) {
 2271:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2272:         my $time = pop(@sorted);
 2273:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2274:     }
 2275:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2276: }
 2277: 
 2278: sub save_cache {
 2279:     &purge_remembered();
 2280:     #&Apache::loncommon::validate_page();
 2281:     undef(%env);
 2282:     undef($env_loaded);
 2283: }
 2284: 
 2285: my $to_remember=-1;
 2286: my %remembered;
 2287: my %accessed;
 2288: my $kicks=0;
 2289: my $hits=0;
 2290: sub make_key {
 2291:     my ($name,$id) = @_;
 2292:     if (length($id) > 65 
 2293: 	&& length(&escape($id)) > 200) {
 2294: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2295:     }
 2296:     return &escape($name.':'.$id);
 2297: }
 2298: 
 2299: sub devalidate_cache_new {
 2300:     my ($name,$id,$debug) = @_;
 2301:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2302:     $id=&make_key($name,$id);
 2303:     $memcache->delete($id);
 2304:     delete($remembered{$id});
 2305:     delete($accessed{$id});
 2306: }
 2307: 
 2308: sub is_cached_new {
 2309:     my ($name,$id,$debug) = @_;
 2310:     $id=&make_key($name,$id);
 2311:     if (exists($remembered{$id})) {
 2312: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2313: 	$accessed{$id}=[&gettimeofday()];
 2314: 	$hits++;
 2315: 	return ($remembered{$id},1);
 2316:     }
 2317:     my $value = $memcache->get($id);
 2318:     if (!(defined($value))) {
 2319: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2320: 	return (undef,undef);
 2321:     }
 2322:     if ($value eq '__undef__') {
 2323: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2324: 	$value=undef;
 2325:     }
 2326:     &make_room($id,$value,$debug);
 2327:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2328:     return ($value,1);
 2329: }
 2330: 
 2331: sub do_cache_new {
 2332:     my ($name,$id,$value,$time,$debug) = @_;
 2333:     $id=&make_key($name,$id);
 2334:     my $setvalue=$value;
 2335:     if (!defined($setvalue)) {
 2336: 	$setvalue='__undef__';
 2337:     }
 2338:     if (!defined($time) ) {
 2339: 	$time=600;
 2340:     }
 2341:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2342:     my $result = $memcache->set($id,$setvalue,$time);
 2343:     if (! $result) {
 2344: 	&logthis("caching of id -> $id  failed");
 2345: 	$memcache->disconnect_all();
 2346:     }
 2347:     # need to make a copy of $value
 2348:     &make_room($id,$value,$debug);
 2349:     return $value;
 2350: }
 2351: 
 2352: sub make_room {
 2353:     my ($id,$value,$debug)=@_;
 2354: 
 2355:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2356:                                     : $value;
 2357:     if ($to_remember<0) { return; }
 2358:     $accessed{$id}=[&gettimeofday()];
 2359:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2360:     my $to_kick;
 2361:     my $max_time=0;
 2362:     foreach my $other (keys(%accessed)) {
 2363: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2364: 	    $to_kick=$other;
 2365: 	    $max_time=&tv_interval($accessed{$other});
 2366: 	}
 2367:     }
 2368:     delete($remembered{$to_kick});
 2369:     delete($accessed{$to_kick});
 2370:     $kicks++;
 2371:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2372:     return;
 2373: }
 2374: 
 2375: sub purge_remembered {
 2376:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2377:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2378:     undef(%remembered);
 2379:     undef(%accessed);
 2380: }
 2381: # ------------------------------------- Read an entry from a user's environment
 2382: 
 2383: sub userenvironment {
 2384:     my ($udom,$unam,@what)=@_;
 2385:     my $items;
 2386:     foreach my $item (@what) {
 2387:         $items.=&escape($item).'&';
 2388:     }
 2389:     $items=~s/\&$//;
 2390:     my %returnhash=();
 2391:     my $uhome = &homeserver($unam,$udom);
 2392:     unless ($uhome eq 'no_host') {
 2393:         my @answer=split(/\&/, 
 2394:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2395:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2396:             return %returnhash;
 2397:         }
 2398:         my $i;
 2399:         for ($i=0;$i<=$#what;$i++) {
 2400: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2401:         }
 2402:     }
 2403:     return %returnhash;
 2404: }
 2405: 
 2406: # ---------------------------------------------------------- Get a studentphoto
 2407: sub studentphoto {
 2408:     my ($udom,$unam,$ext) = @_;
 2409:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2410:     if (defined($env{'request.course.id'})) {
 2411:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2412:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2413:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2414:             } else {
 2415:                 my ($result,$perm_reqd)=
 2416: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2417:                 if ($result eq 'ok') {
 2418:                     if (!($perm_reqd eq 'yes')) {
 2419:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2420:                     }
 2421:                 }
 2422:             }
 2423:         }
 2424:     } else {
 2425:         my ($result,$perm_reqd) = 
 2426: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2427:         if ($result eq 'ok') {
 2428:             if (!($perm_reqd eq 'yes')) {
 2429:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2430:             }
 2431:         }
 2432:     }
 2433:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2434: }
 2435: 
 2436: sub retrievestudentphoto {
 2437:     my ($udom,$unam,$ext,$type) = @_;
 2438:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2439:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2440:     if ($ret eq 'ok') {
 2441:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2442:         if ($type eq 'thumbnail') {
 2443:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2444:         }
 2445:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2446:         return $tokenurl;
 2447:     } else {
 2448:         if ($type eq 'thumbnail') {
 2449:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2450:         } else { 
 2451:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2452:         }
 2453:     }
 2454: }
 2455: 
 2456: # -------------------------------------------------------------------- New chat
 2457: 
 2458: sub chatsend {
 2459:     my ($newentry,$anon,$group)=@_;
 2460:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2461:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2462:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2463:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2464: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2465: 		   &escape($newentry)).':'.$group,$chome);
 2466: }
 2467: 
 2468: # ------------------------------------------ Find current version of a resource
 2469: 
 2470: sub getversion {
 2471:     my $fname=&clutter(shift);
 2472:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2473:     return &currentversion(&filelocation('',$fname));
 2474: }
 2475: 
 2476: sub currentversion {
 2477:     my $fname=shift;
 2478:     my $author=$fname;
 2479:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2480:     my ($udom,$uname)=split(/\//,$author);
 2481:     my $home=&homeserver($uname,$udom);
 2482:     if ($home eq 'no_host') { 
 2483:         return -1; 
 2484:     }
 2485:     my $answer=&reply("currentversion:$fname",$home);
 2486:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2487: 	return -1;
 2488:     }
 2489:     return $answer;
 2490: }
 2491: 
 2492: #
 2493: # Return special version number of resource if set by override, empty otherwise
 2494: #
 2495: sub usedversion {
 2496:     my $fname=shift;
 2497:     unless ($fname) { $fname=$env{'request.uri'}; }
 2498:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2499:     if ($urlversion) { return $urlversion; }
 2500:     return '';
 2501: }
 2502: 
 2503: # ----------------------------- Subscribe to a resource, return URL if possible
 2504: 
 2505: sub subscribe {
 2506:     my $fname=shift;
 2507:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2508:     $fname=~s/[\n\r]//g;
 2509:     my $author=$fname;
 2510:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2511:     my ($udom,$uname)=split(/\//,$author);
 2512:     my $home=homeserver($uname,$udom);
 2513:     if ($home eq 'no_host') {
 2514:         return 'not_found';
 2515:     }
 2516:     my $answer=reply("sub:$fname",$home);
 2517:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2518: 	$answer.=' by '.$home;
 2519:     }
 2520:     return $answer;
 2521: }
 2522:     
 2523: # -------------------------------------------------------------- Replicate file
 2524: 
 2525: sub repcopy {
 2526:     my $filename=shift;
 2527:     $filename=~s/\/+/\//g;
 2528:     my $londocroot = $perlvar{'lonDocRoot'};
 2529:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2530:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2531:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2532: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2533: 	return &repcopy_userfile($filename);
 2534:     }
 2535:     $filename=~s/[\n\r]//g;
 2536:     my $transname="$filename.in.transfer";
 2537: # FIXME: this should flock
 2538:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2539:     my $remoteurl=subscribe($filename);
 2540:     if ($remoteurl =~ /^con_lost by/) {
 2541: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2542:            return 'unavailable';
 2543:     } elsif ($remoteurl eq 'not_found') {
 2544: 	   #&logthis("Subscribe returned not_found: $filename");
 2545: 	   return 'not_found';
 2546:     } elsif ($remoteurl =~ /^rejected by/) {
 2547: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2548:            return 'forbidden';
 2549:     } elsif ($remoteurl eq 'directory') {
 2550:            return 'ok';
 2551:     } else {
 2552:         my $author=$filename;
 2553:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2554:         my ($udom,$uname)=split(/\//,$author);
 2555:         my $home=homeserver($uname,$udom);
 2556:         unless ($home eq $perlvar{'lonHostID'}) {
 2557:            my @parts=split(/\//,$filename);
 2558:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2559:            if ($path ne "$londocroot/res") {
 2560:                &logthis("Malconfiguration for replication: $filename");
 2561: 	       return 'bad_request';
 2562:            }
 2563:            my $count;
 2564:            for ($count=5;$count<$#parts;$count++) {
 2565:                $path.="/$parts[$count]";
 2566:                if ((-e $path)!=1) {
 2567: 		   mkdir($path,0777);
 2568:                }
 2569:            }
 2570:            my $ua=new LWP::UserAgent;
 2571:            my $request=new HTTP::Request('GET',"$remoteurl");
 2572:            my $response=$ua->request($request,$transname);
 2573:            if ($response->is_error()) {
 2574: 	       unlink($transname);
 2575:                my $message=$response->status_line;
 2576:                &logthis("<font color=\"blue\">WARNING:"
 2577:                        ." LWP get: $message: $filename</font>");
 2578:                return 'unavailable';
 2579:            } else {
 2580: 	       if ($remoteurl!~/\.meta$/) {
 2581:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2582:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2583:                   if ($mresponse->is_error()) {
 2584: 		      unlink($filename.'.meta');
 2585:                       &logthis(
 2586:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2587:                   }
 2588: 	       }
 2589:                rename($transname,$filename);
 2590:                return 'ok';
 2591:            }
 2592:        }
 2593:     }
 2594: }
 2595: 
 2596: # ------------------------------------------------ Get server side include body
 2597: sub ssi_body {
 2598:     my ($filelink,%form)=@_;
 2599:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2600:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2601:     }
 2602:     my $output='';
 2603:     my $response;
 2604:     if ($filelink=~/^https?\:/) {
 2605:        ($output,$response)=&externalssi($filelink);
 2606:     } else {
 2607:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2608:        $filelink .= 'inhibitmenu=yes';
 2609:        ($output,$response)=&ssi($filelink,%form);
 2610:     }
 2611:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2612:     $output=~s/^.*?\<body[^\>]*\>//si;
 2613:     $output=~s/\<\/body\s*\>.*?$//si;
 2614:     if (wantarray) {
 2615:         return ($output, $response);
 2616:     } else {
 2617:         return $output;
 2618:     }
 2619: }
 2620: 
 2621: # --------------------------------------------------------- Server Side Include
 2622: 
 2623: sub absolute_url {
 2624:     my ($host_name) = @_;
 2625:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2626:     if ($host_name eq '') {
 2627: 	$host_name = $ENV{'SERVER_NAME'};
 2628:     }
 2629:     return $protocol.$host_name;
 2630: }
 2631: 
 2632: #
 2633: #   Server side include.
 2634: # Parameters:
 2635: #  fn     Possibly encrypted resource name/id.
 2636: #  form   Hash that describes how the rendering should be done
 2637: #         and other things.
 2638: # Returns:
 2639: #   Scalar context: The content of the response.
 2640: #   Array context:  2 element list of the content and the full response object.
 2641: #     
 2642: sub ssi {
 2643: 
 2644:     my ($fn,%form)=@_;
 2645:     my $ua=new LWP::UserAgent;
 2646:     my $request;
 2647: 
 2648:     $form{'no_update_last_known'}=1;
 2649:     &Apache::lonenc::check_encrypt(\$fn);
 2650:     if (%form) {
 2651:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2652:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2653:     } else {
 2654:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2655:     }
 2656: 
 2657:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2658:     my $response= $ua->request($request);
 2659:     my $content = $response->content;
 2660: 
 2661: 
 2662:     if (wantarray) {
 2663: 	return ($content, $response);
 2664:     } else {
 2665: 	return $content;
 2666:     }
 2667: }
 2668: 
 2669: sub externalssi {
 2670:     my ($url)=@_;
 2671:     my $ua=new LWP::UserAgent;
 2672:     my $request=new HTTP::Request('GET',$url);
 2673:     my $response=$ua->request($request);
 2674:     if (wantarray) {
 2675:         return ($response->content, $response);
 2676:     } else {
 2677:         return $response->content;
 2678:     }
 2679: }
 2680: 
 2681: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2682: 
 2683: sub allowuploaded {
 2684:     my ($srcurl,$url)=@_;
 2685:     $url=&clutter(&declutter($url));
 2686:     my $dir=$url;
 2687:     $dir=~s/\/[^\/]+$//;
 2688:     my %httpref=();
 2689:     my $httpurl=&hreflocation('',$url);
 2690:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2691:     &Apache::lonnet::appenv(\%httpref);
 2692: }
 2693: 
 2694: #
 2695: # Determine if the current user should be able to edit a particular resource,
 2696: # when viewing in course context.
 2697: # (a) When viewing resource used to determine if "Edit" item is included in 
 2698: #     Functions.
 2699: # (b) When displaying folder contents in course editor, used to determine if
 2700: #     "Edit" link will be displayed alongside resource.
 2701: #
 2702: #  input: six args -- filename (decluttered), course number, course domain,
 2703: #                   url, symb (if registered) and group (if this is a group
 2704: #                   item -- e.g., bulletin board, group page etc.).
 2705: #  output: array of five scalars -- 
 2706: #          $cfile -- url for file editing if editable on current server
 2707: #          $home -- homeserver of resource (i.e., for author if published,
 2708: #                                           or course if uploaded.).
 2709: #          $switchserver --  1 if server switch will be needed.
 2710: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2711: #          $forceview -- 1 if icon/link should be to go to view mode
 2712: #
 2713: 
 2714: sub can_edit_resource {
 2715:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2716:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2717: #
 2718: # For aboutme pages user can only edit his/her own.
 2719: #
 2720:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2721:         my ($sdom,$sname) = ($1,$2);
 2722:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2723:             $home = $env{'user.home'};
 2724:             $cfile = $resurl;
 2725:             if ($env{'form.forceedit'}) {
 2726:                 $forceview = 1;
 2727:             } else {
 2728:                 $forceedit = 1;
 2729:             }
 2730:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2731:         } else {
 2732:             return;
 2733:         }
 2734:     }
 2735: 
 2736:     if ($env{'request.course.id'}) {
 2737:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2738:         if ($group ne '') {
 2739: # if this is a group homepage or group bulletin board, check group privs
 2740:             my $allowed = 0;
 2741:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2742:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2743:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2744:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2745:                     $allowed = 1;
 2746:                 }
 2747:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2748:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2749:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2750:                     $allowed = 1;
 2751:                 }
 2752:             }
 2753:             if ($allowed) {
 2754:                 $home=&homeserver($cnum,$cdom);
 2755:                 if ($env{'form.forceedit'}) {
 2756:                     $forceview = 1;
 2757:                 } else {
 2758:                     $forceedit = 1;
 2759:                 }
 2760:                 $cfile = $resurl;
 2761:             } else {
 2762:                 return;
 2763:             }
 2764:         } else {
 2765:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2766:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2767:                     return;
 2768:                 }
 2769:             } elsif (!$crsedit) {
 2770: #
 2771: # No edit allowed where CC has switched to student role.
 2772: #
 2773:                 return;
 2774:             }
 2775:         }
 2776:     }
 2777: 
 2778:     if ($file ne '') {
 2779:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2780:             if (&is_course_upload($file,$cnum,$cdom)) {
 2781:                 $uploaded = 1;
 2782:                 $incourse = 1;
 2783:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2784:                     $cfile = &hreflocation('',$file);
 2785:                     if ($env{'form.forceedit'}) {
 2786:                         $forceview = 1;
 2787:                     } else {
 2788:                         $forceedit = 1;
 2789:                     }
 2790:                 }
 2791:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2792:                 $incourse = 1;
 2793:                 if ($env{'form.forceedit'}) {
 2794:                     $forceview = 1;
 2795:                 } else {
 2796:                     $forceedit = 1;
 2797:                 }
 2798:                 $cfile = $resurl;
 2799:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2800:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2801:                     $incourse = 1;
 2802:                     if ($env{'form.forceedit'}) {
 2803:                         $forceview = 1;
 2804:                     } else {
 2805:                         $forceedit = 1;
 2806:                     }
 2807:                     $cfile = $resurl;
 2808:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2809:                     $incourse = 1;
 2810:                     $cfile = $resurl.'/smpedit';
 2811:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2812:                     $incourse = 1;
 2813:                     if ($env{'form.forceedit'}) {
 2814:                         $forceview = 1;
 2815:                     } else {
 2816:                         $forceedit = 1;
 2817:                     }
 2818:                     $cfile = $resurl;
 2819:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2820:                     $incourse = 1;
 2821:                     if ($env{'form.forceedit'}) {
 2822:                         $forceview = 1;
 2823:                     } else {
 2824:                         $forceedit = 1;
 2825:                     }
 2826:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2827:                 }
 2828:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2829:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2830:                 if (&is_on_map($template)) { 
 2831:                     $incourse = 1;
 2832:                     $forceview = 1;
 2833:                     $cfile = $template;
 2834:                 }
 2835:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2836:                     $incourse = 1;
 2837:                     if ($env{'form.forceedit'}) {
 2838:                         $forceview = 1;
 2839:                     } else {
 2840:                         $forceedit = 1;
 2841:                     }
 2842:                     $cfile = $resurl;
 2843:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2844:                 $incourse = 1;
 2845:                 $forceview = 1;
 2846:                 if ($symb) {
 2847:                     my ($map,$id,$res)=&decode_symb($symb);
 2848:                     $env{'request.symb'} = $symb;
 2849:                     $cfile = &clutter($res);
 2850:                 } else {
 2851:                     $cfile = $env{'form.suppurl'};
 2852:                     $cfile =~ s{^http://}{};
 2853:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2854:                 }
 2855:             }
 2856:         }
 2857:         if ($uploaded || $incourse) {
 2858:             $home=&homeserver($cnum,$cdom);
 2859:         } elsif ($file !~ m{/$}) {
 2860:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2861:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2862:             # Check that the user has permission to edit this resource
 2863:             my $setpriv = 1;
 2864:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2865:             if (defined($cfudom)) {
 2866:                 $home=&homeserver($cfuname,$cfudom);
 2867:                 $cfile=$file;
 2868:             }
 2869:         }
 2870:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2871:             (($home ne '') && ($home ne 'no_host'))) {
 2872:             my @ids=&current_machine_ids();
 2873:             unless (grep(/^\Q$home\E$/,@ids)) {
 2874:                 $switchserver=1;
 2875:             }
 2876:         }
 2877:     }
 2878:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2879: }
 2880: 
 2881: sub is_course_upload {
 2882:     my ($file,$cnum,$cdom) = @_;
 2883:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2884:     $uploadpath =~ s{^\/}{};
 2885:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2886:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2887:         return 1;
 2888:     }
 2889:     return;
 2890: }
 2891: 
 2892: sub in_course {
 2893:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2894:     if ($hideprivileged) {
 2895:         my $skipuser;
 2896:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2897:         my @possdoms = ($cdom);  
 2898:         if ($coursehash{'checkforpriv'}) { 
 2899:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2900:         }
 2901:         if (&privileged($uname,$udom,\@possdoms)) {
 2902:             $skipuser = 1;
 2903:             if ($coursehash{'nothideprivileged'}) {
 2904:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2905:                     my $user;
 2906:                     if ($item =~ /:/) {
 2907:                         $user = $item;
 2908:                     } else {
 2909:                         $user = join(':',split(/[\@]/,$item));
 2910:                     }
 2911:                     if ($user eq $uname.':'.$udom) {
 2912:                         undef($skipuser);
 2913:                         last;
 2914:                     }
 2915:                 }
 2916:             }
 2917:             if ($skipuser) {
 2918:                 return 0;
 2919:             }
 2920:         }
 2921:     }
 2922:     $type ||= 'any';
 2923:     if (!defined($cdom) || !defined($cnum)) {
 2924:         my $cid  = $env{'request.course.id'};
 2925:         $cdom = $env{'course.'.$cid.'.domain'};
 2926:         $cnum = $env{'course.'.$cid.'.num'};
 2927:     }
 2928:     my $typesref;
 2929:     if (($type eq 'any') || ($type eq 'all')) {
 2930:         $typesref = ['active','previous','future'];
 2931:     } elsif ($type eq 'previous' || $type eq 'future') {
 2932:         $typesref = [$type];
 2933:     }
 2934:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2935:                               $typesref,undef,[$cdom]);
 2936:     my ($tmp) = keys(%roles);
 2937:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2938:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2939:     if (@course_roles > 0) {
 2940:         return 1;
 2941:     }
 2942:     return 0;
 2943: }
 2944: 
 2945: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2946: # input: action, courseID, current domain, intended
 2947: #        path to file, source of file, instruction to parse file for objects,
 2948: #        ref to hash for embedded objects,
 2949: #        ref to hash for codebase of java objects.
 2950: #        reference to scalar to accommodate mime type determined
 2951: #          from File::MMagic if $parser = parse.
 2952: #
 2953: # output: url to file (if action was uploaddoc), 
 2954: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2955: #
 2956: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2957: # course.
 2958: #
 2959: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2960: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2961: #          course's home server.
 2962: #
 2963: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2964: #          be copied from $source (current location) to 
 2965: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2966: #         and will then be copied to
 2967: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2968: #         course's home server.
 2969: #
 2970: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2971: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2972: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2973: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2974: #         in course's home server.
 2975: #
 2976: 
 2977: sub process_coursefile {
 2978:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2979:         $mimetype)=@_;
 2980:     my $fetchresult;
 2981:     my $home=&homeserver($docuname,$docudom);
 2982:     if ($action eq 'propagate') {
 2983:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2984: 			     $home);
 2985:     } else {
 2986:         my $fpath = '';
 2987:         my $fname = $file;
 2988:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2989:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2990:         my $filepath = &build_filepath($fpath);
 2991:         if ($action eq 'copy') {
 2992:             if ($source eq '') {
 2993:                 $fetchresult = 'no source file';
 2994:                 return $fetchresult;
 2995:             } else {
 2996:                 my $destination = $filepath.'/'.$fname;
 2997:                 rename($source,$destination);
 2998:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2999:                                  $home);
 3000:             }
 3001:         } elsif ($action eq 'uploaddoc') {
 3002:             open(my $fh,'>'.$filepath.'/'.$fname);
 3003:             print $fh $env{'form.'.$source};
 3004:             close($fh);
 3005:             if ($parser eq 'parse') {
 3006:                 my $mm = new File::MMagic;
 3007:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3008:                 if ($type eq 'text/html') {
 3009:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3010:                     unless ($parse_result eq 'ok') {
 3011:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3012:                     }
 3013:                 }
 3014:                 if (ref($mimetype)) {
 3015:                     $$mimetype = $type;
 3016:                 } 
 3017:             }
 3018:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3019:                                  $home);
 3020:             if ($fetchresult eq 'ok') {
 3021:                 return '/uploaded/'.$fpath.'/'.$fname;
 3022:             } else {
 3023:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3024:                         ' to host '.$home.': '.$fetchresult);
 3025:                 return '/adm/notfound.html';
 3026:             }
 3027:         }
 3028:     }
 3029:     unless ( $fetchresult eq 'ok') {
 3030:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3031:              ' to host '.$home.': '.$fetchresult);
 3032:     }
 3033:     return $fetchresult;
 3034: }
 3035: 
 3036: sub build_filepath {
 3037:     my ($fpath) = @_;
 3038:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3039:     unless ($fpath eq '') {
 3040:         my @parts=split('/',$fpath);
 3041:         foreach my $part (@parts) {
 3042:             $filepath.= '/'.$part;
 3043:             if ((-e $filepath)!=1) {
 3044:                 mkdir($filepath,0777);
 3045:             }
 3046:         }
 3047:     }
 3048:     return $filepath;
 3049: }
 3050: 
 3051: sub store_edited_file {
 3052:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3053:     my $file = $primary_url;
 3054:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3055:     my $fpath = '';
 3056:     my $fname = $file;
 3057:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3058:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3059:     my $filepath = &build_filepath($fpath);
 3060:     open(my $fh,'>'.$filepath.'/'.$fname);
 3061:     print $fh $content;
 3062:     close($fh);
 3063:     my $home=&homeserver($docuname,$docudom);
 3064:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3065: 			  $home);
 3066:     if ($$fetchresult eq 'ok') {
 3067:         return '/uploaded/'.$fpath.'/'.$fname;
 3068:     } else {
 3069:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3070: 		 ' to host '.$home.': '.$$fetchresult);
 3071:         return '/adm/notfound.html';
 3072:     }
 3073: }
 3074: 
 3075: sub clean_filename {
 3076:     my ($fname,$args)=@_;
 3077: # Replace Windows backslashes by forward slashes
 3078:     $fname=~s/\\/\//g;
 3079:     if (!$args->{'keep_path'}) {
 3080:         # Get rid of everything but the actual filename
 3081: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3082:     }
 3083: # Replace spaces by underscores
 3084:     $fname=~s/\s+/\_/g;
 3085: # Replace all other weird characters by nothing
 3086:     $fname=~s{[^/\w\.\-]}{}g;
 3087: # Replace all .\d. sequences with _\d. so they no longer look like version
 3088: # numbers
 3089:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3090:     return $fname;
 3091: }
 3092: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3093: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3094: # image with the same aspect ratio as the original, but with dimensions which do 
 3095: # not exceed $resizewidth and $resizeheight.
 3096:  
 3097: sub resizeImage {
 3098:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3099:     my $ima = Image::Magick->new;
 3100:     my $resized;
 3101:     if (-e $img_path) {
 3102:         $ima->Read($img_path);
 3103:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3104:             my $width = $ima->Get('width');
 3105:             my $height = $ima->Get('height');
 3106:             if ($width > $resizewidth) {
 3107: 	        my $factor = $width/$resizewidth;
 3108:                 my $newheight = $height/$factor;
 3109:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3110:                 $resized = 1;
 3111:             }
 3112:         }
 3113:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3114:             my $width = $ima->Get('width');
 3115:             my $height = $ima->Get('height');
 3116:             if ($height > $resizeheight) {
 3117:                 my $factor = $height/$resizeheight;
 3118:                 my $newwidth = $width/$factor;
 3119:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3120:                 $resized = 1;
 3121:             }
 3122:         }
 3123:         if ($resized) {
 3124:             $ima->Write($img_path);
 3125:         }
 3126:     }
 3127:     return;
 3128: }
 3129: 
 3130: # --------------- Take an uploaded file and put it into the userfiles directory
 3131: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3132: #                    the desired filename is in $env{"form.$formname.filename"}
 3133: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3134: #                                    canceloverwrite, or ''. 
 3135: #                   if 'coursedoc': upload to the current course
 3136: #                   if 'existingfile': write file to tmp/overwrites directory 
 3137: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3138: #                   $context is passed as argument to &finishuserfileupload
 3139: #        $subdir - directory in userfile to store the file into
 3140: #        $parser - instruction to parse file for objects ($parser = parse)    
 3141: #        $allfiles - reference to hash for embedded objects
 3142: #        $codebase - reference to hash for codebase of java objects
 3143: #        $desuname - username for permanent storage of uploaded file
 3144: #        $dsetudom - domain for permanaent storage of uploaded file
 3145: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3146: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3147: #        $resizewidth - width (pixels) to which to resize uploaded image
 3148: #        $resizeheight - height (pixels) to which to resize uploaded image
 3149: #        $mimetype - reference to scalar to accommodate mime type determined
 3150: #                    from File::MMagic.
 3151: # 
 3152: # output: url of file in userspace, or error: <message> 
 3153: #             or /adm/notfound.html if failure to upload occurse
 3154: 
 3155: sub userfileupload {
 3156:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3157:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3158:     if (!defined($subdir)) { $subdir='unknown'; }
 3159:     my $fname=$env{'form.'.$formname.'.filename'};
 3160:     $fname=&clean_filename($fname);
 3161:     # See if there is anything left
 3162:     unless ($fname) { return 'error: no uploaded file'; }
 3163:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3164:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3165:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3166:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3167:         my $now = time;
 3168:         my $filepath;
 3169:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3170:              $filepath = 'tmp/helprequests/'.$now;
 3171:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3172:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3173:                          '_'.$env{'user.domain'}.'/pending';
 3174:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3175:             my ($docuname,$docudom);
 3176:             if ($destudom) {
 3177:                 $docudom = $destudom;
 3178:             } else {
 3179:                 $docudom = $env{'user.domain'};
 3180:             }
 3181:             if ($destuname) {
 3182:                 $docuname = $destuname;
 3183:             } else {
 3184:                 $docuname = $env{'user.name'};
 3185:             }
 3186:             if (exists($env{'form.group'})) {
 3187:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3188:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3189:             }
 3190:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3191:             if ($context eq 'canceloverwrite') {
 3192:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3193:                 if (-e  $tempfile) {
 3194:                     my @info = stat($tempfile);
 3195:                     if ($info[9] eq $env{'form.timestamp'}) {
 3196:                         unlink($tempfile);
 3197:                     }
 3198:                 }
 3199:                 return;
 3200:             }
 3201:         }
 3202:         # Create the directory if not present
 3203:         my @parts=split(/\//,$filepath);
 3204:         my $fullpath = $perlvar{'lonDaemons'};
 3205:         for (my $i=0;$i<@parts;$i++) {
 3206:             $fullpath .= '/'.$parts[$i];
 3207:             if ((-e $fullpath)!=1) {
 3208:                 mkdir($fullpath,0777);
 3209:             }
 3210:         }
 3211:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3212:         print $fh $env{'form.'.$formname};
 3213:         close($fh);
 3214:         if ($context eq 'existingfile') {
 3215:             my @info = stat($fullpath.'/'.$fname);
 3216:             return ($fullpath.'/'.$fname,$info[9]);
 3217:         } else {
 3218:             return $fullpath.'/'.$fname;
 3219:         }
 3220:     }
 3221:     if ($subdir eq 'scantron') {
 3222:         $fname = 'scantron_orig_'.$fname;
 3223:     } else {
 3224:         $fname="$subdir/$fname";
 3225:     }
 3226:     if ($context eq 'coursedoc') {
 3227: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3228: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3229:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3230:             return &finishuserfileupload($docuname,$docudom,
 3231: 					 $formname,$fname,$parser,$allfiles,
 3232: 					 $codebase,$thumbwidth,$thumbheight,
 3233:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3234:         } else {
 3235:             if ($env{'form.folder'}) {
 3236:                 $fname=$env{'form.folder'}.'/'.$fname;
 3237:             }
 3238:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3239: 				       $fname,$formname,$parser,
 3240: 				       $allfiles,$codebase,$mimetype);
 3241:         }
 3242:     } elsif (defined($destuname)) {
 3243:         my $docuname=$destuname;
 3244:         my $docudom=$destudom;
 3245: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3246: 				     $parser,$allfiles,$codebase,
 3247:                                      $thumbwidth,$thumbheight,
 3248:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3249:     } else {
 3250:         my $docuname=$env{'user.name'};
 3251:         my $docudom=$env{'user.domain'};
 3252:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3253:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3254:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3255:         }
 3256: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3257: 				     $parser,$allfiles,$codebase,
 3258:                                      $thumbwidth,$thumbheight,
 3259:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3260:     }
 3261: }
 3262: 
 3263: sub finishuserfileupload {
 3264:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3265:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3266:     my $path=$docudom.'/'.$docuname.'/';
 3267:     my $filepath=$perlvar{'lonDocRoot'};
 3268:   
 3269:     my ($fnamepath,$file,$fetchthumb);
 3270:     $file=$fname;
 3271:     if ($fname=~m|/|) {
 3272:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3273: 	$path.=$fnamepath.'/';
 3274:     }
 3275:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3276:     my $count;
 3277:     for ($count=4;$count<=$#parts;$count++) {
 3278:         $filepath.="/$parts[$count]";
 3279:         if ((-e $filepath)!=1) {
 3280: 	    mkdir($filepath,0777);
 3281:         }
 3282:     }
 3283: 
 3284: # Save the file
 3285:     {
 3286: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3287: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3288: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3289: 	    return '/adm/notfound.html';
 3290: 	}
 3291:         if ($context eq 'overwrite') {
 3292:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3293:             my $target = $filepath.'/'.$file;
 3294:             if (-e $source) {
 3295:                 my @info = stat($source);
 3296:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3297:                     unless (&File::Copy::move($source,$target)) {
 3298:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3299:                         return "Moving from $source failed";
 3300:                     }
 3301:                 } else {
 3302:                     return "Temporary file: $source had unexpected date/time for last modification";
 3303:                 }
 3304:             } else {
 3305:                 return "Temporary file: $source missing";
 3306:             }
 3307:         } elsif (!print FH ($env{'form.'.$formname})) {
 3308: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3309: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3310: 	    return '/adm/notfound.html';
 3311: 	}
 3312: 	close(FH);
 3313:         if ($resizewidth && $resizeheight) {
 3314:             my $mm = new File::MMagic;
 3315:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3316:             if ($mime_type =~ m{^image/}) {
 3317: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3318:             }  
 3319: 	}
 3320:     }
 3321:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3322:         if (ref($mimetype)) {
 3323:             if ($$mimetype eq '') {
 3324:                 my $mm = new File::MMagic;
 3325:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3326:                 $$mimetype = $type;
 3327:             }
 3328:         }
 3329:     }
 3330:     if ($parser eq 'parse') {
 3331:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3332:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3333:                                                        $allfiles,$codebase);
 3334:             unless ($parse_result eq 'ok') {
 3335:                 &logthis('Failed to parse '.$filepath.$file.
 3336: 	   	         ' for embedded media: '.$parse_result); 
 3337:             }
 3338:         }
 3339:     }
 3340:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3341:         my $input = $filepath.'/'.$file;
 3342:         my $output = $filepath.'/'.'tn-'.$file;
 3343:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3344:         system("convert -sample $thumbsize $input $output");
 3345:         if (-e $filepath.'/'.'tn-'.$file) {
 3346:             $fetchthumb  = 1; 
 3347:         }
 3348:     }
 3349:  
 3350: # Notify homeserver to grep it
 3351: #
 3352:     my $docuhome=&homeserver($docuname,$docudom);	
 3353:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3354:     if ($fetchresult eq 'ok') {
 3355:         if ($fetchthumb) {
 3356:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3357:             if ($thumbresult ne 'ok') {
 3358:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3359:                          $docuhome.': '.$thumbresult);
 3360:             }
 3361:         }
 3362: #
 3363: # Return the URL to it
 3364:         return '/uploaded/'.$path.$file;
 3365:     } else {
 3366:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3367: 		 ': '.$fetchresult);
 3368:         return '/adm/notfound.html';
 3369:     }
 3370: }
 3371: 
 3372: sub extract_embedded_items {
 3373:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3374:     my @state = ();
 3375:     my (%lastids,%related,%shockwave,%flashvars);
 3376:     my %javafiles = (
 3377:                       codebase => '',
 3378:                       code => '',
 3379:                       archive => ''
 3380:                     );
 3381:     my %mediafiles = (
 3382:                       src => '',
 3383:                       movie => '',
 3384:                      );
 3385:     my $p;
 3386:     if ($content) {
 3387:         $p = HTML::LCParser->new($content);
 3388:     } else {
 3389:         $p = HTML::LCParser->new($fullpath);
 3390:     }
 3391:     while (my $t=$p->get_token()) {
 3392: 	if ($t->[0] eq 'S') {
 3393: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3394: 	    push(@state, $tagname);
 3395:             if (lc($tagname) eq 'allow') {
 3396:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3397:             }
 3398: 	    if (lc($tagname) eq 'img') {
 3399: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3400: 	    }
 3401: 	    if (lc($tagname) eq 'a') {
 3402:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3403:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3404:                 }
 3405: 	    }
 3406:             if (lc($tagname) eq 'script') {
 3407:                 my $src;
 3408:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3409:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3410:                 } else {
 3411:                     if ($attr->{'src'} ne '') {
 3412:                         $src = $attr->{'src'};
 3413:                         &add_filetype($allfiles,$src,'src');
 3414:                     }
 3415:                 }
 3416:                 my $text = $p->get_trimmed_text();
 3417:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3418:                     my @swfargs = split(/,/,$1);
 3419:                     foreach my $item (@swfargs) {
 3420:                         $item =~ s/["']//g;
 3421:                         $item =~ s/^\s+//;
 3422:                         $item =~ s/\s+$//;
 3423:                     }
 3424:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3425:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3426:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3427:                         } else {
 3428:                             $related{$swfargs[0]} = [$swfargs[2]];
 3429:                         }
 3430:                     }
 3431:                 }
 3432:             }
 3433:             if (lc($tagname) eq 'link') {
 3434:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3435:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3436:                 }
 3437:             }
 3438: 	    if (lc($tagname) eq 'object' ||
 3439: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3440: 		foreach my $item (keys(%javafiles)) {
 3441: 		    $javafiles{$item} = '';
 3442: 		}
 3443:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3444:                     $lastids{lc($tagname)} = $attr->{'id'};
 3445:                 }
 3446: 	    }
 3447: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3448: 		my $name = lc($attr->{'name'});
 3449: 		foreach my $item (keys(%javafiles)) {
 3450: 		    if ($name eq $item) {
 3451: 			$javafiles{$item} = $attr->{'value'};
 3452: 			last;
 3453: 		    }
 3454: 		}
 3455:                 my $pathfrom;
 3456: 		foreach my $item (keys(%mediafiles)) {
 3457: 		    if ($name eq $item) {
 3458:                         $pathfrom = $attr->{'value'};
 3459:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3460: 			&add_filetype($allfiles,$pathfrom,$name);
 3461: 			last;
 3462: 		    }
 3463: 		}
 3464:                 if ($name eq 'flashvars') {
 3465:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3466:                 }
 3467:                 if ($pathfrom ne '') {
 3468:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3469:                                          $pathfrom);
 3470:                 }
 3471: 	    }
 3472: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3473: 		foreach my $item (keys(%javafiles)) {
 3474: 		    if ($attr->{$item}) {
 3475: 			$javafiles{$item} = $attr->{$item};
 3476: 			last;
 3477: 		    }
 3478: 		}
 3479: 		foreach my $item (keys(%mediafiles)) {
 3480: 		    if ($attr->{$item}) {
 3481: 			&add_filetype($allfiles,$attr->{$item},$item);
 3482: 			last;
 3483: 		    }
 3484: 		}
 3485:                 if (lc($tagname) eq 'embed') {
 3486:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3487:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3488:                                              $attr->{'src'});
 3489:                     }
 3490:                 }
 3491: 	    }
 3492:             if ($t->[4] =~ m{/>$}) {
 3493:                 pop(@state);  
 3494:             }
 3495: 	} elsif ($t->[0] eq 'E') {
 3496: 	    my ($tagname) = ($t->[1]);
 3497: 	    if ($javafiles{'codebase'} ne '') {
 3498: 		$javafiles{'codebase'} .= '/';
 3499: 	    }  
 3500: 	    if (lc($tagname) eq 'applet' ||
 3501: 		lc($tagname) eq 'object' ||
 3502: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3503: 		) {
 3504: 		foreach my $item (keys(%javafiles)) {
 3505: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3506: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3507: 			&add_filetype($allfiles,$file,$item);
 3508: 		    }
 3509: 		}
 3510: 	    } 
 3511: 	    pop @state;
 3512: 	}
 3513:     }
 3514:     foreach my $id (sort(keys(%flashvars))) {
 3515:         if ($shockwave{$id} ne '') {
 3516:             my @pairs = split(/\&/,$flashvars{$id});
 3517:             foreach my $pair (@pairs) {
 3518:                 my ($key,$value) = split(/\=/,$pair);
 3519:                 if ($key eq 'thumb') {
 3520:                     &add_filetype($allfiles,$value,$key);
 3521:                 } elsif ($key eq 'content') {
 3522:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3523:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3524:                     if ($ext ne '') {
 3525:                         &add_filetype($allfiles,$path.$value,$ext);
 3526:                     }
 3527:                 }
 3528:             }
 3529:         }
 3530:     }
 3531:     return 'ok';
 3532: }
 3533: 
 3534: sub add_filetype {
 3535:     my ($allfiles,$file,$type)=@_;
 3536:     if (exists($allfiles->{$file})) {
 3537: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3538: 	    push(@{$allfiles->{$file}}, &escape($type));
 3539: 	}
 3540:     } else {
 3541: 	@{$allfiles->{$file}} = (&escape($type));
 3542:     }
 3543: }
 3544: 
 3545: sub embedded_dependency {
 3546:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3547:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3548:         if (($identifier ne '') &&
 3549:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3550:             ($pathfrom ne '')) {
 3551:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3552:             foreach my $dep (@{$related->{$identifier}}) {
 3553:                 &add_filetype($allfiles,$path.$dep,'object');
 3554:             }
 3555:         }
 3556:     }
 3557:     return;
 3558: }
 3559: 
 3560: sub removeuploadedurl {
 3561:     my ($url)=@_;	
 3562:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3563:     return &removeuserfile($uname,$udom,$fname);
 3564: }
 3565: 
 3566: sub removeuserfile {
 3567:     my ($docuname,$docudom,$fname)=@_;
 3568:     my $home=&homeserver($docuname,$docudom);    
 3569:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3570:     if ($result eq 'ok') {	
 3571:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3572:             my $metafile = $fname.'.meta';
 3573:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3574: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3575:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3576:             my $sqlresult = 
 3577:                 &update_portfolio_table($docuname,$docudom,$file,
 3578:                                         'portfolio_metadata',$group,
 3579:                                         'delete');
 3580:         }
 3581:     }
 3582:     return $result;
 3583: }
 3584: 
 3585: sub mkdiruserfile {
 3586:     my ($docuname,$docudom,$dir)=@_;
 3587:     my $home=&homeserver($docuname,$docudom);
 3588:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3589: }
 3590: 
 3591: sub renameuserfile {
 3592:     my ($docuname,$docudom,$old,$new)=@_;
 3593:     my $home=&homeserver($docuname,$docudom);
 3594:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3595:                         &escape("$old").':'.&escape("$new"),$home);
 3596:     if ($result eq 'ok') {
 3597:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3598:             my $oldmeta = $old.'.meta';
 3599:             my $newmeta = $new.'.meta';
 3600:             my $metaresult = 
 3601:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3602: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3603:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3604:             my $sqlresult = 
 3605:                 &update_portfolio_table($docuname,$docudom,$file,
 3606:                                         'portfolio_metadata',$group,
 3607:                                         'delete');
 3608:         }
 3609:     }
 3610:     return $result;
 3611: }
 3612: 
 3613: # ------------------------------------------------------------------------- Log
 3614: 
 3615: sub log {
 3616:     my ($dom,$nam,$hom,$what)=@_;
 3617:     return critical("log:$dom:$nam:$what",$hom);
 3618: }
 3619: 
 3620: # ------------------------------------------------------------------ Course Log
 3621: #
 3622: # This routine flushes several buffers of non-mission-critical nature
 3623: #
 3624: 
 3625: sub flushcourselogs {
 3626:     &logthis('Flushing log buffers');
 3627: #
 3628: # course logs
 3629: # This is a log of all transactions in a course, which can be used
 3630: # for data mining purposes
 3631: #
 3632: # It also collects the courseid database, which lists last transaction
 3633: # times and course titles for all courseids
 3634: #
 3635:     my %courseidbuffer=();
 3636:     foreach my $crsid (keys(%courselogs)) {
 3637:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3638: 		          &escape($courselogs{$crsid}),
 3639: 		          $coursehombuf{$crsid}) eq 'ok') {
 3640: 	    delete $courselogs{$crsid};
 3641:         } else {
 3642:             &logthis('Failed to flush log buffer for '.$crsid);
 3643:             if (length($courselogs{$crsid})>40000) {
 3644:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3645:                         " exceeded maximum size, deleting.</font>");
 3646:                delete $courselogs{$crsid};
 3647:             }
 3648:         }
 3649:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3650:             'description' => $coursedescrbuf{$crsid},
 3651:             'inst_code'    => $courseinstcodebuf{$crsid},
 3652:             'type'        => $coursetypebuf{$crsid},
 3653:             'owner'       => $courseownerbuf{$crsid},
 3654:         };
 3655:     }
 3656: #
 3657: # Write course id database (reverse lookup) to homeserver of courses 
 3658: # Is used in pickcourse
 3659: #
 3660:     foreach my $crs_home (keys(%courseidbuffer)) {
 3661:         my $response = &courseidput(&host_domain($crs_home),
 3662:                                     $courseidbuffer{$crs_home},
 3663:                                     $crs_home,'timeonly');
 3664:     }
 3665: #
 3666: # File accesses
 3667: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3668: #
 3669:     foreach my $entry (keys(%accesshash)) {
 3670:         if ($entry =~ /___count$/) {
 3671:             my ($dom,$name);
 3672:             ($dom,$name,undef)=
 3673: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3674:             if (! defined($dom) || $dom eq '' || 
 3675:                 ! defined($name) || $name eq '') {
 3676:                 my $cid = $env{'request.course.id'};
 3677:                 $dom  = $env{'request.'.$cid.'.domain'};
 3678:                 $name = $env{'request.'.$cid.'.num'};
 3679:             }
 3680:             my $value = $accesshash{$entry};
 3681:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3682:             my %temphash=($url => $value);
 3683:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3684:             if ($result eq 'ok') {
 3685:                 delete $accesshash{$entry};
 3686:             }
 3687:         } else {
 3688:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3689:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3690:             my %temphash=($entry => $accesshash{$entry});
 3691:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3692:                 delete $accesshash{$entry};
 3693:             }
 3694:         }
 3695:     }
 3696: #
 3697: # Roles
 3698: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3699: #
 3700:     foreach my $entry (keys(%userrolehash)) {
 3701:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3702: 	    split(/\:/,$entry);
 3703:         if (&Apache::lonnet::put('nohist_userroles',
 3704:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3705:                 $rudom,$runame) eq 'ok') {
 3706: 	    delete $userrolehash{$entry};
 3707:         }
 3708:     }
 3709: #
 3710: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3711: #
 3712:     my %domrolebuffer = ();
 3713:     foreach my $entry (keys(%domainrolehash)) {
 3714:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3715:         if ($domrolebuffer{$rudom}) {
 3716:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3717:                       '='.&escape($domainrolehash{$entry});
 3718:         } else {
 3719:             $domrolebuffer{$rudom}.=&escape($entry).
 3720:                       '='.&escape($domainrolehash{$entry});
 3721:         }
 3722:         delete $domainrolehash{$entry};
 3723:     }
 3724:     foreach my $dom (keys(%domrolebuffer)) {
 3725: 	my %servers = &get_servers($dom,'library');
 3726: 	foreach my $tryserver (keys(%servers)) {
 3727: 	    unless (&reply('domroleput:'.$dom.':'.
 3728: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3729: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3730: 	    }
 3731:         }
 3732:     }
 3733:     $dumpcount++;
 3734: }
 3735: 
 3736: sub courselog {
 3737:     my $what=shift;
 3738:     $what=time.':'.$what;
 3739:     unless ($env{'request.course.id'}) { return ''; }
 3740:     $coursedombuf{$env{'request.course.id'}}=
 3741:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3742:     $coursenumbuf{$env{'request.course.id'}}=
 3743:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3744:     $coursehombuf{$env{'request.course.id'}}=
 3745:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3746:     $coursedescrbuf{$env{'request.course.id'}}=
 3747:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3748:     $courseinstcodebuf{$env{'request.course.id'}}=
 3749:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3750:     $courseownerbuf{$env{'request.course.id'}}=
 3751:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3752:     $coursetypebuf{$env{'request.course.id'}}=
 3753:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3754:     if (defined $courselogs{$env{'request.course.id'}}) {
 3755: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3756:     } else {
 3757: 	$courselogs{$env{'request.course.id'}}.=$what;
 3758:     }
 3759:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3760: 	&flushcourselogs();
 3761:     }
 3762: }
 3763: 
 3764: sub courseacclog {
 3765:     my $fnsymb=shift;
 3766:     unless ($env{'request.course.id'}) { return ''; }
 3767:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3768:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3769:         $what.=':POST';
 3770:         # FIXME: Probably ought to escape things....
 3771: 	foreach my $key (keys(%env)) {
 3772:             if ($key=~/^form\.(.*)/) {
 3773:                 my $formitem = $1;
 3774:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3775:                     $what.=':'.$formitem.'='.$env{$key};
 3776:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3777:                     $what.=':'.$formitem.'='.$env{$key};
 3778:                 }
 3779:             }
 3780:         }
 3781:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3782:         # FIXME: We should not be depending on a form parameter that someone
 3783:         # editing lonsearchcat.pm might change in the future.
 3784:         if ($env{'form.phase'} eq 'course_search') {
 3785:             $what.= ':POST';
 3786:             # FIXME: Probably ought to escape things....
 3787:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3788:                                  'crsdiscuss') {
 3789:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3790:             }
 3791:         }
 3792:     }
 3793:     &courselog($what);
 3794: }
 3795: 
 3796: sub countacc {
 3797:     my $url=&declutter(shift);
 3798:     return if (! defined($url) || $url eq '');
 3799:     unless ($env{'request.course.id'}) { return ''; }
 3800: #
 3801: # Mark that this url was used in this course
 3802: #
 3803:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3804: #
 3805: # Increase the access count for this resource in this child process
 3806: #
 3807:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3808:     $accesshash{$key}++;
 3809: }
 3810: 
 3811: sub linklog {
 3812:     my ($from,$to)=@_;
 3813:     $from=&declutter($from);
 3814:     $to=&declutter($to);
 3815:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3816:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3817: }
 3818: 
 3819: sub statslog {
 3820:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3821:     if ($users<2) { return; }
 3822:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3823:             'course'       => $env{'request.course.id'},
 3824:             'sections'     => '"all"',
 3825:             'num_students' => $users,
 3826:             'part'         => $part,
 3827:             'symb'         => $symb,
 3828:             'mean_tries'   => $av_attempts,
 3829:             'deg_of_diff'  => $degdiff});
 3830:     foreach my $key (keys(%dynstore)) {
 3831:         $accesshash{$key}=$dynstore{$key};
 3832:     }
 3833: }
 3834:   
 3835: sub userrolelog {
 3836:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3837:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3838:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3839:        $userrolehash
 3840:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3841:                     =$tend.':'.$tstart;
 3842:     }
 3843:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3844:        $userrolehash
 3845:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3846:                     =$tend.':'.$tstart;
 3847:     }
 3848:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3849:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3850:        $domainrolehash
 3851:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3852:                     = $tend.':'.$tstart;
 3853:     }
 3854: }
 3855: 
 3856: sub courserolelog {
 3857:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3858:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3859:         my $cdom = $1;
 3860:         my $cnum = $2;
 3861:         my $sec = $3;
 3862:         my $namespace = 'rolelog';
 3863:         my %storehash = (
 3864:                            role    => $trole,
 3865:                            start   => $tstart,
 3866:                            end     => $tend,
 3867:                            selfenroll => $selfenroll,
 3868:                            context    => $context,
 3869:                         );
 3870:         if ($trole eq 'gr') {
 3871:             $namespace = 'groupslog';
 3872:             $storehash{'group'} = $sec;
 3873:         } else {
 3874:             $storehash{'section'} = $sec;
 3875:         }
 3876:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3877:                    $domain,$cnum,$cdom);
 3878:         if (($trole ne 'st') || ($sec ne '')) {
 3879:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3880:         }
 3881:     }
 3882:     return;
 3883: }
 3884: 
 3885: sub domainrolelog {
 3886:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3887:     if ($area =~ m{^/($match_domain)/$}) {
 3888:         my $cdom = $1;
 3889:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3890:         my $namespace = 'rolelog';
 3891:         my %storehash = (
 3892:                            role    => $trole,
 3893:                            start   => $tstart,
 3894:                            end     => $tend,
 3895:                            context => $context,
 3896:                         );
 3897:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3898:                    $domain,$domconfiguser,$cdom);
 3899:     }
 3900:     return;
 3901: 
 3902: }
 3903: 
 3904: sub coauthorrolelog {
 3905:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3906:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3907:         my $audom = $1;
 3908:         my $auname = $2;
 3909:         my $namespace = 'rolelog';
 3910:         my %storehash = (
 3911:                            role    => $trole,
 3912:                            start   => $tstart,
 3913:                            end     => $tend,
 3914:                            context => $context,
 3915:                         );
 3916:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3917:                    $domain,$auname,$audom);
 3918:     }
 3919:     return;
 3920: }
 3921: 
 3922: sub get_course_adv_roles {
 3923:     my ($cid,$codes) = @_;
 3924:     $cid=$env{'request.course.id'} unless (defined($cid));
 3925:     my %coursehash=&coursedescription($cid);
 3926:     my $crstype = &Apache::loncommon::course_type($cid);
 3927:     my %nothide=();
 3928:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3929:         if ($user !~ /:/) {
 3930: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3931:         } else {
 3932:             $nothide{$user}=1;
 3933:         }
 3934:     }
 3935:     my @possdoms = ($coursehash{'domain'});
 3936:     if ($coursehash{'checkforpriv'}) {
 3937:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3938:     }
 3939:     my %returnhash=();
 3940:     my %dumphash=
 3941:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3942:     my $now=time;
 3943:     my %privileged;
 3944:     foreach my $entry (keys(%dumphash)) {
 3945: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3946:         if (($tstart) && ($tstart<0)) { next; }
 3947:         if (($tend) && ($tend<$now)) { next; }
 3948:         if (($tstart) && ($now<$tstart)) { next; }
 3949:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3950: 	if ($username eq '' || $domain eq '') { next; }
 3951:         if ((&privileged($username,$domain,\@possdoms)) &&
 3952:             (!$nothide{$username.':'.$domain})) { next; }
 3953: 	if ($role eq 'cr') { next; }
 3954:         if ($codes) {
 3955:             if ($section) { $role .= ':'.$section; }
 3956:             if ($returnhash{$role}) {
 3957:                 $returnhash{$role}.=','.$username.':'.$domain;
 3958:             } else {
 3959:                 $returnhash{$role}=$username.':'.$domain;
 3960:             }
 3961:         } else {
 3962:             my $key=&plaintext($role,$crstype);
 3963:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3964:             if ($returnhash{$key}) {
 3965: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3966:             } else {
 3967:                 $returnhash{$key}=$username.':'.$domain;
 3968:             }
 3969:         }
 3970:     }
 3971:     return %returnhash;
 3972: }
 3973: 
 3974: sub get_my_roles {
 3975:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3976:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3977:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3978:     my (%dumphash,%nothide);
 3979:     if ($context eq 'userroles') {
 3980:         %dumphash = &dump('roles',$udom,$uname);
 3981:     } else {
 3982:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 3983:         if ($hidepriv) {
 3984:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3985:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3986:                 if ($user !~ /:/) {
 3987:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3988:                 } else {
 3989:                     $nothide{$user} = 1;
 3990:                 }
 3991:             }
 3992:         }
 3993:     }
 3994:     my %returnhash=();
 3995:     my $now=time;
 3996:     my %privileged;
 3997:     foreach my $entry (keys(%dumphash)) {
 3998:         my ($role,$tend,$tstart);
 3999:         if ($context eq 'userroles') {
 4000:             next if ($entry =~ /^rolesdef/);
 4001: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4002:         } else {
 4003:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4004:         }
 4005:         if (($tstart) && ($tstart<0)) { next; }
 4006:         my $status = 'active';
 4007:         if (($tend) && ($tend<=$now)) {
 4008:             $status = 'previous';
 4009:         } 
 4010:         if (($tstart) && ($now<$tstart)) {
 4011:             $status = 'future';
 4012:         }
 4013:         if (ref($types) eq 'ARRAY') {
 4014:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4015:                 next;
 4016:             } 
 4017:         } else {
 4018:             if ($status ne 'active') {
 4019:                 next;
 4020:             }
 4021:         }
 4022:         my ($rolecode,$username,$domain,$section,$area);
 4023:         if ($context eq 'userroles') {
 4024:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4025:             (undef,$domain,$username,$section) = split(/\//,$area);
 4026:         } else {
 4027:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4028:         }
 4029:         if (ref($roledoms) eq 'ARRAY') {
 4030:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4031:                 next;
 4032:             }
 4033:         }
 4034:         if (ref($roles) eq 'ARRAY') {
 4035:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4036:                 if ($role =~ /^cr\//) {
 4037:                     if (!grep(/^cr$/,@{$roles})) {
 4038:                         next;
 4039:                     }
 4040:                 } elsif ($role =~ /^gr\//) {
 4041:                     if (!grep(/^gr$/,@{$roles})) {
 4042:                         next;
 4043:                     }
 4044:                 } else {
 4045:                     next;
 4046:                 }
 4047:             }
 4048:         }
 4049:         if ($hidepriv) {
 4050:             my @privroles = ('dc','su');
 4051:             if ($context eq 'userroles') {
 4052:                 next if (grep(/^\Q$role\E$/,@privroles));
 4053:             } else {
 4054:                 my $possdoms = [$domain];
 4055:                 if (ref($roledoms) eq 'ARRAY') {
 4056:                    push(@{$possdoms},@{$roledoms}); 
 4057:                 }
 4058:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4059:                     if (!$nothide{$username.':'.$domain}) {
 4060:                         next;
 4061:                     }
 4062:                 }
 4063:             }
 4064:         }
 4065:         if ($withsec) {
 4066:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4067:                 $tstart.':'.$tend;
 4068:         } else {
 4069:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4070:         }
 4071:     }
 4072:     return %returnhash;
 4073: }
 4074: 
 4075: # ----------------------------------------------------- Frontpage Announcements
 4076: #
 4077: #
 4078: 
 4079: sub postannounce {
 4080:     my ($server,$text)=@_;
 4081:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4082:     unless ($text=~/\w/) { $text=''; }
 4083:     return &reply('setannounce:'.&escape($text),$server);
 4084: }
 4085: 
 4086: sub getannounce {
 4087: 
 4088:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4089: 	my $announcement='';
 4090: 	while (my $line = <$fh>) { $announcement .= $line; }
 4091: 	close($fh);
 4092: 	if ($announcement=~/\w/) { 
 4093: 	    return 
 4094:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4095:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4096: 	} else {
 4097: 	    return '';
 4098: 	}
 4099:     } else {
 4100: 	return '';
 4101:     }
 4102: }
 4103: 
 4104: # ---------------------------------------------------------- Course ID routines
 4105: # Deal with domain's nohist_courseid.db files
 4106: #
 4107: 
 4108: sub courseidput {
 4109:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4110:     return unless (ref($storehash) eq 'HASH');
 4111:     my $outcome;
 4112:     if ($caller eq 'timeonly') {
 4113:         my $cids = '';
 4114:         foreach my $item (keys(%$storehash)) {
 4115:             $cids.=&escape($item).'&';
 4116:         }
 4117:         $cids=~s/\&$//;
 4118:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4119:                           $coursehome);       
 4120:     } else {
 4121:         my $items = '';
 4122:         foreach my $item (keys(%$storehash)) {
 4123:             $items.= &escape($item).'='.
 4124:                      &freeze_escape($$storehash{$item}).'&';
 4125:         }
 4126:         $items=~s/\&$//;
 4127:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4128:                           $coursehome);
 4129:     }
 4130:     if ($outcome eq 'unknown_cmd') {
 4131:         my $what;
 4132:         foreach my $cid (keys(%$storehash)) {
 4133:             $what .= &escape($cid).'=';
 4134:             foreach my $item ('description','inst_code','owner','type') {
 4135:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4136:             }
 4137:             $what =~ s/\:$/&/;
 4138:         }
 4139:         $what =~ s/\&$//;  
 4140:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4141:     } else {
 4142:         return $outcome;
 4143:     }
 4144: }
 4145: 
 4146: sub courseiddump {
 4147:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4148:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4149:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4150:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4151:     my $as_hash = 1;
 4152:     my %returnhash;
 4153:     if (!$domfilter) { $domfilter=''; }
 4154:     my %libserv = &all_library();
 4155:     foreach my $tryserver (keys(%libserv)) {
 4156:         if ( (  $hostidflag == 1 
 4157: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4158: 	     || (!defined($hostidflag)) ) {
 4159: 
 4160: 	    if (($domfilter eq '') ||
 4161: 		(&host_domain($tryserver) eq $domfilter)) {
 4162:                 my $rep;
 4163:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4164:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4165:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4166:                                 &escape($descfilter), &escape($instcodefilter), 
 4167:                                 &escape($ownerfilter), &escape($coursefilter),
 4168:                                 &escape($typefilter), &escape($regexp_ok), 
 4169:                                 $as_hash, &escape($selfenrollonly), 
 4170:                                 &escape($catfilter), $showhidden, $caller, 
 4171:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4172:                                 &escape($createdbefore), &escape($createdafter), 
 4173:                                 &escape($creationcontext), $domcloner)));
 4174:                 } else {
 4175:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4176:                              $sincefilter.':'.&escape($descfilter).':'.
 4177:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4178:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4179:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4180:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4181:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4182:                              &escape($cc_clone).':'.$cloneonly.':'.
 4183:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4184:                              &escape($creationcontext).':'.$domcloner,
 4185:                              $tryserver);
 4186:                 }
 4187:                      
 4188:                 my @pairs=split(/\&/,$rep);
 4189:                 foreach my $item (@pairs) {
 4190:                     my ($key,$value)=split(/\=/,$item,2);
 4191:                     $key = &unescape($key);
 4192:                     next if ($key =~ /^error: 2 /);
 4193:                     my $result = &thaw_unescape($value);
 4194:                     if (ref($result) eq 'HASH') {
 4195:                         $returnhash{$key}=$result;
 4196:                     } else {
 4197:                         my @responses = split(/:/,$value);
 4198:                         my @items = ('description','inst_code','owner','type');
 4199:                         for (my $i=0; $i<@responses; $i++) {
 4200:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4201:                         }
 4202:                     }
 4203:                 }
 4204:             }
 4205:         }
 4206:     }
 4207:     return %returnhash;
 4208: }
 4209: 
 4210: sub courselastaccess {
 4211:     my ($cdom,$cnum,$hostidref) = @_;
 4212:     my %returnhash;
 4213:     if ($cdom && $cnum) {
 4214:         my $chome = &homeserver($cnum,$cdom);
 4215:         if ($chome ne 'no_host') {
 4216:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4217:             &extract_lastaccess(\%returnhash,$rep);
 4218:         }
 4219:     } else {
 4220:         if (!$cdom) { $cdom=''; }
 4221:         my %libserv = &all_library();
 4222:         foreach my $tryserver (keys(%libserv)) {
 4223:             if (ref($hostidref) eq 'ARRAY') {
 4224:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4225:             } 
 4226:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4227:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4228:                 &extract_lastaccess(\%returnhash,$rep);
 4229:             }
 4230:         }
 4231:     }
 4232:     return %returnhash;
 4233: }
 4234: 
 4235: sub extract_lastaccess {
 4236:     my ($returnhash,$rep) = @_;
 4237:     if (ref($returnhash) eq 'HASH') {
 4238:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4239:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4240:                  $rep eq '') {
 4241:             my @pairs=split(/\&/,$rep);
 4242:             foreach my $item (@pairs) {
 4243:                 my ($key,$value)=split(/\=/,$item,2);
 4244:                 $key = &unescape($key);
 4245:                 next if ($key =~ /^error: 2 /);
 4246:                 $returnhash->{$key} = &thaw_unescape($value);
 4247:             }
 4248:         }
 4249:     }
 4250:     return;
 4251: }
 4252: 
 4253: # ---------------------------------------------------------- DC e-mail
 4254: 
 4255: sub dcmailput {
 4256:     my ($domain,$msgid,$message,$server)=@_;
 4257:     my $status = &Apache::lonnet::critical(
 4258:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4259:        &escape($message),$server);
 4260:     return $status;
 4261: }
 4262: 
 4263: sub dcmaildump {
 4264:     my ($dom,$startdate,$enddate,$senders) = @_;
 4265:     my %returnhash=();
 4266: 
 4267:     if (defined(&domain($dom,'primary'))) {
 4268:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4269:                                                          &escape($enddate).':';
 4270: 	my @esc_senders=map { &escape($_)} @$senders;
 4271: 	$cmd.=&escape(join('&',@esc_senders));
 4272: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4273:             my ($key,$value) = split(/\=/,$line,2);
 4274:             if (($key) && ($value)) {
 4275:                 $returnhash{&unescape($key)} = &unescape($value);
 4276:             }
 4277:         }
 4278:     }
 4279:     return %returnhash;
 4280: }
 4281: # ---------------------------------------------------------- Domain roles
 4282: 
 4283: sub get_domain_roles {
 4284:     my ($dom,$roles,$startdate,$enddate)=@_;
 4285:     if ((!defined($startdate)) || ($startdate eq '')) {
 4286:         $startdate = '.';
 4287:     }
 4288:     if ((!defined($enddate)) || ($enddate eq '')) {
 4289:         $enddate = '.';
 4290:     }
 4291:     my $rolelist;
 4292:     if (ref($roles) eq 'ARRAY') {
 4293:         $rolelist = join('&',@{$roles});
 4294:     }
 4295:     my %personnel = ();
 4296: 
 4297:     my %servers = &get_servers($dom,'library');
 4298:     foreach my $tryserver (keys(%servers)) {
 4299: 	%{$personnel{$tryserver}}=();
 4300: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4301: 					    &escape($startdate).':'.
 4302: 					    &escape($enddate).':'.
 4303: 					    &escape($rolelist), $tryserver))) {
 4304: 	    my ($key,$value) = split(/\=/,$line,2);
 4305: 	    if (($key) && ($value)) {
 4306: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4307: 	    }
 4308: 	}
 4309:     }
 4310:     return %personnel;
 4311: }
 4312: 
 4313: # ----------------------------------------------------------- Interval timing 
 4314: 
 4315: {
 4316: # Caches needed for speedup of navmaps
 4317: # We don't want to cache this for very long at all (5 seconds at most)
 4318: # 
 4319: # The user for whom we cache
 4320: my $cachedkey='';
 4321: # The cached times for this user
 4322: my %cachedtimes=();
 4323: # When this was last done
 4324: my $cachedtime=();
 4325: 
 4326: sub load_all_first_access {
 4327:     my ($uname,$udom)=@_;
 4328:     if (($cachedkey eq $uname.':'.$udom) &&
 4329:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4330:         return;
 4331:     }
 4332:     $cachedtime=time;
 4333:     $cachedkey=$uname.':'.$udom;
 4334:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4335: }
 4336: 
 4337: sub get_first_access {
 4338:     my ($type,$argsymb,$argmap)=@_;
 4339:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4340:     if ($argsymb) { $symb=$argsymb; }
 4341:     my ($map,$id,$res)=&decode_symb($symb);
 4342:     if ($argmap) { $map = $argmap; }
 4343:     if ($type eq 'course') {
 4344: 	$res='course';
 4345:     } elsif ($type eq 'map') {
 4346: 	$res=&symbread($map);
 4347:     } else {
 4348: 	$res=$symb;
 4349:     }
 4350:     &load_all_first_access($uname,$udom);
 4351:     return $cachedtimes{"$courseid\0$res"};
 4352: }
 4353: 
 4354: sub set_first_access {
 4355:     my ($type,$interval)=@_;
 4356:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4357:     my ($map,$id,$res)=&decode_symb($symb);
 4358:     if ($type eq 'course') {
 4359: 	$res='course';
 4360:     } elsif ($type eq 'map') {
 4361: 	$res=&symbread($map);
 4362:     } else {
 4363: 	$res=$symb;
 4364:     }
 4365:     $cachedkey='';
 4366:     my $firstaccess=&get_first_access($type,$symb,$map);
 4367:     if (!$firstaccess) {
 4368:         my $start = time;
 4369: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4370:                           $udom,$uname);
 4371:         if ($putres eq 'ok') {
 4372:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4373:                  $udom,$uname); 
 4374:             &appenv(
 4375:                      {
 4376:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4377:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4378:                      }
 4379:                   );
 4380:         }
 4381:         return $putres;
 4382:     }
 4383:     return 'already_set';
 4384: }
 4385: }
 4386: # --------------------------------------------- Set Expire Date for Spreadsheet
 4387: 
 4388: sub expirespread {
 4389:     my ($uname,$udom,$stype,$usymb)=@_;
 4390:     my $cid=$env{'request.course.id'}; 
 4391:     if ($cid) {
 4392:        my $now=time;
 4393:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4394:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4395:                             $env{'course.'.$cid.'.num'}.
 4396: 	        	    ':nohist_expirationdates:'.
 4397:                             &escape($key).'='.$now,
 4398:                             $env{'course.'.$cid.'.home'})
 4399:     }
 4400:     return 'ok';
 4401: }
 4402: 
 4403: # ----------------------------------------------------- Devalidate Spreadsheets
 4404: 
 4405: sub devalidate {
 4406:     my ($symb,$uname,$udom)=@_;
 4407:     my $cid=$env{'request.course.id'}; 
 4408:     if ($cid) {
 4409:         # delete the stored spreadsheets for
 4410:         # - the student level sheet of this user in course's homespace
 4411:         # - the assessment level sheet for this resource 
 4412:         #   for this user in user's homespace
 4413: 	# - current conditional state info
 4414: 	my $key=$uname.':'.$udom.':';
 4415:         my $status=
 4416: 	    &del('nohist_calculatedsheets',
 4417: 		 [$key.'studentcalc:'],
 4418: 		 $env{'course.'.$cid.'.domain'},
 4419: 		 $env{'course.'.$cid.'.num'})
 4420: 		.' '.
 4421: 	    &del('nohist_calculatedsheets_'.$cid,
 4422: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4423:         unless ($status eq 'ok ok') {
 4424:            &logthis('Could not devalidate spreadsheet '.
 4425:                     $uname.' at '.$udom.' for '.
 4426: 		    $symb.': '.$status);
 4427:         }
 4428: 	&delenv('user.state.'.$cid);
 4429:     }
 4430: }
 4431: 
 4432: sub get_scalar {
 4433:     my ($string,$end) = @_;
 4434:     my $value;
 4435:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4436: 	$value = $1;
 4437:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4438: 	$value = $1;
 4439:     }
 4440:     return &unescape($value);
 4441: }
 4442: 
 4443: sub array2str {
 4444:   my (@array) = @_;
 4445:   my $result=&arrayref2str(\@array);
 4446:   $result=~s/^__ARRAY_REF__//;
 4447:   $result=~s/__END_ARRAY_REF__$//;
 4448:   return $result;
 4449: }
 4450: 
 4451: sub arrayref2str {
 4452:   my ($arrayref) = @_;
 4453:   my $result='__ARRAY_REF__';
 4454:   foreach my $elem (@$arrayref) {
 4455:     if(ref($elem) eq 'ARRAY') {
 4456:       $result.=&arrayref2str($elem).'&';
 4457:     } elsif(ref($elem) eq 'HASH') {
 4458:       $result.=&hashref2str($elem).'&';
 4459:     } elsif(ref($elem)) {
 4460:       #print("Got a ref of ".(ref($elem))." skipping.");
 4461:     } else {
 4462:       $result.=&escape($elem).'&';
 4463:     }
 4464:   }
 4465:   $result=~s/\&$//;
 4466:   $result .= '__END_ARRAY_REF__';
 4467:   return $result;
 4468: }
 4469: 
 4470: sub hash2str {
 4471:   my (%hash) = @_;
 4472:   my $result=&hashref2str(\%hash);
 4473:   $result=~s/^__HASH_REF__//;
 4474:   $result=~s/__END_HASH_REF__$//;
 4475:   return $result;
 4476: }
 4477: 
 4478: sub hashref2str {
 4479:   my ($hashref)=@_;
 4480:   my $result='__HASH_REF__';
 4481:   foreach my $key (sort(keys(%$hashref))) {
 4482:     if (ref($key) eq 'ARRAY') {
 4483:       $result.=&arrayref2str($key).'=';
 4484:     } elsif (ref($key) eq 'HASH') {
 4485:       $result.=&hashref2str($key).'=';
 4486:     } elsif (ref($key)) {
 4487:       $result.='=';
 4488:       #print("Got a ref of ".(ref($key))." skipping.");
 4489:     } else {
 4490: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4491:     }
 4492: 
 4493:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4494:       $result.=&arrayref2str($hashref->{$key}).'&';
 4495:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4496:       $result.=&hashref2str($hashref->{$key}).'&';
 4497:     } elsif(ref($hashref->{$key})) {
 4498:        $result.='&';
 4499:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4500:     } else {
 4501:       $result.=&escape($hashref->{$key}).'&';
 4502:     }
 4503:   }
 4504:   $result=~s/\&$//;
 4505:   $result .= '__END_HASH_REF__';
 4506:   return $result;
 4507: }
 4508: 
 4509: sub str2hash {
 4510:     my ($string)=@_;
 4511:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4512:     return %$hash;
 4513: }
 4514: 
 4515: sub str2hashref {
 4516:   my ($string) = @_;
 4517: 
 4518:   my %hash;
 4519: 
 4520:   if($string !~ /^__HASH_REF__/) {
 4521:       if (! ($string eq '' || !defined($string))) {
 4522: 	  $hash{'error'}='Not hash reference';
 4523:       }
 4524:       return (\%hash, $string);
 4525:   }
 4526: 
 4527:   $string =~ s/^__HASH_REF__//;
 4528: 
 4529:   while($string !~ /^__END_HASH_REF__/) {
 4530:       #key
 4531:       my $key='';
 4532:       if($string =~ /^__HASH_REF__/) {
 4533:           ($key, $string)=&str2hashref($string);
 4534:           if(defined($key->{'error'})) {
 4535:               $hash{'error'}='Bad data';
 4536:               return (\%hash, $string);
 4537:           }
 4538:       } elsif($string =~ /^__ARRAY_REF__/) {
 4539:           ($key, $string)=&str2arrayref($string);
 4540:           if($key->[0] eq 'Array reference error') {
 4541:               $hash{'error'}='Bad data';
 4542:               return (\%hash, $string);
 4543:           }
 4544:       } else {
 4545:           $string =~ s/^(.*?)=//;
 4546: 	  $key=&unescape($1);
 4547:       }
 4548:       $string =~ s/^=//;
 4549: 
 4550:       #value
 4551:       my $value='';
 4552:       if($string =~ /^__HASH_REF__/) {
 4553:           ($value, $string)=&str2hashref($string);
 4554:           if(defined($value->{'error'})) {
 4555:               $hash{'error'}='Bad data';
 4556:               return (\%hash, $string);
 4557:           }
 4558:       } elsif($string =~ /^__ARRAY_REF__/) {
 4559:           ($value, $string)=&str2arrayref($string);
 4560:           if($value->[0] eq 'Array reference error') {
 4561:               $hash{'error'}='Bad data';
 4562:               return (\%hash, $string);
 4563:           }
 4564:       } else {
 4565: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4566:       }
 4567:       $string =~ s/^&//;
 4568: 
 4569:       $hash{$key}=$value;
 4570:   }
 4571: 
 4572:   $string =~ s/^__END_HASH_REF__//;
 4573: 
 4574:   return (\%hash, $string);
 4575: }
 4576: 
 4577: sub str2array {
 4578:     my ($string)=@_;
 4579:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4580:     return @$array;
 4581: }
 4582: 
 4583: sub str2arrayref {
 4584:   my ($string) = @_;
 4585:   my @array;
 4586: 
 4587:   if($string !~ /^__ARRAY_REF__/) {
 4588:       if (! ($string eq '' || !defined($string))) {
 4589: 	  $array[0]='Array reference error';
 4590:       }
 4591:       return (\@array, $string);
 4592:   }
 4593: 
 4594:   $string =~ s/^__ARRAY_REF__//;
 4595: 
 4596:   while($string !~ /^__END_ARRAY_REF__/) {
 4597:       my $value='';
 4598:       if($string =~ /^__HASH_REF__/) {
 4599:           ($value, $string)=&str2hashref($string);
 4600:           if(defined($value->{'error'})) {
 4601:               $array[0] ='Array reference error';
 4602:               return (\@array, $string);
 4603:           }
 4604:       } elsif($string =~ /^__ARRAY_REF__/) {
 4605:           ($value, $string)=&str2arrayref($string);
 4606:           if($value->[0] eq 'Array reference error') {
 4607:               $array[0] ='Array reference error';
 4608:               return (\@array, $string);
 4609:           }
 4610:       } else {
 4611: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4612:       }
 4613:       $string =~ s/^&//;
 4614: 
 4615:       push(@array, $value);
 4616:   }
 4617: 
 4618:   $string =~ s/^__END_ARRAY_REF__//;
 4619: 
 4620:   return (\@array, $string);
 4621: }
 4622: 
 4623: # -------------------------------------------------------------------Temp Store
 4624: 
 4625: sub tmpreset {
 4626:   my ($symb,$namespace,$domain,$stuname) = @_;
 4627:   if (!$symb) {
 4628:     $symb=&symbread();
 4629:     if (!$symb) { $symb= $env{'request.url'}; }
 4630:   }
 4631:   $symb=escape($symb);
 4632: 
 4633:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4634:   $namespace=~s/\//\_/g;
 4635:   $namespace=~s/\W//g;
 4636: 
 4637:   if (!$domain) { $domain=$env{'user.domain'}; }
 4638:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4639:   if ($domain eq 'public' && $stuname eq 'public') {
 4640:       $stuname=$ENV{'REMOTE_ADDR'};
 4641:   }
 4642:   my $path=LONCAPA::tempdir();
 4643:   my %hash;
 4644:   if (tie(%hash,'GDBM_File',
 4645: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4646: 	  &GDBM_WRCREAT(),0640)) {
 4647:     foreach my $key (keys(%hash)) {
 4648:       if ($key=~ /:$symb/) {
 4649: 	delete($hash{$key});
 4650:       }
 4651:     }
 4652:   }
 4653: }
 4654: 
 4655: sub tmpstore {
 4656:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4657: 
 4658:   if (!$symb) {
 4659:     $symb=&symbread();
 4660:     if (!$symb) { $symb= $env{'request.url'}; }
 4661:   }
 4662:   $symb=escape($symb);
 4663: 
 4664:   if (!$namespace) {
 4665:     # I don't think we would ever want to store this for a course.
 4666:     # it seems this will only be used if we don't have a course.
 4667:     #$namespace=$env{'request.course.id'};
 4668:     #if (!$namespace) {
 4669:       $namespace=$env{'request.state'};
 4670:     #}
 4671:   }
 4672:   $namespace=~s/\//\_/g;
 4673:   $namespace=~s/\W//g;
 4674:   if (!$domain) { $domain=$env{'user.domain'}; }
 4675:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4676:   if ($domain eq 'public' && $stuname eq 'public') {
 4677:       $stuname=$ENV{'REMOTE_ADDR'};
 4678:   }
 4679:   my $now=time;
 4680:   my %hash;
 4681:   my $path=LONCAPA::tempdir();
 4682:   if (tie(%hash,'GDBM_File',
 4683: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4684: 	  &GDBM_WRCREAT(),0640)) {
 4685:     $hash{"version:$symb"}++;
 4686:     my $version=$hash{"version:$symb"};
 4687:     my $allkeys=''; 
 4688:     foreach my $key (keys(%$storehash)) {
 4689:       $allkeys.=$key.':';
 4690:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4691:     }
 4692:     $hash{"$version:$symb:timestamp"}=$now;
 4693:     $allkeys.='timestamp';
 4694:     $hash{"$version:keys:$symb"}=$allkeys;
 4695:     if (untie(%hash)) {
 4696:       return 'ok';
 4697:     } else {
 4698:       return "error:$!";
 4699:     }
 4700:   } else {
 4701:     return "error:$!";
 4702:   }
 4703: }
 4704: 
 4705: # -----------------------------------------------------------------Temp Restore
 4706: 
 4707: sub tmprestore {
 4708:   my ($symb,$namespace,$domain,$stuname) = @_;
 4709: 
 4710:   if (!$symb) {
 4711:     $symb=&symbread();
 4712:     if (!$symb) { $symb= $env{'request.url'}; }
 4713:   }
 4714:   $symb=escape($symb);
 4715: 
 4716:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4717: 
 4718:   if (!$domain) { $domain=$env{'user.domain'}; }
 4719:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4720:   if ($domain eq 'public' && $stuname eq 'public') {
 4721:       $stuname=$ENV{'REMOTE_ADDR'};
 4722:   }
 4723:   my %returnhash;
 4724:   $namespace=~s/\//\_/g;
 4725:   $namespace=~s/\W//g;
 4726:   my %hash;
 4727:   my $path=LONCAPA::tempdir();
 4728:   if (tie(%hash,'GDBM_File',
 4729: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4730: 	  &GDBM_READER(),0640)) {
 4731:     my $version=$hash{"version:$symb"};
 4732:     $returnhash{'version'}=$version;
 4733:     my $scope;
 4734:     for ($scope=1;$scope<=$version;$scope++) {
 4735:       my $vkeys=$hash{"$scope:keys:$symb"};
 4736:       my @keys=split(/:/,$vkeys);
 4737:       my $key;
 4738:       $returnhash{"$scope:keys"}=$vkeys;
 4739:       foreach $key (@keys) {
 4740: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4741: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4742:       }
 4743:     }
 4744:     if (!(untie(%hash))) {
 4745:       return "error:$!";
 4746:     }
 4747:   } else {
 4748:     return "error:$!";
 4749:   }
 4750:   return %returnhash;
 4751: }
 4752: 
 4753: # ----------------------------------------------------------------------- Store
 4754: 
 4755: sub store {
 4756:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4757:     my $home='';
 4758: 
 4759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4760: 
 4761:     $symb=&symbclean($symb);
 4762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4763: 
 4764:     if (!$domain) { $domain=$env{'user.domain'}; }
 4765:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4766: 
 4767:     &devalidate($symb,$stuname,$domain);
 4768: 
 4769:     $symb=escape($symb);
 4770:     if (!$namespace) { 
 4771:        unless ($namespace=$env{'request.course.id'}) { 
 4772:           return ''; 
 4773:        } 
 4774:     }
 4775:     if (!$home) { $home=$env{'user.home'}; }
 4776: 
 4777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4778:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4779: 
 4780:     my $namevalue='';
 4781:     foreach my $key (keys(%$storehash)) {
 4782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4783:     }
 4784:     $namevalue=~s/\&$//;
 4785:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4786:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4787: }
 4788: 
 4789: # -------------------------------------------------------------- Critical Store
 4790: 
 4791: sub cstore {
 4792:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4793:     my $home='';
 4794: 
 4795:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4796: 
 4797:     $symb=&symbclean($symb);
 4798:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4799: 
 4800:     if (!$domain) { $domain=$env{'user.domain'}; }
 4801:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4802: 
 4803:     &devalidate($symb,$stuname,$domain);
 4804: 
 4805:     $symb=escape($symb);
 4806:     if (!$namespace) { 
 4807:        unless ($namespace=$env{'request.course.id'}) { 
 4808:           return ''; 
 4809:        } 
 4810:     }
 4811:     if (!$home) { $home=$env{'user.home'}; }
 4812: 
 4813:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4814:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4815: 
 4816:     my $namevalue='';
 4817:     foreach my $key (keys(%$storehash)) {
 4818:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4819:     }
 4820:     $namevalue=~s/\&$//;
 4821:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4822:     return critical
 4823:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4824: }
 4825: 
 4826: # --------------------------------------------------------------------- Restore
 4827: 
 4828: sub restore {
 4829:     my ($symb,$namespace,$domain,$stuname) = @_;
 4830:     my $home='';
 4831: 
 4832:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4833: 
 4834:     if (!$symb) {
 4835:         return if ($namespace eq 'courserequests');
 4836:         unless ($symb=escape(&symbread())) { return ''; }
 4837:     } else {
 4838:         unless ($namespace eq 'courserequests') {
 4839:             $symb=&escape(&symbclean($symb));
 4840:         }
 4841:     }
 4842:     if (!$namespace) { 
 4843:        unless ($namespace=$env{'request.course.id'}) { 
 4844:           return ''; 
 4845:        } 
 4846:     }
 4847:     if (!$domain) { $domain=$env{'user.domain'}; }
 4848:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4849:     if (!$home) { $home=$env{'user.home'}; }
 4850:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4851: 
 4852:     my %returnhash=();
 4853:     foreach my $line (split(/\&/,$answer)) {
 4854: 	my ($name,$value)=split(/\=/,$line);
 4855:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4856:     }
 4857:     my $version;
 4858:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4859:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4860:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4861:        }
 4862:     }
 4863:     return %returnhash;
 4864: }
 4865: 
 4866: # ---------------------------------------------------------- Course Description
 4867: #
 4868: #  
 4869: 
 4870: sub coursedescription {
 4871:     my ($courseid,$args)=@_;
 4872:     $courseid=~s/^\///;
 4873:     $courseid=~s/\_/\//g;
 4874:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4875:     my $chome=&homeserver($cnum,$cdomain);
 4876:     my $normalid=$cdomain.'_'.$cnum;
 4877:     # need to always cache even if we get errors otherwise we keep 
 4878:     # trying and trying and trying to get the course description.
 4879:     my %envhash=();
 4880:     my %returnhash=();
 4881:     
 4882:     my $expiretime=600;
 4883:     if ($env{'request.course.id'} eq $normalid) {
 4884: 	$expiretime=120;
 4885:     }
 4886: 
 4887:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4888:     if (!$args->{'freshen_cache'}
 4889: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4890: 	foreach my $key (keys(%env)) {
 4891: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4892: 	    my ($setting) = $1;
 4893: 	    $returnhash{$setting} = $env{$key};
 4894: 	}
 4895: 	return %returnhash;
 4896:     }
 4897: 
 4898:     # get the data again
 4899: 
 4900:     if (!$args->{'one_time'}) {
 4901: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4902:     }
 4903: 
 4904:     if ($chome ne 'no_host') {
 4905:        %returnhash=&dump('environment',$cdomain,$cnum);
 4906:        if (!exists($returnhash{'con_lost'})) {
 4907: 	   my $username = $env{'user.name'}; # Defult username
 4908: 	   if(defined $args->{'user'}) {
 4909: 	       $username = $args->{'user'};
 4910: 	   }
 4911:            $returnhash{'home'}= $chome;
 4912: 	   $returnhash{'domain'} = $cdomain;
 4913: 	   $returnhash{'num'} = $cnum;
 4914:            if (!defined($returnhash{'type'})) {
 4915:                $returnhash{'type'} = 'Course';
 4916:            }
 4917:            while (my ($name,$value) = each %returnhash) {
 4918:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4919:            }
 4920:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4921:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4922: 	       $username.'_'.$cdomain.'_'.$cnum;
 4923:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4924:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4925:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4926:        }
 4927:     }
 4928:     if (!$args->{'one_time'}) {
 4929: 	&appenv(\%envhash);
 4930:     }
 4931:     return %returnhash;
 4932: }
 4933: 
 4934: sub update_released_required {
 4935:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4936:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4937:         $cid = $env{'request.course.id'};
 4938:         $cdom = $env{'course.'.$cid.'.domain'};
 4939:         $cnum = $env{'course.'.$cid.'.num'};
 4940:         $chome = $env{'course.'.$cid.'.home'};
 4941:     }
 4942:     if ($needsrelease) {
 4943:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4944:         my $needsupdate;
 4945:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4946:             $needsupdate = 1;
 4947:         } else {
 4948:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4949:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4950:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4951:                 $needsupdate = 1;
 4952:             }
 4953:         }
 4954:         if ($needsupdate) {
 4955:             my %needshash = (
 4956:                              'internal.releaserequired' => $needsrelease,
 4957:                             );
 4958:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4959:             if ($putresult eq 'ok') {
 4960:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4961:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4962:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4963:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4964:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4965:                 }
 4966:             }
 4967:         }
 4968:     }
 4969:     return;
 4970: }
 4971: 
 4972: # -------------------------------------------------See if a user is privileged
 4973: 
 4974: sub privileged {
 4975:     my ($username,$domain,$possdomains,$possroles)=@_;
 4976:     my $now = time;
 4977:     my $roles;
 4978:     if (ref($possroles) eq 'ARRAY') {
 4979:         $roles = $possroles; 
 4980:     } else {
 4981:         $roles = ['dc','su'];
 4982:     }
 4983:     if (ref($possdomains) eq 'ARRAY') {
 4984:         my %privileged = &privileged_by_domain($possdomains,$roles);
 4985:         foreach my $dom (@{$possdomains}) {
 4986:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 4987:                 (ref($privileged{$dom}) eq 'HASH')) {
 4988:                 foreach my $role (@{$roles}) {
 4989:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 4990:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 4991:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 4992:                             return 1 unless (($end && $end < $now) ||
 4993:                                              ($start && $start > $now));
 4994:                         }
 4995:                     }
 4996:                 }
 4997:             }
 4998:         }
 4999:     } else {
 5000:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5001:         my $now = time;
 5002: 
 5003:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5004:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5005:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5006:                 return 1 unless ($tend && $tend < $now) 
 5007:                         or ($tstart && $tstart > $now);
 5008:             }
 5009:         }
 5010:     }
 5011:     return 0;
 5012: }
 5013: 
 5014: sub privileged_by_domain {
 5015:     my ($domains,$roles) = @_;
 5016:     my %privileged = ();
 5017:     my $cachetime = 60*60*24;
 5018:     my $now = time;
 5019:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5020:         return %privileged;
 5021:     }
 5022:     foreach my $dom (@{$domains}) {
 5023:         next if (ref($privileged{$dom}) eq 'HASH');
 5024:         my $needroles;
 5025:         foreach my $role (@{$roles}) {
 5026:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5027:             if (defined($cached)) {
 5028:                 if (ref($result) eq 'HASH') {
 5029:                     $privileged{$dom}{$role} = $result;
 5030:                 }
 5031:             } else {
 5032:                 $needroles = 1;
 5033:             }
 5034:         }
 5035:         if ($needroles) {
 5036:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5037:             $privileged{$dom} = {};
 5038:             foreach my $server (keys(%dompersonnel)) {
 5039:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5040:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5041:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5042:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5043:                         next if ($end && $end < $now);
 5044:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5045:                             $dompersonnel{$server}{$item};
 5046:                     }
 5047:                 }
 5048:             }
 5049:             if (ref($privileged{$dom}) eq 'HASH') {
 5050:                 foreach my $role (@{$roles}) {
 5051:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5052:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5053:                     } else {
 5054:                         my %hash = ();
 5055:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5056:                     }
 5057:                 }
 5058:             }
 5059:         }
 5060:     }
 5061:     return %privileged;
 5062: }
 5063: 
 5064: # -------------------------------------------------------- Get user privileges
 5065: 
 5066: sub rolesinit {
 5067:     my ($domain, $username) = @_;
 5068:     my %userroles = ('user.login.time' => time);
 5069:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5070: 
 5071:     # firstaccess and timerinterval are related to timed maps/resources. 
 5072:     # also, blocking can be triggered by an activating timer
 5073:     # it's saved in the user's %env.
 5074:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5075:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5076:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5077:         %timerintchk, %timerintenv);
 5078: 
 5079:     foreach my $key (keys(%firstaccess)) {
 5080:         my ($cid, $rest) = split(/\0/, $key);
 5081:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5082:     }
 5083: 
 5084:     foreach my $key (keys(%timerinterval)) {
 5085:         my ($cid,$rest) = split(/\0/,$key);
 5086:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5087:     }
 5088: 
 5089:     my %allroles=();
 5090:     my %allgroups=();
 5091: 
 5092:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5093:         my $role = $rolesdump{$area};
 5094:         $area =~ s/\_\w\w$//;
 5095: 
 5096:         my ($trole, $tend, $tstart, $group_privs);
 5097: 
 5098:         if ($role =~ /^cr/) {
 5099:         # Custom role, defined by a user 
 5100:         # e.g., user.role.cr/msu/smith/mynewrole
 5101:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5102:                 $trole = $1;
 5103:                 ($tend, $tstart) = split('_', $2);
 5104:             } else {
 5105:                 $trole = $role;
 5106:             }
 5107:         } elsif ($role =~ m|^gr/|) {
 5108:         # Role of member in a group, defined within a course/community
 5109:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5110:             ($trole, $tend, $tstart) = split(/_/, $role);
 5111:             next if $tstart eq '-1';
 5112:             ($trole, $group_privs) = split(/\//, $trole);
 5113:             $group_privs = &unescape($group_privs);
 5114:         } else {
 5115:         # Just a normal role, defined in roles.tab
 5116:             ($trole, $tend, $tstart) = split(/_/,$role);
 5117:         }
 5118: 
 5119:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5120:                  $username);
 5121:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5122: 
 5123:         # role expired or not available yet?
 5124:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5125:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5126: 
 5127:         next if $area eq '' or $trole eq '';
 5128: 
 5129:         my $spec = "$trole.$area";
 5130:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5131: 
 5132:         if ($trole =~ /^cr\//) {
 5133:         # Custom role, defined by a user
 5134:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5135:         } elsif ($trole eq 'gr') {
 5136:         # Role of a member in a group, defined within a course/community
 5137:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5138:             next;
 5139:         } else {
 5140:         # Normal role, defined in roles.tab
 5141:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5142:         }
 5143: 
 5144:         my $cid = $tdomain.'_'.$trest;
 5145:         unless ($firstaccchk{$cid}) {
 5146:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5147:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5148:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5149:                         $coursetimerstarts{$cid}{$item}; 
 5150:                 }
 5151:             }
 5152:             $firstaccchk{$cid} = 1;
 5153:         }
 5154:         unless ($timerintchk{$cid}) {
 5155:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5156:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5157:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5158:                        $coursetimerintervals{$cid}{$item};
 5159:                 }
 5160:             }
 5161:             $timerintchk{$cid} = 1;
 5162:         }
 5163:     }
 5164: 
 5165:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5166:         \%allroles, \%allgroups);
 5167:     $env{'user.adv'} = $userroles{'user.adv'};
 5168: 
 5169:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5170: }
 5171: 
 5172: sub set_arearole {
 5173:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5174:     unless ($nolog) {
 5175: # log the associated role with the area
 5176:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5177:     }
 5178:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5179: }
 5180: 
 5181: sub custom_roleprivs {
 5182:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5183:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5184:     my $homsvr=homeserver($rauthor,$rdomain);
 5185:     if (&hostname($homsvr) ne '') {
 5186:         my ($rdummy,$roledef)=
 5187:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5188:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5189:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5190:             if (defined($syspriv)) {
 5191:                 if ($trest =~ /^$match_community$/) {
 5192:                     $syspriv =~ s/bre\&S//; 
 5193:                 }
 5194:                 $$allroles{'cm./'}.=':'.$syspriv;
 5195:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5196:             }
 5197:             if ($tdomain ne '') {
 5198:                 if (defined($dompriv)) {
 5199:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5200:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5201:                 }
 5202:                 if (($trest ne '') && (defined($coursepriv))) {
 5203:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5204:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5205:                 }
 5206:             }
 5207:         }
 5208:     }
 5209: }
 5210: 
 5211: sub group_roleprivs {
 5212:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5213:     my $access = 1;
 5214:     my $now = time;
 5215:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5216:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5217:     if ($access) {
 5218:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5219:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5220:     }
 5221: }
 5222: 
 5223: sub standard_roleprivs {
 5224:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5225:     if (defined($pr{$trole.':s'})) {
 5226:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5227:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5228:     }
 5229:     if ($tdomain ne '') {
 5230:         if (defined($pr{$trole.':d'})) {
 5231:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5232:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5233:         }
 5234:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5235:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5236:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5237:         }
 5238:     }
 5239: }
 5240: 
 5241: sub set_userprivs {
 5242:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5243:     my $author=0;
 5244:     my $adv=0;
 5245:     my %grouproles = ();
 5246:     if (keys(%{$allgroups}) > 0) {
 5247:         my @groupkeys; 
 5248:         foreach my $role (keys(%{$allroles})) {
 5249:             push(@groupkeys,$role);
 5250:         }
 5251:         if (ref($groups_roles) eq 'HASH') {
 5252:             foreach my $key (keys(%{$groups_roles})) {
 5253:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5254:                     push(@groupkeys,$key);
 5255:                 }
 5256:             }
 5257:         }
 5258:         if (@groupkeys > 0) {
 5259:             foreach my $role (@groupkeys) {
 5260:                 my ($trole,$area,$sec,$extendedarea);
 5261:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5262:                     $trole = $1;
 5263:                     $area = $2;
 5264:                     $sec = $3;
 5265:                     $extendedarea = $area.$sec;
 5266:                     if (exists($$allgroups{$area})) {
 5267:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5268:                             my $spec = $trole.'.'.$extendedarea;
 5269:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5270:                                                 $$allgroups{$area}{$group};
 5271:                         }
 5272:                     }
 5273:                 }
 5274:             }
 5275:         }
 5276:     }
 5277:     foreach my $group (keys(%grouproles)) {
 5278:         $$allroles{$group} = $grouproles{$group};
 5279:     }
 5280:     foreach my $role (keys(%{$allroles})) {
 5281:         my %thesepriv;
 5282:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5283:         foreach my $item (split(/:/,$$allroles{$role})) {
 5284:             if ($item ne '') {
 5285:                 my ($privilege,$restrictions)=split(/&/,$item);
 5286:                 if ($restrictions eq '') {
 5287:                     $thesepriv{$privilege}='F';
 5288:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5289:                     $thesepriv{$privilege}.=$restrictions;
 5290:                 }
 5291:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5292:             }
 5293:         }
 5294:         my $thesestr='';
 5295:         foreach my $priv (sort(keys(%thesepriv))) {
 5296: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5297: 	}
 5298:         $userroles->{'user.priv.'.$role} = $thesestr;
 5299:     }
 5300:     return ($author,$adv);
 5301: }
 5302: 
 5303: sub role_status {
 5304:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5305:     my @pwhere = ();
 5306:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5307:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5308:         unless (!defined($$role) || $$role eq '') {
 5309:             $$where=join('.',@pwhere);
 5310:             $$trolecode=$$role.'.'.$$where;
 5311:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5312:             $$tstatus='is';
 5313:             if ($$tstart && $$tstart>$update) {
 5314:                 $$tstatus='future';
 5315:                 if ($$tstart<$now) {
 5316:                     if ($$tstart && $$tstart>$refresh) {
 5317:                         if (($$where ne '') && ($$role ne '')) {
 5318:                             my (%allroles,%allgroups,$group_privs,
 5319:                                 %groups_roles,@rolecodes);
 5320:                             my %userroles = (
 5321:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5322:                             );
 5323:                             @rolecodes = ('cm'); 
 5324:                             my $spec=$$role.'.'.$$where;
 5325:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5326:                             if ($$role =~ /^cr\//) {
 5327:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5328:                                 push(@rolecodes,'cr');
 5329:                             } elsif ($$role eq 'gr') {
 5330:                                 push(@rolecodes,$$role);
 5331:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5332:                                                     $env{'user.name'});
 5333:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5334:                                 (undef,my $group_privs) = split(/\//,$trole);
 5335:                                 $group_privs = &unescape($group_privs);
 5336:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5337:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5338:                                 &get_groups_roles($tdomain,$trest,
 5339:                                                   \%course_roles,\@rolecodes,
 5340:                                                   \%groups_roles);
 5341:                             } else {
 5342:                                 push(@rolecodes,$$role);
 5343:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5344:                             }
 5345:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5346:                             &appenv(\%userroles,\@rolecodes);
 5347:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5348:                         }
 5349:                     }
 5350:                     $$tstatus = 'is';
 5351:                 }
 5352:             }
 5353:             if ($$tend) {
 5354:                 if ($$tend<$update) {
 5355:                     $$tstatus='expired';
 5356:                 } elsif ($$tend<$now) {
 5357:                     $$tstatus='will_not';
 5358:                 }
 5359:             }
 5360:         }
 5361:     }
 5362: }
 5363: 
 5364: sub get_groups_roles {
 5365:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5366:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5367:                   (ref($rolecodes) eq 'ARRAY') && 
 5368:                   (ref($groups_roles) eq 'HASH')); 
 5369:     if (keys(%{$cdom_courseroles}) > 0) {
 5370:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5371:         if ($cdom ne '' && $cnum ne '') {
 5372:             foreach my $key (keys(%{$cdom_courseroles})) {
 5373:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5374:                     my $crsrole = $1;
 5375:                     my $crssec = $2;
 5376:                     if ($crsrole =~ /^cr/) {
 5377:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5378:                             push(@{$rolecodes},'cr');
 5379:                         }
 5380:                     } else {
 5381:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5382:                             push(@{$rolecodes},$crsrole);
 5383:                         }
 5384:                     }
 5385:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5386:                     if ($crssec ne '') {
 5387:                         $rolekey .= "/$crssec";
 5388:                     }
 5389:                     $rolekey .= './';
 5390:                     $groups_roles->{$rolekey} = $rolecodes;
 5391:                 }
 5392:             }
 5393:         }
 5394:     }
 5395:     return;
 5396: }
 5397: 
 5398: sub delete_env_groupprivs {
 5399:     my ($where,$courseroles,$possroles) = @_;
 5400:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5401:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5402:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5403:         %{$courseroles->{$udom}} =
 5404:             &get_my_roles('','','userroles',['active'],
 5405:                           $possroles,[$udom],1);
 5406:     }
 5407:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5408:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5409:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5410:             my $area = '/'.$cdom.'/'.$cnum;
 5411:             my $privkey = "user.priv.$crsrole.$area";
 5412:             if ($crssec ne '') {
 5413:                 $privkey .= '/'.$crssec;
 5414:             }
 5415:             $privkey .= ".$area/$group";
 5416:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5417:         }
 5418:     }
 5419:     return;
 5420: }
 5421: 
 5422: sub check_adhoc_privs {
 5423:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5424:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5425:     my $setprivs;
 5426:     if ($env{$cckey}) {
 5427:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5428:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5429:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5430:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5431:             $setprivs = 1;
 5432:         }
 5433:     } else {
 5434:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5435:         $setprivs = 1;
 5436:     }
 5437:     return $setprivs;
 5438: }
 5439: 
 5440: sub set_adhoc_privileges {
 5441: # role can be cc or ca
 5442:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5443:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5444:     my $spec = $role.'.'.$area;
 5445:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5446:                                   $env{'user.name'},1);
 5447:     my %ccrole = ();
 5448:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5449:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5450:     &appenv(\%userroles,[$role,'cm']);
 5451:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5452:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5453:         &appenv( {'request.role'        => $spec,
 5454:                   'request.role.domain' => $dcdom,
 5455:                   'request.course.sec'  => ''
 5456:                  }
 5457:                );
 5458:         my $tadv=0;
 5459:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5460:         &appenv({'request.role.adv'    => $tadv});
 5461:     }
 5462: }
 5463: 
 5464: # --------------------------------------------------------------- get interface
 5465: 
 5466: sub get {
 5467:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5468:    my $items='';
 5469:    foreach my $item (@$storearr) {
 5470:        $items.=&escape($item).'&';
 5471:    }
 5472:    $items=~s/\&$//;
 5473:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5474:    if (!$uname) { $uname=$env{'user.name'}; }
 5475:    my $uhome=&homeserver($uname,$udomain);
 5476: 
 5477:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5478:    my @pairs=split(/\&/,$rep);
 5479:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5480:      return @pairs;
 5481:    }
 5482:    my %returnhash=();
 5483:    my $i=0;
 5484:    foreach my $item (@$storearr) {
 5485:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5486:       $i++;
 5487:    }
 5488:    return %returnhash;
 5489: }
 5490: 
 5491: # --------------------------------------------------------------- del interface
 5492: 
 5493: sub del {
 5494:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5495:    my $items='';
 5496:    foreach my $item (@$storearr) {
 5497:        $items.=&escape($item).'&';
 5498:    }
 5499: 
 5500:    $items=~s/\&$//;
 5501:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5502:    if (!$uname) { $uname=$env{'user.name'}; }
 5503:    my $uhome=&homeserver($uname,$udomain);
 5504:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5505: }
 5506: 
 5507: # -------------------------------------------------------------- dump interface
 5508: 
 5509: sub unserialize {
 5510:     my ($rep, $escapedkeys) = @_;
 5511: 
 5512:     return {} if $rep =~ /^error/;
 5513: 
 5514:     my %returnhash=();
 5515: 	foreach my $item (split /\&/, $rep) {
 5516: 	    my ($key, $value) = split(/=/, $item, 2);
 5517: 	    $key = unescape($key) unless $escapedkeys;
 5518: 	    next if $key =~ /^error: 2 /;
 5519: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5520: 	}
 5521:     #return %returnhash;
 5522:     return \%returnhash;
 5523: }        
 5524: 
 5525: # see Lond::dump_with_regexp
 5526: # if $escapedkeys hash keys won't get unescaped.
 5527: sub dump {
 5528:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5529:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5530:     if (!$uname) { $uname=$env{'user.name'}; }
 5531:     my $uhome=&homeserver($uname,$udomain);
 5532: 
 5533:     my $reply;
 5534:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5535:         # user is hosted on this machine
 5536:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5537:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5538:         return %{unserialize($reply, $escapedkeys)};
 5539:     }
 5540:     if ($regexp) {
 5541: 	$regexp=&escape($regexp);
 5542:     } else {
 5543: 	$regexp='.';
 5544:     }
 5545:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5546:     my @pairs=split(/\&/,$rep);
 5547:     my %returnhash=();
 5548:     if (!($rep =~ /^error/ )) {
 5549: 	foreach my $item (@pairs) {
 5550: 	    my ($key,$value)=split(/=/,$item,2);
 5551:         $key = unescape($key) unless $escapedkeys;
 5552:         #$key = &unescape($key);
 5553: 	    next if ($key =~ /^error: 2 /);
 5554: 	    $returnhash{$key}=&thaw_unescape($value);
 5555: 	}
 5556:     }
 5557:     return %returnhash;
 5558: }
 5559: 
 5560: 
 5561: # --------------------------------------------------------- dumpstore interface
 5562: 
 5563: sub dumpstore {
 5564:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5565:    # same as dump but keys must be escaped. They may contain colon separated
 5566:    # lists of values that may themself contain colons (e.g. symbs).
 5567:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5568: }
 5569: 
 5570: # -------------------------------------------------------------- keys interface
 5571: 
 5572: sub getkeys {
 5573:    my ($namespace,$udomain,$uname)=@_;
 5574:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5575:    if (!$uname) { $uname=$env{'user.name'}; }
 5576:    my $uhome=&homeserver($uname,$udomain);
 5577:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5578:    my @keyarray=();
 5579:    foreach my $key (split(/\&/,$rep)) {
 5580:       next if ($key =~ /^error: 2 /);
 5581:       push(@keyarray,&unescape($key));
 5582:    }
 5583:    return @keyarray;
 5584: }
 5585: 
 5586: # --------------------------------------------------------------- currentdump
 5587: sub currentdump {
 5588:    my ($courseid,$sdom,$sname)=@_;
 5589:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5590:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5591:    $sname    = $env{'user.name'}         if (! defined($sname));
 5592:    my $uhome = &homeserver($sname,$sdom);
 5593:    my $rep;
 5594: 
 5595:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5596:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5597:                    $courseid)));
 5598:    } else {
 5599:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5600:    }
 5601: 
 5602:    return if ($rep =~ /^(error:|no_such_host)/);
 5603:    #
 5604:    my %returnhash=();
 5605:    #
 5606:    if ($rep eq "unknown_cmd") { 
 5607:        # an old lond will not know currentdump
 5608:        # Do a dump and make it look like a currentdump
 5609:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5610:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5611:        my %hash = @tmp;
 5612:        @tmp=();
 5613:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5614:    } else {
 5615:        my @pairs=split(/\&/,$rep);
 5616:        foreach my $pair (@pairs) {
 5617:            my ($key,$value)=split(/=/,$pair,2);
 5618:            my ($symb,$param) = split(/:/,$key);
 5619:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5620:                                                         &thaw_unescape($value);
 5621:        }
 5622:    }
 5623:    return %returnhash;
 5624: }
 5625: 
 5626: sub convert_dump_to_currentdump{
 5627:     my %hash = %{shift()};
 5628:     my %returnhash;
 5629:     # Code ripped from lond, essentially.  The only difference
 5630:     # here is the unescaping done by lonnet::dump().  Conceivably
 5631:     # we might run in to problems with parameter names =~ /^v\./
 5632:     while (my ($key,$value) = each(%hash)) {
 5633:         my ($v,$symb,$param) = split(/:/,$key);
 5634: 	$symb  = &unescape($symb);
 5635: 	$param = &unescape($param);
 5636:         next if ($v eq 'version' || $symb eq 'keys');
 5637:         next if (exists($returnhash{$symb}) &&
 5638:                  exists($returnhash{$symb}->{$param}) &&
 5639:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5640:         $returnhash{$symb}->{$param}=$value;
 5641:         $returnhash{$symb}->{'v.'.$param}=$v;
 5642:     }
 5643:     #
 5644:     # Remove all of the keys in the hashes which keep track of
 5645:     # the version of the parameter.
 5646:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5647:         # use a foreach because we are going to delete from the hash.
 5648:         foreach my $key (keys(%$param_hash)) {
 5649:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5650:         }
 5651:     }
 5652:     return \%returnhash;
 5653: }
 5654: 
 5655: # ------------------------------------------------------ critical inc interface
 5656: 
 5657: sub cinc {
 5658:     return &inc(@_,'critical');
 5659: }
 5660: 
 5661: # --------------------------------------------------------------- inc interface
 5662: 
 5663: sub inc {
 5664:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5665:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5666:     if (!$uname) { $uname=$env{'user.name'}; }
 5667:     my $uhome=&homeserver($uname,$udomain);
 5668:     my $items='';
 5669:     if (! ref($store)) {
 5670:         # got a single value, so use that instead
 5671:         $items = &escape($store).'=&';
 5672:     } elsif (ref($store) eq 'SCALAR') {
 5673:         $items = &escape($$store).'=&';        
 5674:     } elsif (ref($store) eq 'ARRAY') {
 5675:         $items = join('=&',map {&escape($_);} @{$store});
 5676:     } elsif (ref($store) eq 'HASH') {
 5677:         while (my($key,$value) = each(%{$store})) {
 5678:             $items.= &escape($key).'='.&escape($value).'&';
 5679:         }
 5680:     }
 5681:     $items=~s/\&$//;
 5682:     if ($critical) {
 5683: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5684:     } else {
 5685: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5686:     }
 5687: }
 5688: 
 5689: # --------------------------------------------------------------- put interface
 5690: 
 5691: sub put {
 5692:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5693:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5694:    if (!$uname) { $uname=$env{'user.name'}; }
 5695:    my $uhome=&homeserver($uname,$udomain);
 5696:    my $items='';
 5697:    foreach my $item (keys(%$storehash)) {
 5698:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5699:    }
 5700:    $items=~s/\&$//;
 5701:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5702: }
 5703: 
 5704: # ------------------------------------------------------------ newput interface
 5705: 
 5706: sub newput {
 5707:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5708:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5709:    if (!$uname) { $uname=$env{'user.name'}; }
 5710:    my $uhome=&homeserver($uname,$udomain);
 5711:    my $items='';
 5712:    foreach my $key (keys(%$storehash)) {
 5713:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5714:    }
 5715:    $items=~s/\&$//;
 5716:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5717: }
 5718: 
 5719: # ---------------------------------------------------------  putstore interface
 5720: 
 5721: sub putstore {
 5722:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5724:    if (!$uname) { $uname=$env{'user.name'}; }
 5725:    my $uhome=&homeserver($uname,$udomain);
 5726:    my $items='';
 5727:    foreach my $key (keys(%$storehash)) {
 5728:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5729:    }
 5730:    $items=~s/\&$//;
 5731:    my $esc_symb=&escape($symb);
 5732:    my $esc_v=&escape($version);
 5733:    my $reply =
 5734:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5735: 	      $uhome);
 5736:    if ($reply eq 'unknown_cmd') {
 5737:        # gfall back to way things use to be done
 5738:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5739: 			    $uname);
 5740:    }
 5741:    return $reply;
 5742: }
 5743: 
 5744: sub old_putstore {
 5745:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5746:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5747:     if (!$uname) { $uname=$env{'user.name'}; }
 5748:     my $uhome=&homeserver($uname,$udomain);
 5749:     my %newstorehash;
 5750:     foreach my $item (keys(%$storehash)) {
 5751: 	my $key = $version.':'.&escape($symb).':'.$item;
 5752: 	$newstorehash{$key} = $storehash->{$item};
 5753:     }
 5754:     my $items='';
 5755:     my %allitems = ();
 5756:     foreach my $item (keys(%newstorehash)) {
 5757: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5758: 	    my $key = $1.':keys:'.$2;
 5759: 	    $allitems{$key} .= $3.':';
 5760: 	}
 5761: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5762:     }
 5763:     foreach my $item (keys(%allitems)) {
 5764: 	$allitems{$item} =~ s/\:$//;
 5765: 	$items.= $item.'='.$allitems{$item}.'&';
 5766:     }
 5767:     $items=~s/\&$//;
 5768:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5769: }
 5770: 
 5771: # ------------------------------------------------------ critical put interface
 5772: 
 5773: sub cput {
 5774:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5775:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5776:    if (!$uname) { $uname=$env{'user.name'}; }
 5777:    my $uhome=&homeserver($uname,$udomain);
 5778:    my $items='';
 5779:    foreach my $item (keys(%$storehash)) {
 5780:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5781:    }
 5782:    $items=~s/\&$//;
 5783:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5784: }
 5785: 
 5786: # -------------------------------------------------------------- eget interface
 5787: 
 5788: sub eget {
 5789:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5790:    my $items='';
 5791:    foreach my $item (@$storearr) {
 5792:        $items.=&escape($item).'&';
 5793:    }
 5794:    $items=~s/\&$//;
 5795:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5796:    if (!$uname) { $uname=$env{'user.name'}; }
 5797:    my $uhome=&homeserver($uname,$udomain);
 5798:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5799:    my @pairs=split(/\&/,$rep);
 5800:    my %returnhash=();
 5801:    my $i=0;
 5802:    foreach my $item (@$storearr) {
 5803:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5804:       $i++;
 5805:    }
 5806:    return %returnhash;
 5807: }
 5808: 
 5809: # ------------------------------------------------------------ tmpput interface
 5810: sub tmpput {
 5811:     my ($storehash,$server,$context)=@_;
 5812:     my $items='';
 5813:     foreach my $item (keys(%$storehash)) {
 5814: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5815:     }
 5816:     $items=~s/\&$//;
 5817:     if (defined($context)) {
 5818:         $items .= ':'.&escape($context);
 5819:     }
 5820:     return &reply("tmpput:$items",$server);
 5821: }
 5822: 
 5823: # ------------------------------------------------------------ tmpget interface
 5824: sub tmpget {
 5825:     my ($token,$server)=@_;
 5826:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5827:     my $rep=&reply("tmpget:$token",$server);
 5828:     my %returnhash;
 5829:     foreach my $item (split(/\&/,$rep)) {
 5830: 	my ($key,$value)=split(/=/,$item);
 5831:         next if ($key =~ /^error: 2 /);
 5832: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5833:     }
 5834:     return %returnhash;
 5835: }
 5836: 
 5837: # ------------------------------------------------------------ tmpdel interface
 5838: sub tmpdel {
 5839:     my ($token,$server)=@_;
 5840:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5841:     return &reply("tmpdel:$token",$server);
 5842: }
 5843: 
 5844: # ------------------------------------------------------------ get_timebased_id 
 5845: 
 5846: sub get_timebased_id {
 5847:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5848:         $maxtries) = @_;
 5849:     my ($newid,$error,$dellock);
 5850:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5851:         return ('','ok','invalid call to get suffix');
 5852:     }
 5853: 
 5854: # set defaults for any optional args for which values were not supplied
 5855:     if ($who eq '') {
 5856:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5857:     }
 5858:     if (!$locktries) {
 5859:         $locktries = 3;
 5860:     }
 5861:     if (!$maxtries) {
 5862:         $maxtries = 10;
 5863:     }
 5864:     
 5865:     if (($cdom eq '') || ($cnum eq '')) {
 5866:         if ($env{'request.course.id'}) {
 5867:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5868:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5869:         }
 5870:         if (($cdom eq '') || ($cnum eq '')) {
 5871:             return ('','ok','call to get suffix not in course context');
 5872:         }
 5873:     }
 5874: 
 5875: # construct locking item
 5876:     my $lockhash = {
 5877:                       $prefix."\0".'locked_'.$keyid => $who,
 5878:                    };
 5879:     my $tries = 0;
 5880: 
 5881: # attempt to get lock on nohist_$namespace file
 5882:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5883:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5884:         $tries ++;
 5885:         sleep 1;
 5886:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5887:     }
 5888: 
 5889: # attempt to get unique identifier, based on current timestamp
 5890:     if ($gotlock eq 'ok') {
 5891:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5892:         my $id = time;
 5893:         $newid = $id;
 5894:         my $idtries = 0;
 5895:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5896:             if ($idtype eq 'concat') {
 5897:                 $newid = $id.$idtries;
 5898:             } else {
 5899:                 $newid ++;
 5900:             }
 5901:             $idtries ++;
 5902:         }
 5903:         if (!exists($inuse{$prefix."\0".$newid})) {
 5904:             my %new_item =  (
 5905:                               $prefix."\0".$newid => $who,
 5906:                             );
 5907:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5908:                                                  $cdom,$cnum);
 5909:             if ($putresult ne 'ok') {
 5910:                 undef($newid);
 5911:                 $error = 'error saving new item: '.$putresult;
 5912:             }
 5913:         } else {
 5914:              $error = ('error: no unique suffix available for the new item ');
 5915:         }
 5916: #  remove lock
 5917:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5918:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5919:     } else {
 5920:         $error = "error: could not obtain lockfile\n";
 5921:         $dellock = 'ok';
 5922:     }
 5923:     return ($newid,$dellock,$error);
 5924: }
 5925: 
 5926: # -------------------------------------------------- portfolio access checking
 5927: 
 5928: sub portfolio_access {
 5929:     my ($requrl) = @_;
 5930:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5931:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5932:     if ($result) {
 5933:         my %setters;
 5934:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5935:             my ($startblock,$endblock) =
 5936:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5937:             if ($startblock && $endblock) {
 5938:                 return 'B';
 5939:             }
 5940:         } else {
 5941:             my ($startblock,$endblock) =
 5942:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5943:             if ($startblock && $endblock) {
 5944:                 return 'B';
 5945:             }
 5946:         }
 5947:     }
 5948:     if ($result eq 'ok') {
 5949:        return 'F';
 5950:     } elsif ($result =~ /^[^:]+:guest_/) {
 5951:        return 'A';
 5952:     }
 5953:     return '';
 5954: }
 5955: 
 5956: sub get_portfolio_access {
 5957:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5958: 
 5959:     if (!ref($access_hash)) {
 5960: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5961: 	my %access_controls = &get_access_controls($current_perms,$group,
 5962: 						   $file_name);
 5963: 	$access_hash = $access_controls{$file_name};
 5964:     }
 5965: 
 5966:     my ($public,$guest,@domains,@users,@courses,@groups);
 5967:     my $now = time;
 5968:     if (ref($access_hash) eq 'HASH') {
 5969:         foreach my $key (keys(%{$access_hash})) {
 5970:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5971:             if ($start > $now) {
 5972:                 next;
 5973:             }
 5974:             if ($end && $end<$now) {
 5975:                 next;
 5976:             }
 5977:             if ($scope eq 'public') {
 5978:                 $public = $key;
 5979:                 last;
 5980:             } elsif ($scope eq 'guest') {
 5981:                 $guest = $key;
 5982:             } elsif ($scope eq 'domains') {
 5983:                 push(@domains,$key);
 5984:             } elsif ($scope eq 'users') {
 5985:                 push(@users,$key);
 5986:             } elsif ($scope eq 'course') {
 5987:                 push(@courses,$key);
 5988:             } elsif ($scope eq 'group') {
 5989:                 push(@groups,$key);
 5990:             }
 5991:         }
 5992:         if ($public) {
 5993:             return 'ok';
 5994:         }
 5995:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5996:             if ($guest) {
 5997:                 return $guest;
 5998:             }
 5999:         } else {
 6000:             if (@domains > 0) {
 6001:                 foreach my $domkey (@domains) {
 6002:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6003:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6004:                             return 'ok';
 6005:                         }
 6006:                     }
 6007:                 }
 6008:             }
 6009:             if (@users > 0) {
 6010:                 foreach my $userkey (@users) {
 6011:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6012:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6013:                             if (ref($item) eq 'HASH') {
 6014:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6015:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6016:                                     return 'ok';
 6017:                                 }
 6018:                             }
 6019:                         }
 6020:                     } 
 6021:                 }
 6022:             }
 6023:             my %roleshash;
 6024:             my @courses_and_groups = @courses;
 6025:             push(@courses_and_groups,@groups); 
 6026:             if (@courses_and_groups > 0) {
 6027:                 my (%allgroups,%allroles); 
 6028:                 my ($start,$end,$role,$sec,$group);
 6029:                 foreach my $envkey (%env) {
 6030:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6031:                         my $cid = $2.'_'.$3; 
 6032:                         if ($1 eq 'gr') {
 6033:                             $group = $4;
 6034:                             $allgroups{$cid}{$group} = $env{$envkey};
 6035:                         } else {
 6036:                             if ($4 eq '') {
 6037:                                 $sec = 'none';
 6038:                             } else {
 6039:                                 $sec = $4;
 6040:                             }
 6041:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6042:                         }
 6043:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6044:                         my $cid = $2.'_'.$3;
 6045:                         if ($4 eq '') {
 6046:                             $sec = 'none';
 6047:                         } else {
 6048:                             $sec = $4;
 6049:                         }
 6050:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6051:                     }
 6052:                 }
 6053:                 if (keys(%allroles) == 0) {
 6054:                     return;
 6055:                 }
 6056:                 foreach my $key (@courses_and_groups) {
 6057:                     my %content = %{$$access_hash{$key}};
 6058:                     my $cnum = $content{'number'};
 6059:                     my $cdom = $content{'domain'};
 6060:                     my $cid = $cdom.'_'.$cnum;
 6061:                     if (!exists($allroles{$cid})) {
 6062:                         next;
 6063:                     }    
 6064:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6065:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6066:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6067:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6068:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6069:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6070:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6071:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6072:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6073:                                         if (grep/^all$/,@sections) {
 6074:                                             return 'ok';
 6075:                                         } else {
 6076:                                             if (grep/^$sec$/,@sections) {
 6077:                                                 return 'ok';
 6078:                                             }
 6079:                                         }
 6080:                                     }
 6081:                                 }
 6082:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6083:                                     if (grep/^none$/,@groups) {
 6084:                                         return 'ok';
 6085:                                     }
 6086:                                 } else {
 6087:                                     if (grep/^all$/,@groups) {
 6088:                                         return 'ok';
 6089:                                     } 
 6090:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6091:                                         if (grep/^$group$/,@groups) {
 6092:                                             return 'ok';
 6093:                                         }
 6094:                                     }
 6095:                                 } 
 6096:                             }
 6097:                         }
 6098:                     }
 6099:                 }
 6100:             }
 6101:             if ($guest) {
 6102:                 return $guest;
 6103:             }
 6104:         }
 6105:     }
 6106:     return;
 6107: }
 6108: 
 6109: sub course_group_datechecker {
 6110:     my ($dates,$now,$status) = @_;
 6111:     my ($start,$end) = split(/\./,$dates);
 6112:     if (!$start && !$end) {
 6113:         return 'ok';
 6114:     }
 6115:     if (grep/^active$/,@{$status}) {
 6116:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6117:             return 'ok';
 6118:         }
 6119:     }
 6120:     if (grep/^previous$/,@{$status}) {
 6121:         if ($end > $now ) {
 6122:             return 'ok';
 6123:         }
 6124:     }
 6125:     if (grep/^future$/,@{$status}) {
 6126:         if ($start > $now) {
 6127:             return 'ok';
 6128:         }
 6129:     }
 6130:     return; 
 6131: }
 6132: 
 6133: sub parse_portfolio_url {
 6134:     my ($url) = @_;
 6135: 
 6136:     my ($type,$udom,$unum,$group,$file_name);
 6137:     
 6138:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6139: 	$type = 1;
 6140:         $udom = $1;
 6141:         $unum = $2;
 6142:         $file_name = $3;
 6143:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6144: 	$type = 2;
 6145:         $udom = $1;
 6146:         $unum = $2;
 6147:         $group = $3;
 6148:         $file_name = $3.'/'.$4;
 6149:     }
 6150:     if (wantarray) {
 6151: 	return ($type,$udom,$unum,$file_name,$group);
 6152:     }
 6153:     return $type;
 6154: }
 6155: 
 6156: sub is_portfolio_url {
 6157:     my ($url) = @_;
 6158:     return scalar(&parse_portfolio_url($url));
 6159: }
 6160: 
 6161: sub is_portfolio_file {
 6162:     my ($file) = @_;
 6163:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6164:         return 1;
 6165:     }
 6166:     return;
 6167: }
 6168: 
 6169: sub usertools_access {
 6170:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6171:     my ($access,%tools);
 6172:     if ($context eq '') {
 6173:         $context = 'tools';
 6174:     }
 6175:     if ($context eq 'requestcourses') {
 6176:         %tools = (
 6177:                       official   => 1,
 6178:                       unofficial => 1,
 6179:                       community  => 1,
 6180:                  );
 6181:     } elsif ($context eq 'requestauthor') {
 6182:         %tools = (
 6183:                       requestauthor => 1,
 6184:                  );
 6185:     } else {
 6186:         %tools = (
 6187:                       aboutme   => 1,
 6188:                       blog      => 1,
 6189:                       webdav    => 1,
 6190:                       portfolio => 1,
 6191:                  );
 6192:     }
 6193:     return if (!defined($tools{$tool}));
 6194: 
 6195:     if ((!defined($udom)) || (!defined($uname))) {
 6196:         $udom = $env{'user.domain'};
 6197:         $uname = $env{'user.name'};
 6198:     }
 6199: 
 6200:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6201:         if ($action ne 'reload') {
 6202:             if ($context eq 'requestcourses') {
 6203:                 return $env{'environment.canrequest.'.$tool};
 6204:             } elsif ($context eq 'requestauthor') {
 6205:                 return $env{'environment.canrequest.author'};
 6206:             } else {
 6207:                 return $env{'environment.availabletools.'.$tool};
 6208:             }
 6209:         }
 6210:     }
 6211: 
 6212:     my ($toolstatus,$inststatus,$envkey);
 6213:     if ($context eq 'requestauthor') {
 6214:         $envkey = $context; 
 6215:     } else {
 6216:         $envkey = $context.'.'.$tool;
 6217:     }
 6218: 
 6219:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6220:          ($action ne 'reload')) {
 6221:         $toolstatus = $env{'environment.'.$envkey};
 6222:         $inststatus = $env{'environment.inststatus'};
 6223:     } else {
 6224:         if (ref($userenvref) eq 'HASH') {
 6225:             $toolstatus = $userenvref->{$envkey};
 6226:             $inststatus = $userenvref->{'inststatus'};
 6227:         } else {
 6228:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6229:             $toolstatus = $userenv{$envkey};
 6230:             $inststatus = $userenv{'inststatus'};
 6231:         }
 6232:     }
 6233: 
 6234:     if ($toolstatus ne '') {
 6235:         if ($toolstatus) {
 6236:             $access = 1;
 6237:         } else {
 6238:             $access = 0;
 6239:         }
 6240:         return $access;
 6241:     }
 6242: 
 6243:     my ($is_adv,%domdef);
 6244:     if (ref($is_advref) eq 'HASH') {
 6245:         $is_adv = $is_advref->{'is_adv'};
 6246:     } else {
 6247:         $is_adv = &is_advanced_user($udom,$uname);
 6248:     }
 6249:     if (ref($domdefref) eq 'HASH') {
 6250:         %domdef = %{$domdefref};
 6251:     } else {
 6252:         %domdef = &get_domain_defaults($udom);
 6253:     }
 6254:     if (ref($domdef{$tool}) eq 'HASH') {
 6255:         if ($is_adv) {
 6256:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6257:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6258:                     $access = 1;
 6259:                 } else {
 6260:                     $access = 0;
 6261:                 }
 6262:                 return $access;
 6263:             }
 6264:         }
 6265:         if ($inststatus ne '') {
 6266:             my ($hasaccess,$hasnoaccess);
 6267:             foreach my $affiliation (split(/:/,$inststatus)) {
 6268:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6269:                     if ($domdef{$tool}{$affiliation}) {
 6270:                         $hasaccess = 1;
 6271:                     } else {
 6272:                         $hasnoaccess = 1;
 6273:                     }
 6274:                 }
 6275:             }
 6276:             if ($hasaccess || $hasnoaccess) {
 6277:                 if ($hasaccess) {
 6278:                     $access = 1;
 6279:                 } elsif ($hasnoaccess) {
 6280:                     $access = 0; 
 6281:                 }
 6282:                 return $access;
 6283:             }
 6284:         } else {
 6285:             if ($domdef{$tool}{'default'} ne '') {
 6286:                 if ($domdef{$tool}{'default'}) {
 6287:                     $access = 1;
 6288:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6289:                     $access = 0;
 6290:                 }
 6291:                 return $access;
 6292:             }
 6293:         }
 6294:     } else {
 6295:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6296:             $access = 1;
 6297:         } else {
 6298:             $access = 0;
 6299:         }
 6300:         return $access;
 6301:     }
 6302: }
 6303: 
 6304: sub is_course_owner {
 6305:     my ($cdom,$cnum,$udom,$uname) = @_;
 6306:     if (($udom eq '') || ($uname eq '')) {
 6307:         $udom = $env{'user.domain'};
 6308:         $uname = $env{'user.name'};
 6309:     }
 6310:     unless (($udom eq '') || ($uname eq '')) {
 6311:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6312:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6313:                 return 1;
 6314:             } else {
 6315:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6316:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6317:                     return 1;
 6318:                 }
 6319:             }
 6320:         }
 6321:     }
 6322:     return;
 6323: }
 6324: 
 6325: sub is_advanced_user {
 6326:     my ($udom,$uname) = @_;
 6327:     if ($udom ne '' && $uname ne '') {
 6328:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6329:             if (wantarray) {
 6330:                 return ($env{'user.adv'},$env{'user.author'});
 6331:             } else {
 6332:                 return $env{'user.adv'};
 6333:             }
 6334:         }
 6335:     }
 6336:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6337:     my %allroles;
 6338:     my ($is_adv,$is_author);
 6339:     foreach my $role (keys(%roleshash)) {
 6340:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6341:         my $area = '/'.$tdomain.'/'.$trest;
 6342:         if ($sec ne '') {
 6343:             $area .= '/'.$sec;
 6344:         }
 6345:         if (($area ne '') && ($trole ne '')) {
 6346:             my $spec=$trole.'.'.$area;
 6347:             if ($trole =~ /^cr\//) {
 6348:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6349:             } elsif ($trole ne 'gr') {
 6350:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6351:             }
 6352:             if ($trole eq 'au') {
 6353:                 $is_author = 1;
 6354:             }
 6355:         }
 6356:     }
 6357:     foreach my $role (keys(%allroles)) {
 6358:         last if ($is_adv);
 6359:         foreach my $item (split(/:/,$allroles{$role})) {
 6360:             if ($item ne '') {
 6361:                 my ($privilege,$restrictions)=split(/&/,$item);
 6362:                 if ($privilege eq 'adv') {
 6363:                     $is_adv = 1;
 6364:                     last;
 6365:                 }
 6366:             }
 6367:         }
 6368:     }
 6369:     if (wantarray) {
 6370:         return ($is_adv,$is_author);
 6371:     }
 6372:     return $is_adv;
 6373: }
 6374: 
 6375: sub check_can_request {
 6376:     my ($dom,$can_request,$request_domains) = @_;
 6377:     my $canreq = 0;
 6378:     my ($types,$typename) = &Apache::loncommon::course_types();
 6379:     my @options = ('approval','validate','autolimit');
 6380:     my $optregex = join('|',@options);
 6381:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6382:         foreach my $type (@{$types}) {
 6383:             if (&usertools_access($env{'user.name'},
 6384:                                   $env{'user.domain'},
 6385:                                   $type,undef,'requestcourses')) {
 6386:                 $canreq ++;
 6387:                 if (ref($request_domains) eq 'HASH') {
 6388:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6389:                 }
 6390:                 if ($dom eq $env{'user.domain'}) {
 6391:                     $can_request->{$type} = 1;
 6392:                 }
 6393:             }
 6394:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6395:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6396:                 if (@curr > 0) {
 6397:                     foreach my $item (@curr) {
 6398:                         if (ref($request_domains) eq 'HASH') {
 6399:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6400:                             if ($otherdom ne '') {
 6401:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6402:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6403:                                         push(@{$request_domains->{$type}},$otherdom);
 6404:                                     }
 6405:                                 } else {
 6406:                                     push(@{$request_domains->{$type}},$otherdom);
 6407:                                 }
 6408:                             }
 6409:                         }
 6410:                     }
 6411:                     unless($dom eq $env{'user.domain'}) {
 6412:                         $canreq ++;
 6413:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6414:                             $can_request->{$type} = 1;
 6415:                         }
 6416:                     }
 6417:                 }
 6418:             }
 6419:         }
 6420:     }
 6421:     return $canreq;
 6422: }
 6423: 
 6424: # ---------------------------------------------- Custom access rule evaluation
 6425: 
 6426: sub customaccess {
 6427:     my ($priv,$uri)=@_;
 6428:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6429:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6430:     $udom = &LONCAPA::clean_domain($udom);
 6431:     $ucrs = &LONCAPA::clean_username($ucrs);
 6432:     my $access=0;
 6433:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6434: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6435: 	if ($type eq 'user') {
 6436: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6437: 		my ($tdom,$tuname)=split(m{/},$scope);
 6438: 		if ($tdom) {
 6439: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6440: 		}
 6441: 		if ($tuname) {
 6442: 		    if ($tuname ne $env{'user.name'}) { next; }
 6443: 		}
 6444: 		$access=($effect eq 'allow');
 6445: 		last;
 6446: 	    }
 6447: 	} else {
 6448: 	    if ($role) {
 6449: 		if ($role ne $urole) { next; }
 6450: 	    }
 6451: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6452: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6453: 		if ($tdom) {
 6454: 		    if ($tdom ne $udom) { next; }
 6455: 		}
 6456: 		if ($tcrs) {
 6457: 		    if ($tcrs ne $ucrs) { next; }
 6458: 		}
 6459: 		if ($tsec) {
 6460: 		    if ($tsec ne $usec) { next; }
 6461: 		}
 6462: 		$access=($effect eq 'allow');
 6463: 		last;
 6464: 	    }
 6465: 	    if ($realm eq '' && $role eq '') {
 6466: 		$access=($effect eq 'allow');
 6467: 	    }
 6468: 	}
 6469:     }
 6470:     return $access;
 6471: }
 6472: 
 6473: # ------------------------------------------------- Check for a user privilege
 6474: 
 6475: sub allowed {
 6476:     my ($priv,$uri,$symb,$role)=@_;
 6477:     my $ver_orguri=$uri;
 6478:     $uri=&deversion($uri);
 6479:     my $orguri=$uri;
 6480:     $uri=&declutter($uri);
 6481: 
 6482:     if ($priv eq 'evb') {
 6483: # Evade communication block restrictions for specified role in a course
 6484:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6485:             return $1;
 6486:         } else {
 6487:             return;
 6488:         }
 6489:     }
 6490: 
 6491:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6492: # Free bre access to adm and meta resources
 6493:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6494: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6495: 	&& ($priv eq 'bre')) {
 6496: 	return 'F';
 6497:     }
 6498: 
 6499: # Free bre access to user's own portfolio contents
 6500:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6501:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6502: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6503:         my %setters;
 6504:         my ($startblock,$endblock) = 
 6505:             &Apache::loncommon::blockcheck(\%setters,'port');
 6506:         if ($startblock && $endblock) {
 6507:             return 'B';
 6508:         } else {
 6509:             return 'F';
 6510:         }
 6511:     }
 6512: 
 6513: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6514:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6515:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6516:         if (exists($env{'request.course.id'})) {
 6517:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6518:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6519:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6520:                 my $courseprivid=$env{'request.course.id'};
 6521:                 $courseprivid=~s/\_/\//;
 6522:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6523:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6524:                     return $1; 
 6525:                 } else {
 6526:                     if ($env{'request.course.sec'}) {
 6527:                         $courseprivid.='/'.$env{'request.course.sec'};
 6528:                     }
 6529:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6530:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6531:                         return $2;
 6532:                     }
 6533:                 }
 6534:             }
 6535:         }
 6536:     }
 6537: 
 6538: # Free bre to public access
 6539: 
 6540:     if ($priv eq 'bre') {
 6541:         my $copyright=&metadata($uri,'copyright');
 6542: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6543:            return 'F'; 
 6544:         }
 6545:         if ($copyright eq 'priv') {
 6546:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6547: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6548: 		return '';
 6549:             }
 6550:         }
 6551:         if ($copyright eq 'domain') {
 6552:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6553: 	    unless (($env{'user.domain'} eq $1) ||
 6554:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6555: 		return '';
 6556:             }
 6557:         }
 6558:         if ($env{'request.role'}=~ /li\.\//) {
 6559:             # Library role, so allow browsing of resources in this domain.
 6560:             return 'F';
 6561:         }
 6562:         if ($copyright eq 'custom') {
 6563: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6564:         }
 6565:     }
 6566:     # Domain coordinator is trying to create a course
 6567:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6568:         # uri is the requested domain in this case.
 6569:         # comparison to 'request.role.domain' shows if the user has selected
 6570:         # a role of dc for the domain in question.
 6571:         return 'F' if ($uri eq $env{'request.role.domain'});
 6572:     }
 6573: 
 6574:     my $thisallowed='';
 6575:     my $statecond=0;
 6576:     my $courseprivid='';
 6577: 
 6578:     my $ownaccess;
 6579:     # Community Coordinator or Assistant Co-author browsing resource space.
 6580:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6581:         if ($uri eq '') {
 6582:             $ownaccess = 1;
 6583:         } else {
 6584:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6585:                 my $udom = $env{'user.domain'};
 6586:                 my $uname = $env{'user.name'};
 6587:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6588:                     $ownaccess = 1;
 6589:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6590:                     unless ($uri =~ m{\.\./}) {
 6591:                         $ownaccess = 1;
 6592:                     }
 6593:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6594:                     my $now = time;
 6595:                     if ($uri =~ m{^([^/]+)/?$}) {
 6596:                         my $adom = $1;
 6597:                         foreach my $key (keys(%env)) {
 6598:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6599:                                 my ($start,$end) = split('.',$env{$key});
 6600:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6601:                                     $ownaccess = 1;
 6602:                                     last;
 6603:                                 }
 6604:                             }
 6605:                         }
 6606:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6607:                         my $adom = $1;
 6608:                         my $aname = $2;
 6609:                         foreach my $role ('ca','aa') { 
 6610:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6611:                                 my ($start,$end) =
 6612:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6613:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6614:                                     $ownaccess = 1;
 6615:                                     last;
 6616:                                 }
 6617:                             }
 6618:                         }
 6619:                     }
 6620:                 }
 6621:             }
 6622:         }
 6623:     }
 6624: 
 6625: # Course
 6626: 
 6627:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6628:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6629:             $thisallowed.=$1;
 6630:         }
 6631:     }
 6632: 
 6633: # Domain
 6634: 
 6635:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6636:        =~/\Q$priv\E\&([^\:]*)/) {
 6637:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6638:             $thisallowed.=$1;
 6639:         }
 6640:     }
 6641: 
 6642: # User who is not author or co-author might still be able to edit
 6643: # resource of an author in the domain (e.g., if Domain Coordinator).
 6644:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6645:         (&allowed('mdc',$env{'request.course.id'}))) {
 6646:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6647:             $thisallowed.=$1;
 6648:         }
 6649:     }
 6650: 
 6651: # Course: uri itself is a course
 6652:     my $courseuri=$uri;
 6653:     $courseuri=~s/\_(\d)/\/$1/;
 6654:     $courseuri=~s/^([^\/])/\/$1/;
 6655: 
 6656:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6657:        =~/\Q$priv\E\&([^\:]*)/) {
 6658:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6659:             $thisallowed.=$1;
 6660:         }
 6661:     }
 6662: 
 6663: # URI is an uploaded document for this course, default permissions don't matter
 6664: # not allowing 'edit' access (editupload) to uploaded course docs
 6665:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6666: 	$thisallowed='';
 6667:         my ($match)=&is_on_map($uri);
 6668:         if ($match) {
 6669:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6670:                   =~/\Q$priv\E\&([^\:]*)/) {
 6671:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6672:                 if (@blockers > 0) {
 6673:                     $thisallowed = 'B';
 6674:                 } else {
 6675:                     $thisallowed.=$1;
 6676:                 }
 6677:             }
 6678:         } else {
 6679:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6680:             if ($refuri) {
 6681:                 if ($refuri =~ m|^/adm/|) {
 6682:                     $thisallowed='F';
 6683:                 } else {
 6684:                     $refuri=&declutter($refuri);
 6685:                     my ($match) = &is_on_map($refuri);
 6686:                     if ($match) {
 6687:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6688:                         if (@blockers > 0) {
 6689:                             $thisallowed = 'B';
 6690:                         } else {
 6691:                             $thisallowed='F';
 6692:                         }
 6693:                     }
 6694:                 }
 6695:             }
 6696:         }
 6697:     }
 6698: 
 6699:     if ($priv eq 'bre'
 6700: 	&& $thisallowed ne 'F' 
 6701: 	&& $thisallowed ne '2'
 6702: 	&& &is_portfolio_url($uri)) {
 6703: 	$thisallowed = &portfolio_access($uri);
 6704:     }
 6705:     
 6706: # Full access at system, domain or course-wide level? Exit.
 6707:     if ($thisallowed=~/F/) {
 6708: 	return 'F';
 6709:     }
 6710: 
 6711: # If this is generating or modifying users, exit with special codes
 6712: 
 6713:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6714: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6715: 	    my ($audom,$auname)=split('/',$uri);
 6716: # no author name given, so this just checks on the general right to make a co-author in this domain
 6717: 	    unless ($auname) { return $thisallowed; }
 6718: # an author name is given, so we are about to actually make a co-author for a certain account
 6719: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6720: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6721: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6722: 	}
 6723: 	return $thisallowed;
 6724:     }
 6725: #
 6726: # Gathered so far: system, domain and course wide privileges
 6727: #
 6728: # Course: See if uri or referer is an individual resource that is part of 
 6729: # the course
 6730: 
 6731:     if ($env{'request.course.id'}) {
 6732: 
 6733:        $courseprivid=$env{'request.course.id'};
 6734:        if ($env{'request.course.sec'}) {
 6735:           $courseprivid.='/'.$env{'request.course.sec'};
 6736:        }
 6737:        $courseprivid=~s/\_/\//;
 6738:        my $checkreferer=1;
 6739:        my ($match,$cond)=&is_on_map($uri);
 6740:        if ($match) {
 6741:            $statecond=$cond;
 6742:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6743:                =~/\Q$priv\E\&([^\:]*)/) {
 6744:                my $value = $1;
 6745:                if ($priv eq 'bre') {
 6746:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6747:                    if (@blockers > 0) {
 6748:                        $thisallowed = 'B';
 6749:                    } else {
 6750:                        $thisallowed.=$value;
 6751:                    }
 6752:                } else {
 6753:                    $thisallowed.=$value;
 6754:                }
 6755:                $checkreferer=0;
 6756:            }
 6757:        }
 6758:        
 6759:        if ($checkreferer) {
 6760: 	  my $refuri=$env{'httpref.'.$orguri};
 6761:             unless ($refuri) {
 6762:                 foreach my $key (keys(%env)) {
 6763: 		    if ($key=~/^httpref\..*\*/) {
 6764: 			my $pattern=$key;
 6765:                         $pattern=~s/^httpref\.\/res\///;
 6766:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6767:                         $pattern=~s/\//\\\//g;
 6768:                         if ($orguri=~/$pattern/) {
 6769: 			    $refuri=$env{$key};
 6770:                         }
 6771:                     }
 6772:                 }
 6773:             }
 6774: 
 6775:          if ($refuri) { 
 6776: 	  $refuri=&declutter($refuri);
 6777:           my ($match,$cond)=&is_on_map($refuri);
 6778:             if ($match) {
 6779:               my $refstatecond=$cond;
 6780:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6781:                   =~/\Q$priv\E\&([^\:]*)/) {
 6782:                   my $value = $1;
 6783:                   if ($priv eq 'bre') {
 6784:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6785:                       if (@blockers > 0) {
 6786:                           $thisallowed = 'B';
 6787:                       } else {
 6788:                           $thisallowed.=$value;
 6789:                       }
 6790:                   } else {
 6791:                       $thisallowed.=$value;
 6792:                   }
 6793:                   $uri=$refuri;
 6794:                   $statecond=$refstatecond;
 6795:               }
 6796:           }
 6797:         }
 6798:        }
 6799:    }
 6800: 
 6801: #
 6802: # Gathered now: all privileges that could apply, and condition number
 6803: # 
 6804: #
 6805: # Full or no access?
 6806: #
 6807: 
 6808:     if ($thisallowed=~/F/) {
 6809: 	return 'F';
 6810:     }
 6811: 
 6812:     unless ($thisallowed) {
 6813:         return '';
 6814:     }
 6815: 
 6816: # Restrictions exist, deal with them
 6817: #
 6818: #   C:according to course preferences
 6819: #   R:according to resource settings
 6820: #   L:unless locked
 6821: #   X:according to user session state
 6822: #
 6823: 
 6824: # Possibly locked functionality, check all courses
 6825: # Locks might take effect only after 10 minutes cache expiration for other
 6826: # courses, and 2 minutes for current course
 6827: 
 6828:     my $envkey;
 6829:     if ($thisallowed=~/L/) {
 6830:         foreach $envkey (keys(%env)) {
 6831:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6832:                my $courseid=$2;
 6833:                my $roleid=$1.'.'.$2;
 6834:                $courseid=~s/^\///;
 6835:                my $expiretime=600;
 6836:                if ($env{'request.role'} eq $roleid) {
 6837: 		  $expiretime=120;
 6838:                }
 6839: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6840:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6841:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6842: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6843:                }
 6844:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6845:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6846: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6847:                        &log($env{'user.domain'},$env{'user.name'},
 6848:                             $env{'user.home'},
 6849:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6850:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6851:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6852: 		       return '';
 6853:                    }
 6854:                }
 6855:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6856:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6857: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6858:                        &log($env{'user.domain'},$env{'user.name'},
 6859:                             $env{'user.home'},
 6860:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6861:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6862:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6863: 		       return '';
 6864:                    }
 6865:                }
 6866: 	   }
 6867:        }
 6868:     }
 6869:    
 6870: #
 6871: # Rest of the restrictions depend on selected course
 6872: #
 6873: 
 6874:     unless ($env{'request.course.id'}) {
 6875: 	if ($thisallowed eq 'A') {
 6876: 	    return 'A';
 6877:         } elsif ($thisallowed eq 'B') {
 6878:             return 'B';
 6879: 	} else {
 6880: 	    return '1';
 6881: 	}
 6882:     }
 6883: 
 6884: #
 6885: # Now user is definitely in a course
 6886: #
 6887: 
 6888: 
 6889: # Course preferences
 6890: 
 6891:    if ($thisallowed=~/C/) {
 6892:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6893:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6894:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6895: 	   =~/\Q$rolecode\E/) {
 6896: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6897: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6898: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6899: 			$env{'request.course.id'});
 6900: 	   }
 6901:            return '';
 6902:        }
 6903: 
 6904:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6905: 	   =~/\Q$unamedom\E/) {
 6906: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6907: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6908: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6909: 			$env{'request.course.id'});
 6910: 	   }
 6911:            return '';
 6912:        }
 6913:    }
 6914: 
 6915: # Resource preferences
 6916: 
 6917:    if ($thisallowed=~/R/) {
 6918:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6919:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6920: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6921: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6922: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6923: 	   }
 6924: 	   return '';
 6925:        }
 6926:    }
 6927: 
 6928: # Restricted by state or randomout?
 6929: 
 6930:    if ($thisallowed=~/X/) {
 6931:       if ($env{'acc.randomout'}) {
 6932: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6933:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6934:             return ''; 
 6935:          }
 6936:       }
 6937:       if (&condval($statecond)) {
 6938: 	 return '2';
 6939:       } else {
 6940:          return '';
 6941:       }
 6942:    }
 6943: 
 6944:     if ($thisallowed eq 'A') {
 6945: 	return 'A';
 6946:     } elsif ($thisallowed eq 'B') {
 6947:         return 'B';
 6948:     }
 6949:    return 'F';
 6950: }
 6951: 
 6952: # ------------------------------------------- Check construction space access
 6953: 
 6954: sub constructaccess {
 6955:     my ($url,$setpriv)=@_;
 6956: 
 6957: # We do not allow editing of previous versions of files
 6958:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6959: 
 6960: # Get username and domain from URL
 6961:     my ($ownername,$ownerdomain,$ownerhome);
 6962: 
 6963:     ($ownerdomain,$ownername) =
 6964:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6965: 
 6966: # The URL does not really point to any authorspace, forget it
 6967:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6968: 
 6969: # Now we need to see if the user has access to the authorspace of
 6970: # $ownername at $ownerdomain
 6971: 
 6972:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6973: # Real author for this?
 6974:        $ownerhome = $env{'user.home'};
 6975:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6976:           return ($ownername,$ownerdomain,$ownerhome);
 6977:        }
 6978:     } else {
 6979: # Co-author for this?
 6980:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6981:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6982:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6983:             return ($ownername,$ownerdomain,$ownerhome);
 6984:         }
 6985:     }
 6986: 
 6987: # We don't have any access right now. If we are not possibly going to do anything about this,
 6988: # we might as well leave
 6989:    unless ($setpriv) { return ''; }
 6990: 
 6991: # Backdoor access?
 6992:     my $allowed=&allowed('eco',$ownerdomain);
 6993: # Nope
 6994:     unless ($allowed) { return ''; }
 6995: # Looks like we may have access, but could be locked by the owner of the construction space
 6996:     if ($allowed eq 'U') {
 6997:         my %blocked=&get('environment',['domcoord.author'],
 6998:                          $ownerdomain,$ownername);
 6999: # Is blocked by owner
 7000:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7001:     }
 7002:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7003: # Grant temporary access
 7004:         my $then=$env{'user.login.time'};
 7005:         my $update=$env{'user.update.time'};
 7006:         if (!$update) { $update = $then; }
 7007:         my $refresh=$env{'user.refresh.time'};
 7008:         if (!$refresh) { $refresh = $update; }
 7009:         my $now = time;
 7010:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7011:                            $now,'ca','constructaccess');
 7012:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7013:         return($ownername,$ownerdomain,$ownerhome);
 7014:     }
 7015: # No business here
 7016:     return '';
 7017: }
 7018: 
 7019: sub get_comm_blocks {
 7020:     my ($cdom,$cnum) = @_;
 7021:     if ($cdom eq '' || $cnum eq '') {
 7022:         return unless ($env{'request.course.id'});
 7023:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7024:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7025:     }
 7026:     my %commblocks;
 7027:     my $hashid=$cdom.'_'.$cnum;
 7028:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7029:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7030:         %commblocks = %{$blocksref};
 7031:     } else {
 7032:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7033:         my $cachetime = 600;
 7034:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7035:     }
 7036:     return %commblocks;
 7037: }
 7038: 
 7039: sub has_comm_blocking {
 7040:     my ($priv,$symb,$uri,$blocks) = @_;
 7041:     return unless ($env{'request.course.id'});
 7042:     return unless ($priv eq 'bre');
 7043:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7044:     my %commblocks;
 7045:     if (ref($blocks) eq 'HASH') {
 7046:         %commblocks = %{$blocks};
 7047:     } else {
 7048:         %commblocks = &get_comm_blocks();
 7049:     }
 7050:     return unless (keys(%commblocks) > 0);
 7051:     if (!$symb) { $symb=&symbread($uri,1); }
 7052:     my ($map,$resid,undef)=&decode_symb($symb);
 7053:     my %tocheck = (
 7054:                     maps      => $map,
 7055:                     resources => $symb,
 7056:                   );
 7057:     my @blockers;
 7058:     my $now = time;
 7059:     my $navmap = Apache::lonnavmaps::navmap->new();
 7060:     foreach my $block (keys(%commblocks)) {
 7061:         if ($block =~ /^(\d+)____(\d+)$/) {
 7062:             my ($start,$end) = ($1,$2);
 7063:             if ($start <= $now && $end >= $now) {
 7064:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7065:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7066:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7067:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7068:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7069:                                     push(@blockers,$block);
 7070:                                 }
 7071:                             }
 7072:                         }
 7073:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7074:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7075:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7076:                                     push(@blockers,$block);
 7077:                                 }
 7078:                             }
 7079:                         }
 7080:                     }
 7081:                 }
 7082:             }
 7083:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7084:             my $item = $1;
 7085:             my @to_test;
 7086:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7087:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7088:                     my $check_interval;
 7089:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7090:                         my @interval;
 7091:                         my $type = 'map';
 7092:                         if ($item eq 'course') {
 7093:                             $type = 'course';
 7094:                             @interval=&EXT("resource.0.interval");
 7095:                         } else {
 7096:                             if ($item =~ /___\d+___/) {
 7097:                                 $type = 'resource';
 7098:                                 @interval=&EXT("resource.0.interval",$item);
 7099:                                 if (ref($navmap)) {                        
 7100:                                     my $res = $navmap->getBySymb($item); 
 7101:                                     push(@to_test,$res);
 7102:                                 }
 7103:                             } else {
 7104:                                 my $mapsymb = &symbread($item,1);
 7105:                                 if ($mapsymb) {
 7106:                                     if (ref($navmap)) {
 7107:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7108:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7109:                                         foreach my $res (@to_test) {
 7110:                                             my $symb = $res->symb();
 7111:                                             next if ($symb eq $mapsymb);
 7112:                                             if ($symb ne '') {
 7113:                                                 @interval=&EXT("resource.0.interval",$symb);
 7114:                                                 last;
 7115:                                             }
 7116:                                         }
 7117:                                     }
 7118:                                 }
 7119:                             }
 7120:                         }
 7121:                         if ($interval[0] =~ /\d+/) {
 7122:                             my $first_access;
 7123:                             if ($type eq 'resource') {
 7124:                                 $first_access=&get_first_access($interval[1],$item);
 7125:                             } elsif ($type eq 'map') {
 7126:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7127:                             } else {
 7128:                                 $first_access=&get_first_access($interval[1]);
 7129:                             }
 7130:                             if ($first_access) {
 7131:                                 my $timesup = $first_access+$interval[0];
 7132:                                 if ($timesup > $now) {
 7133:                                     foreach my $res (@to_test) {
 7134:                                         if ($res->is_problem()) {
 7135:                                             if ($res->completable()) {
 7136:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7137:                                                     push(@blockers,$block);
 7138:                                                 }
 7139:                                                 last;
 7140:                                             }
 7141:                                         }
 7142:                                     }
 7143:                                 }
 7144:                             }
 7145:                         }
 7146:                     }
 7147:                 }
 7148:             }
 7149:         }
 7150:     }
 7151:     return @blockers;
 7152: }
 7153: 
 7154: sub check_docs_block {
 7155:     my ($docsblock,$tocheck) =@_;
 7156:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7157:         return;
 7158:     }
 7159:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7160:         if ($tocheck->{'maps'}) {
 7161:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7162:                 return 1;
 7163:             }
 7164:         }
 7165:     }
 7166:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7167:         if ($tocheck->{'resources'}) {
 7168:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7169:                 return 1;
 7170:             }
 7171:         }
 7172:     }
 7173:     return;
 7174: }
 7175: 
 7176: #
 7177: #   Removes the versino from a URI and
 7178: #   splits it in to its filename and path to the filename.
 7179: #   Seems like File::Basename could have done this more clearly.
 7180: #   Parameters:
 7181: #      $uri   - input URI
 7182: #   Returns:
 7183: #     Two element list consisting of 
 7184: #     $pathname  - the URI up to and excluding the trailing /
 7185: #     $filename  - The part of the URI following the last /
 7186: #  NOTE:
 7187: #    Another realization of this is simply:
 7188: #    use File::Basename;
 7189: #    ...
 7190: #    $uri = shift;
 7191: #    $filename = basename($uri);
 7192: #    $path     = dirname($uri);
 7193: #    return ($filename, $path);
 7194: #
 7195: #     The implementation below is probably faster however.
 7196: #
 7197: sub split_uri_for_cond {
 7198:     my $uri=&deversion(&declutter(shift));
 7199:     my @uriparts=split(/\//,$uri);
 7200:     my $filename=pop(@uriparts);
 7201:     my $pathname=join('/',@uriparts);
 7202:     return ($pathname,$filename);
 7203: }
 7204: # --------------------------------------------------- Is a resource on the map?
 7205: 
 7206: sub is_on_map {
 7207:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7208:     #Trying to find the conditional for the file
 7209:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7210: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7211:     if ($match) {
 7212: 	return (1,$1);
 7213:     } else {
 7214: 	return (0,0);
 7215:     }
 7216: }
 7217: 
 7218: # --------------------------------------------------------- Get symb from alias
 7219: 
 7220: sub get_symb_from_alias {
 7221:     my $symb=shift;
 7222:     my ($map,$resid,$url)=&decode_symb($symb);
 7223: # Already is a symb
 7224:     if ($url) { return $symb; }
 7225: # Must be an alias
 7226:     my $aliassymb='';
 7227:     my %bighash;
 7228:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7229:                             &GDBM_READER(),0640)) {
 7230:         my $rid=$bighash{'mapalias_'.$symb};
 7231: 	if ($rid) {
 7232: 	    my ($mapid,$resid)=split(/\./,$rid);
 7233: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7234: 				    $resid,$bighash{'src_'.$rid});
 7235: 	}
 7236:         untie %bighash;
 7237:     }
 7238:     return $aliassymb;
 7239: }
 7240: 
 7241: # ----------------------------------------------------------------- Define Role
 7242: 
 7243: sub definerole {
 7244:   if (allowed('mcr','/')) {
 7245:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7246:     foreach my $role (split(':',$sysrole)) {
 7247: 	my ($crole,$cqual)=split(/\&/,$role);
 7248:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7249:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7250: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7251:                return "refused:s:$crole&$cqual"; 
 7252:             }
 7253:         }
 7254:     }
 7255:     foreach my $role (split(':',$domrole)) {
 7256: 	my ($crole,$cqual)=split(/\&/,$role);
 7257:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7258:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7259: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7260:                return "refused:d:$crole&$cqual"; 
 7261:             }
 7262:         }
 7263:     }
 7264:     foreach my $role (split(':',$courole)) {
 7265: 	my ($crole,$cqual)=split(/\&/,$role);
 7266:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7267:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7268: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7269:                return "refused:c:$crole&$cqual"; 
 7270:             }
 7271:         }
 7272:     }
 7273:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7274:                 "$env{'user.domain'}:$env{'user.name'}:".
 7275: 	        "rolesdef_$rolename=".
 7276:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7277:     return reply($command,$env{'user.home'});
 7278:   } else {
 7279:     return 'refused';
 7280:   }
 7281: }
 7282: 
 7283: # ---------------- Make a metadata query against the network of library servers
 7284: 
 7285: sub metadata_query {
 7286:     my ($query,$custom,$customshow,$server_array)=@_;
 7287:     my %rhash;
 7288:     my %libserv = &all_library();
 7289:     my @server_list = (defined($server_array) ? @$server_array
 7290:                                               : keys(%libserv) );
 7291:     for my $server (@server_list) {
 7292: 	unless ($custom or $customshow) {
 7293: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7294: 	    $rhash{$server}=$reply;
 7295: 	}
 7296: 	else {
 7297: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7298: 			     &escape($custom).':'.&escape($customshow),
 7299: 			     $server);
 7300: 	    $rhash{$server}=$reply;
 7301: 	}
 7302:     }
 7303:     return \%rhash;
 7304: }
 7305: 
 7306: # ----------------------------------------- Send log queries and wait for reply
 7307: 
 7308: sub log_query {
 7309:     my ($uname,$udom,$query,%filters)=@_;
 7310:     my $uhome=&homeserver($uname,$udom);
 7311:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7312:     my $uhost=&hostname($uhome);
 7313:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7314:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7315:                        $uhome);
 7316:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7317:     return get_query_reply($queryid);
 7318: }
 7319: 
 7320: # -------------------------- Update MySQL table for portfolio file
 7321: 
 7322: sub update_portfolio_table {
 7323:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7324:     if ($group ne '') {
 7325:         $file_name =~s /^\Q$group\E//;
 7326:     }
 7327:     my $homeserver = &homeserver($uname,$udom);
 7328:     my $queryid=
 7329:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7330:                ':'.&escape($file_name).':'.$action,$homeserver);
 7331:     my $reply = &get_query_reply($queryid);
 7332:     return $reply;
 7333: }
 7334: 
 7335: # -------------------------- Update MySQL allusers table
 7336: 
 7337: sub update_allusers_table {
 7338:     my ($uname,$udom,$names) = @_;
 7339:     my $homeserver = &homeserver($uname,$udom);
 7340:     my $queryid=
 7341:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7342:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7343:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7344:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7345:                'generation='.&escape($names->{'generation'}).'%%'.
 7346:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7347:                'id='.&escape($names->{'id'}),$homeserver);
 7348:     return;
 7349: }
 7350: 
 7351: # ------- Request retrieval of institutional classlists for course(s)
 7352: 
 7353: sub fetch_enrollment_query {
 7354:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7355:     my $homeserver;
 7356:     my $maxtries = 1;
 7357:     if ($context eq 'automated') {
 7358:         $homeserver = $perlvar{'lonHostID'};
 7359:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7360:     } else {
 7361:         $homeserver = &homeserver($cnum,$dom);
 7362:     }
 7363:     my $host=&hostname($homeserver);
 7364:     my $cmd = '';
 7365:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7366:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7367:     }
 7368:     $cmd =~ s/%%$//;
 7369:     $cmd = &escape($cmd);
 7370:     my $query = 'fetchenrollment';
 7371:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7372:     unless ($queryid=~/^\Q$host\E\_/) { 
 7373:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7374:         return 'error: '.$queryid;
 7375:     }
 7376:     my $reply = &get_query_reply($queryid);
 7377:     my $tries = 1;
 7378:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7379:         $reply = &get_query_reply($queryid);
 7380:         $tries ++;
 7381:     }
 7382:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7383:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7384:     } else {
 7385:         my @responses = split(/:/,$reply);
 7386:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7387:             foreach my $line (@responses) {
 7388:                 my ($key,$value) = split(/=/,$line,2);
 7389:                 $$replyref{$key} = $value;
 7390:             }
 7391:         } else {
 7392:             my $pathname = LONCAPA::tempdir();
 7393:             foreach my $line (@responses) {
 7394:                 my ($key,$value) = split(/=/,$line);
 7395:                 $$replyref{$key} = $value;
 7396:                 if ($value > 0) {
 7397:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7398:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7399:                         my $destname = $pathname.'/'.$filename;
 7400:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7401:                         if ($xml_classlist =~ /^error/) {
 7402:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7403:                         } else {
 7404:                             if ( open(FILE,">$destname") ) {
 7405:                                 print FILE &unescape($xml_classlist);
 7406:                                 close(FILE);
 7407:                             } else {
 7408:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7409:                             }
 7410:                         }
 7411:                     }
 7412:                 }
 7413:             }
 7414:         }
 7415:         return 'ok';
 7416:     }
 7417:     return 'error';
 7418: }
 7419: 
 7420: sub get_query_reply {
 7421:     my $queryid=shift;
 7422:     my $replyfile=LONCAPA::tempdir().$queryid;
 7423:     my $reply='';
 7424:     for (1..100) {
 7425: 	sleep 2;
 7426:         if (-e $replyfile.'.end') {
 7427: 	    if (open(my $fh,$replyfile)) {
 7428: 		$reply = join('',<$fh>);
 7429: 		close($fh);
 7430: 	   } else { return 'error: reply_file_error'; }
 7431:            return &unescape($reply);
 7432: 	}
 7433:     }
 7434:     return 'timeout:'.$queryid;
 7435: }
 7436: 
 7437: sub courselog_query {
 7438: #
 7439: # possible filters:
 7440: # url: url or symb
 7441: # username
 7442: # domain
 7443: # action: view, submit, grade
 7444: # start: timestamp
 7445: # end: timestamp
 7446: #
 7447:     my (%filters)=@_;
 7448:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7449:     if ($filters{'url'}) {
 7450: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7451:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7452:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7453:     }
 7454:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7455:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7456:     return &log_query($cname,$cdom,'courselog',%filters);
 7457: }
 7458: 
 7459: sub userlog_query {
 7460: #
 7461: # possible filters:
 7462: # action: log check role
 7463: # start: timestamp
 7464: # end: timestamp
 7465: #
 7466:     my ($uname,$udom,%filters)=@_;
 7467:     return &log_query($uname,$udom,'userlog',%filters);
 7468: }
 7469: 
 7470: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7471: 
 7472: sub auto_run {
 7473:     my ($cnum,$cdom) = @_;
 7474:     my $response = 0;
 7475:     my $settings;
 7476:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7477:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7478:         $settings = $domconfig{'autoenroll'};
 7479:         if ($settings->{'run'} eq '1') {
 7480:             $response = 1;
 7481:         }
 7482:     } else {
 7483:         my $homeserver;
 7484:         if (&is_course($cdom,$cnum)) {
 7485:             $homeserver = &homeserver($cnum,$cdom);
 7486:         } else {
 7487:             $homeserver = &domain($cdom,'primary');
 7488:         }
 7489:         if ($homeserver ne 'no_host') {
 7490:             $response = &reply('autorun:'.$cdom,$homeserver);
 7491:         }
 7492:     }
 7493:     return $response;
 7494: }
 7495: 
 7496: sub auto_get_sections {
 7497:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7498:     my $homeserver;
 7499:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7500:         $homeserver = &homeserver($cnum,$cdom);
 7501:     }
 7502:     if (!defined($homeserver)) { 
 7503:         if ($cdom =~ /^$match_domain$/) {
 7504:             $homeserver = &domain($cdom,'primary');
 7505:         }
 7506:     }
 7507:     my @secs;
 7508:     if (defined($homeserver)) {
 7509:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7510:         unless ($response eq 'refused') {
 7511:             @secs = split(/:/,$response);
 7512:         }
 7513:     }
 7514:     return @secs;
 7515: }
 7516: 
 7517: sub auto_new_course {
 7518:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7519:     my $homeserver = &homeserver($cnum,$cdom);
 7520:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7521:     return $response;
 7522: }
 7523: 
 7524: sub auto_validate_courseID {
 7525:     my ($cnum,$cdom,$inst_course_id) = @_;
 7526:     my $homeserver = &homeserver($cnum,$cdom);
 7527:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7528:     return $response;
 7529: }
 7530: 
 7531: sub auto_validate_instcode {
 7532:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7533:     my ($homeserver,$response);
 7534:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7535:         $homeserver = &homeserver($cnum,$cdom);
 7536:     }
 7537:     if (!defined($homeserver)) {
 7538:         if ($cdom =~ /^$match_domain$/) {
 7539:             $homeserver = &domain($cdom,'primary');
 7540:         }
 7541:     }
 7542:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7543:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7544:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7545:     return ($outcome,$description,$defaultcredits);
 7546: }
 7547: 
 7548: sub auto_create_password {
 7549:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7550:     my ($homeserver,$response);
 7551:     my $create_passwd = 0;
 7552:     my $authchk = '';
 7553:     if ($udom =~ /^$match_domain$/) {
 7554:         $homeserver = &domain($udom,'primary');
 7555:     }
 7556:     if ($homeserver eq '') {
 7557:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7558:             $homeserver = &homeserver($cnum,$cdom);
 7559:         }
 7560:     }
 7561:     if ($homeserver eq '') {
 7562:         $authchk = 'nodomain';
 7563:     } else {
 7564:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7565:         if ($response eq 'refused') {
 7566:             $authchk = 'refused';
 7567:         } else {
 7568:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7569:         }
 7570:     }
 7571:     return ($authparam,$create_passwd,$authchk);
 7572: }
 7573: 
 7574: sub auto_photo_permission {
 7575:     my ($cnum,$cdom,$students) = @_;
 7576:     my $homeserver = &homeserver($cnum,$cdom);
 7577:     my ($outcome,$perm_reqd,$conditions) = 
 7578: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7579:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7580: 	return (undef,undef);
 7581:     }
 7582:     return ($outcome,$perm_reqd,$conditions);
 7583: }
 7584: 
 7585: sub auto_checkphotos {
 7586:     my ($uname,$udom,$pid) = @_;
 7587:     my $homeserver = &homeserver($uname,$udom);
 7588:     my ($result,$resulttype);
 7589:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7590: 				   &escape($uname).':'.&escape($pid),
 7591: 				   $homeserver));
 7592:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7593: 	return (undef,undef);
 7594:     }
 7595:     if ($outcome) {
 7596:         ($result,$resulttype) = split(/:/,$outcome);
 7597:     } 
 7598:     return ($result,$resulttype);
 7599: }
 7600: 
 7601: sub auto_photochoice {
 7602:     my ($cnum,$cdom) = @_;
 7603:     my $homeserver = &homeserver($cnum,$cdom);
 7604:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7605: 						       &escape($cdom),
 7606: 						       $homeserver)));
 7607:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7608: 	return (undef,undef);
 7609:     }
 7610:     return ($update,$comment);
 7611: }
 7612: 
 7613: sub auto_photoupdate {
 7614:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7615:     my $homeserver = &homeserver($cnum,$dom);
 7616:     my $host=&hostname($homeserver);
 7617:     my $cmd = '';
 7618:     my $maxtries = 1;
 7619:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7620:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7621:     }
 7622:     $cmd =~ s/%%$//;
 7623:     $cmd = &escape($cmd);
 7624:     my $query = 'institutionalphotos';
 7625:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7626:     unless ($queryid=~/^\Q$host\E\_/) {
 7627:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7628:         return 'error: '.$queryid;
 7629:     }
 7630:     my $reply = &get_query_reply($queryid);
 7631:     my $tries = 1;
 7632:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7633:         $reply = &get_query_reply($queryid);
 7634:         $tries ++;
 7635:     }
 7636:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7637:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7638:     } else {
 7639:         my @responses = split(/:/,$reply);
 7640:         my $outcome = shift(@responses); 
 7641:         foreach my $item (@responses) {
 7642:             my ($key,$value) = split(/=/,$item);
 7643:             $$photo{$key} = $value;
 7644:         }
 7645:         return $outcome;
 7646:     }
 7647:     return 'error';
 7648: }
 7649: 
 7650: sub auto_instcode_format {
 7651:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7652: 	$cat_order) = @_;
 7653:     my $courses = '';
 7654:     my @homeservers;
 7655:     if ($caller eq 'global') {
 7656: 	my %servers = &get_servers($codedom,'library');
 7657: 	foreach my $tryserver (keys(%servers)) {
 7658: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7659: 		push(@homeservers,$tryserver);
 7660: 	    }
 7661:         }
 7662:     } elsif ($caller eq 'requests') {
 7663:         if ($codedom =~ /^$match_domain$/) {
 7664:             my $chome = &domain($codedom,'primary');
 7665:             unless ($chome eq 'no_host') {
 7666:                 push(@homeservers,$chome);
 7667:             }
 7668:         }
 7669:     } else {
 7670:         push(@homeservers,&homeserver($caller,$codedom));
 7671:     }
 7672:     foreach my $code (keys(%{$instcodes})) {
 7673:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7674:     }
 7675:     chop($courses);
 7676:     my $ok_response = 0;
 7677:     my $response;
 7678:     while (@homeservers > 0 && $ok_response == 0) {
 7679:         my $server = shift(@homeservers); 
 7680:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7681:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7682:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7683: 		split(/:/,$response);
 7684:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7685:             push(@{$codetitles},&str2array($codetitles_str));
 7686:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7687:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7688:             $ok_response = 1;
 7689:         }
 7690:     }
 7691:     if ($ok_response) {
 7692:         return 'ok';
 7693:     } else {
 7694:         return $response;
 7695:     }
 7696: }
 7697: 
 7698: sub auto_instcode_defaults {
 7699:     my ($domain,$returnhash,$code_order) = @_;
 7700:     my @homeservers;
 7701: 
 7702:     my %servers = &get_servers($domain,'library');
 7703:     foreach my $tryserver (keys(%servers)) {
 7704: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7705: 	    push(@homeservers,$tryserver);
 7706: 	}
 7707:     }
 7708: 
 7709:     my $response;
 7710:     foreach my $server (@homeservers) {
 7711:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7712:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7713: 	
 7714: 	foreach my $pair (split(/\&/,$response)) {
 7715: 	    my ($name,$value)=split(/\=/,$pair);
 7716: 	    if ($name eq 'code_order') {
 7717: 		@{$code_order} = split(/\&/,&unescape($value));
 7718: 	    } else {
 7719: 		$returnhash->{&unescape($name)}=&unescape($value);
 7720: 	    }
 7721: 	}
 7722: 	return 'ok';
 7723:     }
 7724: 
 7725:     return $response;
 7726: }
 7727: 
 7728: sub auto_possible_instcodes {
 7729:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7730:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7731:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7732:         return;
 7733:     }
 7734:     my (@homeservers,$uhome);
 7735:     if (defined(&domain($domain,'primary'))) {
 7736:         $uhome=&domain($domain,'primary');
 7737:         push(@homeservers,&domain($domain,'primary'));
 7738:     } else {
 7739:         my %servers = &get_servers($domain,'library');
 7740:         foreach my $tryserver (keys(%servers)) {
 7741:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7742:                 push(@homeservers,$tryserver);
 7743:             }
 7744:         }
 7745:     }
 7746:     my $response;
 7747:     foreach my $server (@homeservers) {
 7748:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7749:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7750:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7751:             split(':',$response);
 7752:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7753:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7754:         foreach my $item (split('&',$cat_title)) {   
 7755:             my ($name,$value)=split('=',$item);
 7756:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7757:         }
 7758:         foreach my $item (split('&',$cat_order)) {
 7759:             my ($name,$value)=split('=',$item);
 7760:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7761:         }
 7762:         return 'ok';
 7763:     }
 7764:     return $response;
 7765: }
 7766: 
 7767: sub auto_courserequest_checks {
 7768:     my ($dom) = @_;
 7769:     my ($homeserver,%validations);
 7770:     if ($dom =~ /^$match_domain$/) {
 7771:         $homeserver = &domain($dom,'primary');
 7772:     }
 7773:     unless ($homeserver eq 'no_host') {
 7774:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7775:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7776:             my @items = split(/&/,$response);
 7777:             foreach my $item (@items) {
 7778:                 my ($key,$value) = split('=',$item);
 7779:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7780:             }
 7781:         }
 7782:     }
 7783:     return %validations; 
 7784: }
 7785: 
 7786: sub auto_courserequest_validation {
 7787:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7788:     my ($homeserver,$response);
 7789:     if ($dom =~ /^$match_domain$/) {
 7790:         $homeserver = &domain($dom,'primary');
 7791:     }
 7792:     unless ($homeserver eq 'no_host') {  
 7793:           
 7794:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7795:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7796:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7797:                                     $homeserver));
 7798:     }
 7799:     return $response;
 7800: }
 7801: 
 7802: sub auto_validate_class_sec {
 7803:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7804:     my $homeserver = &homeserver($cnum,$cdom);
 7805:     my $ownerlist;
 7806:     if (ref($owners) eq 'ARRAY') {
 7807:         $ownerlist = join(',',@{$owners});
 7808:     } else {
 7809:         $ownerlist = $owners;
 7810:     }
 7811:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7812:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7813:     return $response;
 7814: }
 7815: 
 7816: # ------------------------------------------------------- Course Group routines
 7817: 
 7818: sub get_coursegroups {
 7819:     my ($cdom,$cnum,$group,$namespace) = @_;
 7820:     return(&dump($namespace,$cdom,$cnum,$group));
 7821: }
 7822: 
 7823: sub modify_coursegroup {
 7824:     my ($cdom,$cnum,$groupsettings) = @_;
 7825:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7826: }
 7827: 
 7828: sub toggle_coursegroup_status {
 7829:     my ($cdom,$cnum,$group,$action) = @_;
 7830:     my ($from_namespace,$to_namespace);
 7831:     if ($action eq 'delete') {
 7832:         $from_namespace = 'coursegroups';
 7833:         $to_namespace = 'deleted_groups';
 7834:     } else {
 7835:         $from_namespace = 'deleted_groups';
 7836:         $to_namespace = 'coursegroups';
 7837:     }
 7838:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7839:     if (my $tmp = &error(%curr_group)) {
 7840:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7841:         return ('read error',$tmp);
 7842:     } else {
 7843:         my %savedsettings = %curr_group; 
 7844:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7845:         my $deloutcome;
 7846:         if ($result eq 'ok') {
 7847:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7848:         } else {
 7849:             return ('write error',$result);
 7850:         }
 7851:         if ($deloutcome eq 'ok') {
 7852:             return 'ok';
 7853:         } else {
 7854:             return ('delete error',$deloutcome);
 7855:         }
 7856:     }
 7857: }
 7858: 
 7859: sub modify_group_roles {
 7860:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7861:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7862:     my $role = 'gr/'.&escape($userprivs);
 7863:     my ($uname,$udom) = split(/:/,$user);
 7864:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7865:     if ($result eq 'ok') {
 7866:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7867:     }
 7868:     return $result;
 7869: }
 7870: 
 7871: sub modify_coursegroup_membership {
 7872:     my ($cdom,$cnum,$membership) = @_;
 7873:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7874:     return $result;
 7875: }
 7876: 
 7877: sub get_active_groups {
 7878:     my ($udom,$uname,$cdom,$cnum) = @_;
 7879:     my $now = time;
 7880:     my %groups = ();
 7881:     foreach my $key (keys(%env)) {
 7882:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7883:             my ($start,$end) = split(/\./,$env{$key});
 7884:             if (($end!=0) && ($end<$now)) { next; }
 7885:             if (($start!=0) && ($start>$now)) { next; }
 7886:             if ($1 eq $cdom && $2 eq $cnum) {
 7887:                 $groups{$3} = $env{$key} ;
 7888:             }
 7889:         }
 7890:     }
 7891:     return %groups;
 7892: }
 7893: 
 7894: sub get_group_membership {
 7895:     my ($cdom,$cnum,$group) = @_;
 7896:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7897: }
 7898: 
 7899: sub get_users_groups {
 7900:     my ($udom,$uname,$courseid) = @_;
 7901:     my @usersgroups;
 7902:     my $cachetime=1800;
 7903: 
 7904:     my $hashid="$udom:$uname:$courseid";
 7905:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7906:     if (defined($cached)) {
 7907:         @usersgroups = split(/:/,$grouplist);
 7908:     } else {  
 7909:         $grouplist = '';
 7910:         my $courseurl = &courseid_to_courseurl($courseid);
 7911:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7912:         my $access_end = $env{'course.'.$courseid.
 7913:                               '.default_enrollment_end_date'};
 7914:         my $now = time;
 7915:         foreach my $key (keys(%roleshash)) {
 7916:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7917:                 my $group = $1;
 7918:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7919:                     my $start = $2;
 7920:                     my $end = $1;
 7921:                     if ($start == -1) { next; } # deleted from group
 7922:                     if (($start!=0) && ($start>$now)) { next; }
 7923:                     if (($end!=0) && ($end<$now)) {
 7924:                         if ($access_end && $access_end < $now) {
 7925:                             if ($access_end - $end < 86400) {
 7926:                                 push(@usersgroups,$group);
 7927:                             }
 7928:                         }
 7929:                         next;
 7930:                     }
 7931:                     push(@usersgroups,$group);
 7932:                 }
 7933:             }
 7934:         }
 7935:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7936:         $grouplist = join(':',@usersgroups);
 7937:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7938:     }
 7939:     return @usersgroups;
 7940: }
 7941: 
 7942: sub devalidate_getgroups_cache {
 7943:     my ($udom,$uname,$cdom,$cnum)=@_;
 7944:     my $courseid = $cdom.'_'.$cnum;
 7945: 
 7946:     my $hashid="$udom:$uname:$courseid";
 7947:     &devalidate_cache_new('getgroups',$hashid);
 7948: }
 7949: 
 7950: # ------------------------------------------------------------------ Plain Text
 7951: 
 7952: sub plaintext {
 7953:     my ($short,$type,$cid,$forcedefault) = @_;
 7954:     if ($short =~ m{^cr/}) {
 7955: 	return (split('/',$short))[-1];
 7956:     }
 7957:     if (!defined($cid)) {
 7958:         $cid = $env{'request.course.id'};
 7959:     }
 7960:     my %rolenames = (
 7961:                       Course    => 'std',
 7962:                       Community => 'alt1',
 7963:                     );
 7964:     if ($cid ne '') {
 7965:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7966:             unless ($forcedefault) {
 7967:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7968:                 &Apache::lonlocal::mt_escape(\$roletext);
 7969:                 return &Apache::lonlocal::mt($roletext);
 7970:             }
 7971:         }
 7972:     }
 7973:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7974:         (defined($rolenames{$type})) && 
 7975:         (defined($prp{$short}{$rolenames{$type}}))) {
 7976:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7977:     } elsif ($cid ne '') {
 7978:         my $crstype = $env{'course.'.$cid.'.type'};
 7979:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7980:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7981:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7982:         }
 7983:     }
 7984:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7985: }
 7986: 
 7987: # ----------------------------------------------------------------- Assign Role
 7988: 
 7989: sub assignrole {
 7990:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7991:         $context)=@_;
 7992:     my $mrole;
 7993:     if ($role =~ /^cr\//) {
 7994:         my $cwosec=$url;
 7995:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7996: 	unless (&allowed('ccr',$cwosec)) {
 7997:            my $refused = 1;
 7998:            if ($context eq 'requestcourses') {
 7999:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8000:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8001:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8002:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8003:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8004:                            if ($crsenv{'internal.courseowner'} eq
 8005:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8006:                                $refused = '';
 8007:                            }
 8008:                        }
 8009:                    }
 8010:                }
 8011:            }
 8012:            if ($refused) {
 8013:                &logthis('Refused custom assignrole: '.
 8014:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8015:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8016:                return 'refused';
 8017:            }
 8018:         }
 8019:         $mrole='cr';
 8020:     } elsif ($role =~ /^gr\//) {
 8021:         my $cwogrp=$url;
 8022:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8023:         unless (&allowed('mdg',$cwogrp)) {
 8024:             &logthis('Refused group assignrole: '.
 8025:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8026:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8027:             return 'refused';
 8028:         }
 8029:         $mrole='gr';
 8030:     } else {
 8031:         my $cwosec=$url;
 8032:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8033:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8034:             my $refused;
 8035:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8036:                 if (!(&allowed('c'.$role,$url))) {
 8037:                     $refused = 1;
 8038:                 }
 8039:             } else {
 8040:                 $refused = 1;
 8041:             }
 8042:             if ($refused) {
 8043:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8044:                 if (!$selfenroll && $context eq 'course') {
 8045:                     my %crsenv;
 8046:                     if ($role eq 'cc' || $role eq 'co') {
 8047:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8048:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8049:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8050:                                 if ($crsenv{'internal.courseowner'} eq 
 8051:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8052:                                     $refused = '';
 8053:                                 }
 8054:                             }
 8055:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8056:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8057:                                 if ($crsenv{'internal.courseowner'} eq 
 8058:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8059:                                     $refused = '';
 8060:                                 }
 8061:                             }
 8062:                         }
 8063:                     }
 8064:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8065:                     $refused = '';
 8066:                 } elsif ($context eq 'requestcourses') {
 8067:                     my @possroles = ('st','ta','ep','in','cc','co');
 8068:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8069:                         my $wrongcc;
 8070:                         if ($cnum =~ /^$match_community$/) {
 8071:                             $wrongcc = 1 if ($role eq 'cc');
 8072:                         } else {
 8073:                             $wrongcc = 1 if ($role eq 'co');
 8074:                         }
 8075:                         unless ($wrongcc) {
 8076:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8077:                             if ($crsenv{'internal.courseowner'} eq 
 8078:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8079:                                 $refused = '';
 8080:                             }
 8081:                         }
 8082:                     }
 8083:                 } elsif ($context eq 'requestauthor') {
 8084:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8085:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8086:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8087:                             $refused = '';
 8088:                         } else {
 8089:                             my %domdefaults = &get_domain_defaults($udom);
 8090:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8091:                                 my $checkbystatus;
 8092:                                 if ($env{'user.adv'}) { 
 8093:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8094:                                     if ($disposition eq 'automatic') {
 8095:                                         $refused = '';
 8096:                                     } elsif ($disposition eq '') {
 8097:                                         $checkbystatus = 1;
 8098:                                     } 
 8099:                                 } else {
 8100:                                     $checkbystatus = 1;
 8101:                                 }
 8102:                                 if ($checkbystatus) {
 8103:                                     if ($env{'environment.inststatus'}) {
 8104:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8105:                                         foreach my $type (@inststatuses) {
 8106:                                             if (($type ne '') &&
 8107:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8108:                                                 $refused = '';
 8109:                                             }
 8110:                                         }
 8111:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8112:                                         $refused = '';
 8113:                                     }
 8114:                                 }
 8115:                             }
 8116:                         }
 8117:                     }
 8118:                 }
 8119:                 if ($refused) {
 8120:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8121:                              ' '.$role.' '.$end.' '.$start.' by '.
 8122: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8123:                     return 'refused';
 8124:                 }
 8125:             }
 8126:         } elsif ($role eq 'au') {
 8127:             if ($url ne '/'.$udom.'/') {
 8128:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8129:                          ' to assign author role for '.$uname.':'.$udom.
 8130:                          ' in domain: '.$url.' refused (wrong domain).');
 8131:                 return 'refused';
 8132:             }
 8133:         }
 8134:         $mrole=$role;
 8135:     }
 8136:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8137:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8138:     if ($end) { $command.='_'.$end; }
 8139:     if ($start) {
 8140: 	if ($end) { 
 8141:            $command.='_'.$start; 
 8142:         } else {
 8143:            $command.='_0_'.$start;
 8144:         }
 8145:     }
 8146:     my $origstart = $start;
 8147:     my $origend = $end;
 8148:     my $delflag;
 8149: # actually delete
 8150:     if ($deleteflag) {
 8151: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8152: # modify command to delete the role
 8153:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8154:                 "$udom:$uname:$url".'_'."$mrole";
 8155: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8156: # set start and finish to negative values for userrolelog
 8157:            $start=-1;
 8158:            $end=-1;
 8159:            $delflag = 1;
 8160:         }
 8161:     }
 8162: # send command
 8163:     my $answer=&reply($command,&homeserver($uname,$udom));
 8164: # log new user role if status is ok
 8165:     if ($answer eq 'ok') {
 8166: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8167:         if (($role eq 'cc') || ($role eq 'in') ||
 8168:             ($role eq 'ep') || ($role eq 'ad') ||
 8169:             ($role eq 'ta') || ($role eq 'st') ||
 8170:             ($role=~/^cr/) || ($role eq 'gr') ||
 8171:             ($role eq 'co')) {
 8172: # for course roles, perform group memberships changes triggered by role change.
 8173:             unless ($role =~ /^gr/) {
 8174:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8175:                                                  $origstart,$selfenroll,$context);
 8176:             }
 8177:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8178:                            $selfenroll,$context);
 8179:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8180:                  ($role eq 'au') || ($role eq 'dc')) {
 8181:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8182:                            $context);
 8183:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8184:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8185:                              $context); 
 8186:         }
 8187:         if ($role eq 'cc') {
 8188:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8189:         }
 8190:     }
 8191:     return $answer;
 8192: }
 8193: 
 8194: sub autoupdate_coowners {
 8195:     my ($url,$end,$start,$uname,$udom) = @_;
 8196:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8197:     if (($cdom ne '') && ($cnum ne '')) {
 8198:         my $now = time;
 8199:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8200:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8201:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8202:             my $instcode = $coursehash{'internal.coursecode'};
 8203:             if ($instcode ne '') {
 8204:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8205:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8206:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8207:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8208:                         if ($result eq 'valid') {
 8209:                             if ($coursehash{'internal.co-owners'}) {
 8210:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8211:                                     push(@newcoowners,$coowner);
 8212:                                 }
 8213:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8214:                                     push(@newcoowners,$uname.':'.$udom);
 8215:                                 }
 8216:                                 @newcoowners = sort(@newcoowners);
 8217:                             } else {
 8218:                                 push(@newcoowners,$uname.':'.$udom);
 8219:                             }
 8220:                         } else {
 8221:                             if ($coursehash{'internal.co-owners'}) {
 8222:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8223:                                     unless ($coowner eq $uname.':'.$udom) {
 8224:                                         push(@newcoowners,$coowner);
 8225:                                     }
 8226:                                 }
 8227:                                 unless (@newcoowners > 0) {
 8228:                                     $delcoowners = 1;
 8229:                                     $coowners = '';
 8230:                                 }
 8231:                             }
 8232:                         }
 8233:                         if (@newcoowners || $delcoowners) {
 8234:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8235:                                             $delcoowners,@newcoowners);
 8236:                         }
 8237:                     }
 8238:                 }
 8239:             }
 8240:         }
 8241:     }
 8242: }
 8243: 
 8244: sub store_coowners {
 8245:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8246:     my $cid = $cdom.'_'.$cnum;
 8247:     my ($coowners,$delresult,$putresult);
 8248:     if (@newcoowners) {
 8249:         $coowners = join(',',@newcoowners);
 8250:         my %coownershash = (
 8251:                             'internal.co-owners' => $coowners,
 8252:                            );
 8253:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8254:         if ($putresult eq 'ok') {
 8255:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8256:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8257:             }
 8258:         }
 8259:     }
 8260:     if ($delcoowners) {
 8261:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8262:         if ($delresult eq 'ok') {
 8263:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8264:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8265:             }
 8266:         }
 8267:     }
 8268:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8269:         my %crsinfo =
 8270:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8271:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8272:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8273:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8274:         }
 8275:     }
 8276: }
 8277: 
 8278: # -------------------------------------------------- Modify user authentication
 8279: # Overrides without validation
 8280: 
 8281: sub modifyuserauth {
 8282:     my ($udom,$uname,$umode,$upass)=@_;
 8283:     my $uhome=&homeserver($uname,$udom);
 8284:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8285:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8286:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8287:              ' in domain '.$env{'request.role.domain'});  
 8288:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8289: 		     &escape($upass),$uhome);
 8290:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8291:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8292:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8293:     &log($udom,,$uname,$uhome,
 8294:         'Authentication changed by '.$env{'user.domain'}.', '.
 8295:                                      $env{'user.name'}.', '.$umode.
 8296:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8297:     unless ($reply eq 'ok') {
 8298:         &logthis('Authentication mode error: '.$reply);
 8299: 	return 'error: '.$reply;
 8300:     }   
 8301:     return 'ok';
 8302: }
 8303: 
 8304: # --------------------------------------------------------------- Modify a user
 8305: 
 8306: sub modifyuser {
 8307:     my ($udom,    $uname, $uid,
 8308:         $umode,   $upass, $first,
 8309:         $middle,  $last,  $gene,
 8310:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8311:     $udom= &LONCAPA::clean_domain($udom);
 8312:     $uname=&LONCAPA::clean_username($uname);
 8313:     my $showcandelete = 'none';
 8314:     if (ref($candelete) eq 'ARRAY') {
 8315:         if (@{$candelete} > 0) {
 8316:             $showcandelete = join(', ',@{$candelete});
 8317:         }
 8318:     }
 8319:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8320:              $umode.', '.$first.', '.$middle.', '.
 8321: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8322:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8323:                                      ' desiredhome not specified'). 
 8324:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8325:              ' in domain '.$env{'request.role.domain'});
 8326:     my $uhome=&homeserver($uname,$udom,'true');
 8327:     my $newuser;
 8328:     if ($uhome eq 'no_host') {
 8329:         $newuser = 1;
 8330:     }
 8331: # ----------------------------------------------------------------- Create User
 8332:     if (($uhome eq 'no_host') && 
 8333: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8334:         my $unhome='';
 8335:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8336:             $unhome = $desiredhome;
 8337: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8338: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8339:         } else { # load balancing routine for determining $unhome
 8340:             my $loadm=10000000;
 8341: 	    my %servers = &get_servers($udom,'library');
 8342: 	    foreach my $tryserver (keys(%servers)) {
 8343: 		my $answer=reply('load',$tryserver);
 8344: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8345: 		    $loadm=$answer;
 8346: 		    $unhome=$tryserver;
 8347: 		}
 8348: 	    }
 8349:         }
 8350:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8351: 	    return 'error: unable to find a home server for '.$uname.
 8352:                    ' in domain '.$udom;
 8353:         }
 8354:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8355:                          &escape($upass),$unhome);
 8356: 	unless ($reply eq 'ok') {
 8357:             return 'error: '.$reply;
 8358:         }   
 8359:         $uhome=&homeserver($uname,$udom,'true');
 8360:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8361: 	    return 'error: unable verify users home machine.';
 8362:         }
 8363:     }   # End of creation of new user
 8364: # ---------------------------------------------------------------------- Add ID
 8365:     if ($uid) {
 8366:        $uid=~tr/A-Z/a-z/;
 8367:        my %uidhash=&idrget($udom,$uname);
 8368:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8369:          && (!$forceid)) {
 8370: 	  unless ($uid eq $uidhash{$uname}) {
 8371: 	      return 'error: user id "'.$uid.'" does not match '.
 8372:                   'current user id "'.$uidhash{$uname}.'".';
 8373:           }
 8374:        } else {
 8375: 	  &idput($udom,($uname => $uid));
 8376:        }
 8377:     }
 8378: # -------------------------------------------------------------- Add names, etc
 8379:     my @tmp=&get('environment',
 8380: 		   ['firstname','middlename','lastname','generation','id',
 8381:                     'permanentemail','inststatus'],
 8382: 		   $udom,$uname);
 8383:     my (%names,%oldnames);
 8384:     if ($tmp[0] =~ m/^error:.*/) { 
 8385:         %names=(); 
 8386:     } else {
 8387:         %names = @tmp;
 8388:         %oldnames = %names;
 8389:     }
 8390: #
 8391: # If name, email and/or uid are blank (e.g., because an uploaded file
 8392: # of users did not contain them), do not overwrite existing values
 8393: # unless field is in $candelete array ref.  
 8394: #
 8395: 
 8396:     my @fields = ('firstname','middlename','lastname','generation',
 8397:                   'permanentemail','id');
 8398:     my %newvalues;
 8399:     if (ref($candelete) eq 'ARRAY') {
 8400:         foreach my $field (@fields) {
 8401:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8402:                 if ($field eq 'firstname') {
 8403:                     $names{$field} = $first;
 8404:                 } elsif ($field eq 'middlename') {
 8405:                     $names{$field} = $middle;
 8406:                 } elsif ($field eq 'lastname') {
 8407:                     $names{$field} = $last;
 8408:                 } elsif ($field eq 'generation') { 
 8409:                     $names{$field} = $gene;
 8410:                 } elsif ($field eq 'permanentemail') {
 8411:                     $names{$field} = $email;
 8412:                 } elsif ($field eq 'id') {
 8413:                     $names{$field}  = $uid;
 8414:                 }
 8415:             }
 8416:         }
 8417:     }
 8418:     if ($first)  { $names{'firstname'}  = $first; }
 8419:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8420:     if ($last)   { $names{'lastname'}   = $last; }
 8421:     if (defined($gene))   { $names{'generation'} = $gene; }
 8422:     if ($email) {
 8423:        $email=~s/[^\w\@\.\-\,]//gs;
 8424:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8425:     }
 8426:     if ($uid) { $names{'id'}  = $uid; }
 8427:     if (defined($inststatus)) {
 8428:         $names{'inststatus'} = '';
 8429:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8430:         if (ref($usertypes) eq 'HASH') {
 8431:             my @okstatuses; 
 8432:             foreach my $item (split(/:/,$inststatus)) {
 8433:                 if (defined($usertypes->{$item})) {
 8434:                     push(@okstatuses,$item);  
 8435:                 }
 8436:             }
 8437:             if (@okstatuses) {
 8438:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8439:             }
 8440:         }
 8441:     }
 8442:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8443:                  $umode.', '.$first.', '.$middle.', '.
 8444:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8445:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8446:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8447:     } else {
 8448:         $logmsg .= ' during self creation';
 8449:     }
 8450:     my $changed;
 8451:     if ($newuser) {
 8452:         $changed = 1;
 8453:     } else {
 8454:         foreach my $field (@fields) {
 8455:             if ($names{$field} ne $oldnames{$field}) {
 8456:                 $changed = 1;
 8457:                 last;
 8458:             }
 8459:         }
 8460:     }
 8461:     unless ($changed) {
 8462:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8463:         &logthis($logmsg);
 8464:         return 'ok';
 8465:     }
 8466:     my $reply = &put('environment', \%names, $udom,$uname);
 8467:     if ($reply ne 'ok') { 
 8468:         return 'error: '.$reply;
 8469:     }
 8470:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8471:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8472:     }
 8473:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8474:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8475:     $logmsg = 'Success modifying user '.$logmsg;
 8476:     &logthis($logmsg);
 8477:     return 'ok';
 8478: }
 8479: 
 8480: # -------------------------------------------------------------- Modify student
 8481: 
 8482: sub modifystudent {
 8483:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8484:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8485:         $selfenroll,$context,$inststatus,$credits)=@_;
 8486:     if (!$cid) {
 8487: 	unless ($cid=$env{'request.course.id'}) {
 8488: 	    return 'not_in_class';
 8489: 	}
 8490:     }
 8491: # --------------------------------------------------------------- Make the user
 8492:     my $reply=&modifyuser
 8493: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8494:          $desiredhome,$email,$inststatus);
 8495:     unless ($reply eq 'ok') { return $reply; }
 8496:     # This will cause &modify_student_enrollment to get the uid from the
 8497:     # students environment
 8498:     $uid = undef if (!$forceid);
 8499:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8500:                                         $gene,$usec,$end,$start,$type,$locktype,
 8501:                                         $cid,$selfenroll,$context,$credits);
 8502:     return $reply;
 8503: }
 8504: 
 8505: sub modify_student_enrollment {
 8506:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8507:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8508:     my ($cdom,$cnum,$chome);
 8509:     if (!$cid) {
 8510: 	unless ($cid=$env{'request.course.id'}) {
 8511: 	    return 'not_in_class';
 8512: 	}
 8513: 	$cdom=$env{'course.'.$cid.'.domain'};
 8514: 	$cnum=$env{'course.'.$cid.'.num'};
 8515:     } else {
 8516: 	($cdom,$cnum)=split(/_/,$cid);
 8517:     }
 8518:     $chome=$env{'course.'.$cid.'.home'};
 8519:     if (!$chome) {
 8520: 	$chome=&homeserver($cnum,$cdom);
 8521:     }
 8522:     if (!$chome) { return 'unknown_course'; }
 8523:     # Make sure the user exists
 8524:     my $uhome=&homeserver($uname,$udom);
 8525:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8526: 	return 'error: no such user';
 8527:     }
 8528:     # Get student data if we were not given enough information
 8529:     if (!defined($first)  || $first  eq '' || 
 8530:         !defined($last)   || $last   eq '' || 
 8531:         !defined($uid)    || $uid    eq '' || 
 8532:         !defined($middle) || $middle eq '' || 
 8533:         !defined($gene)   || $gene   eq '') {
 8534:         # They did not supply us with enough data to enroll the student, so
 8535:         # we need to pick up more information.
 8536:         my %tmp = &get('environment',
 8537:                        ['firstname','middlename','lastname', 'generation','id']
 8538:                        ,$udom,$uname);
 8539: 
 8540:         #foreach my $key (keys(%tmp)) {
 8541:         #    &logthis("key $key = ".$tmp{$key});
 8542:         #}
 8543:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8544:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8545:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8546:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8547:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8548:     }
 8549:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8550:     my $user = "$uname:$udom";
 8551:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8552:     my $reply=cput('classlist',
 8553: 		   {$user => 
 8554: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8555: 		   $cdom,$cnum);
 8556:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8557:         &devalidate_getsection_cache($udom,$uname,$cid);
 8558:     } else { 
 8559: 	return 'error: '.$reply;
 8560:     }
 8561:     # Add student role to user
 8562:     my $uurl='/'.$cid;
 8563:     $uurl=~s/\_/\//g;
 8564:     if ($usec) {
 8565: 	$uurl.='/'.$usec;
 8566:     }
 8567:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8568:                              $selfenroll,$context);
 8569:     if ($result ne 'ok') {
 8570:         if ($old_entry{$user} ne '') {
 8571:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8572:         } else {
 8573:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8574:         }
 8575:     }
 8576:     return $result; 
 8577: }
 8578: 
 8579: sub format_name {
 8580:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8581:     my $name;
 8582:     if ($first ne 'lastname') {
 8583: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8584:     } else {
 8585: 	if ($lastname=~/\S/) {
 8586: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8587: 	    $name=~s/\s+,/,/;
 8588: 	} else {
 8589: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8590: 	}
 8591:     }
 8592:     $name=~s/^\s+//;
 8593:     $name=~s/\s+$//;
 8594:     $name=~s/\s+/ /g;
 8595:     return $name;
 8596: }
 8597: 
 8598: # ------------------------------------------------- Write to course preferences
 8599: 
 8600: sub writecoursepref {
 8601:     my ($courseid,%prefs)=@_;
 8602:     $courseid=~s/^\///;
 8603:     $courseid=~s/\_/\//g;
 8604:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8605:     my $chome=homeserver($cnum,$cdomain);
 8606:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8607: 	return 'error: no such course';
 8608:     }
 8609:     my $cstring='';
 8610:     foreach my $pref (keys(%prefs)) {
 8611: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8612:     }
 8613:     $cstring=~s/\&$//;
 8614:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8615: }
 8616: 
 8617: # ---------------------------------------------------------- Make/modify course
 8618: 
 8619: sub createcourse {
 8620:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8621:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8622:     $url=&declutter($url);
 8623:     my $cid='';
 8624:     if ($context eq 'requestcourses') {
 8625:         my $can_create = 0;
 8626:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8627:         if ($udom eq $ownerdom) {
 8628:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8629:                                   $context)) {
 8630:                 $can_create = 1;
 8631:             }
 8632:         } else {
 8633:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8634:                                            $category);
 8635:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8636:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8637:                 if (@curr > 0) {
 8638:                     my @options = qw(approval validate autolimit);
 8639:                     my $optregex = join('|',@options);
 8640:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8641:                         $can_create = 1;
 8642:                     }
 8643:                 }
 8644:             }
 8645:         }
 8646:         if ($can_create) {
 8647:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8648:                 unless (&allowed('ccc',$udom)) {
 8649:                     return 'refused'; 
 8650:                 }
 8651:             }
 8652:         } else {
 8653:             return 'refused';
 8654:         }
 8655:     } elsif (!&allowed('ccc',$udom)) {
 8656:         return 'refused';
 8657:     }
 8658: # --------------------------------------------------------------- Get Unique ID
 8659:     my $uname;
 8660:     if ($cnum =~ /^$match_courseid$/) {
 8661:         my $chome=&homeserver($cnum,$udom,'true');
 8662:         if (($chome eq '') || ($chome eq 'no_host')) {
 8663:             $uname = $cnum;
 8664:         } else {
 8665:             $uname = &generate_coursenum($udom,$crstype);
 8666:         }
 8667:     } else {
 8668:         $uname = &generate_coursenum($udom,$crstype);
 8669:     }
 8670:     return $uname if ($uname =~ /^error/);
 8671: # -------------------------------------------------- Check supplied server name
 8672:     if (!defined($course_server)) {
 8673:         if (defined(&domain($udom,'primary'))) {
 8674:             $course_server = &domain($udom,'primary');
 8675:         } else {
 8676:             $course_server = $env{'user.home'}; 
 8677:         }
 8678:     }
 8679:     my %host_servers =
 8680:         &Apache::lonnet::get_servers($udom,'library');
 8681:     unless ($host_servers{$course_server}) {
 8682:         return 'error: invalid home server for course: '.$course_server;
 8683:     }
 8684: # ------------------------------------------------------------- Make the course
 8685:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8686:                       $course_server);
 8687:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8688:     my $uhome=&homeserver($uname,$udom,'true');
 8689:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8690: 	return 'error: no such course';
 8691:     }
 8692: # ----------------------------------------------------------------- Course made
 8693: # log existence
 8694:     my $now = time;
 8695:     my $newcourse = {
 8696:                     $udom.'_'.$uname => {
 8697:                                      description => $description,
 8698:                                      inst_code   => $inst_code,
 8699:                                      owner       => $course_owner,
 8700:                                      type        => $crstype,
 8701:                                      creator     => $env{'user.name'}.':'.
 8702:                                                     $env{'user.domain'},
 8703:                                      created     => $now,
 8704:                                      context     => $context,
 8705:                                                 },
 8706:                     };
 8707:     &courseidput($udom,$newcourse,$uhome,'notime');
 8708: # set toplevel url
 8709:     my $topurl=$url;
 8710:     unless ($nonstandard) {
 8711: # ------------------------------------------ For standard courses, make top url
 8712:         my $mapurl=&clutter($url);
 8713:         if ($mapurl eq '/res/') { $mapurl=''; }
 8714:         $env{'form.initmap'}=(<<ENDINITMAP);
 8715: <map>
 8716: <resource id="1" type="start"></resource>
 8717: <resource id="2" src="$mapurl"></resource>
 8718: <resource id="3" type="finish"></resource>
 8719: <link index="1" from="1" to="2"></link>
 8720: <link index="2" from="2" to="3"></link>
 8721: </map>
 8722: ENDINITMAP
 8723:         $topurl=&declutter(
 8724:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8725:                           );
 8726:     }
 8727: # ----------------------------------------------------------- Write preferences
 8728:     &writecoursepref($udom.'_'.$uname,
 8729:                      ('description'              => $description,
 8730:                       'url'                      => $topurl,
 8731:                       'internal.creator'         => $env{'user.name'}.':'.
 8732:                                                     $env{'user.domain'},
 8733:                       'internal.created'         => $now,
 8734:                       'internal.creationcontext' => $context)
 8735:                     );
 8736:     return '/'.$udom.'/'.$uname;
 8737: }
 8738: 
 8739: # ------------------------------------------------------------------- Create ID
 8740: sub generate_coursenum {
 8741:     my ($udom,$crstype) = @_;
 8742:     my $domdesc = &domain($udom);
 8743:     return 'error: invalid domain' if ($domdesc eq '');
 8744:     my $first;
 8745:     if ($crstype eq 'Community') {
 8746:         $first = '0';
 8747:     } else {
 8748:         $first = int(1+rand(9)); 
 8749:     } 
 8750:     my $uname=$first.
 8751:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8752:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8753:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8754: # ----------------------------------------------- Make sure that does not exist
 8755:     my $uhome=&homeserver($uname,$udom,'true');
 8756:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8757:         if ($crstype eq 'Community') {
 8758:             $first = '0';
 8759:         } else {
 8760:             $first = int(1+rand(9));
 8761:         }
 8762:         $uname=$first.
 8763:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8764:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8765:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8766:         $uhome=&homeserver($uname,$udom,'true');
 8767:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8768:             return 'error: unable to generate unique course-ID';
 8769:         }
 8770:     }
 8771:     return $uname;
 8772: }
 8773: 
 8774: sub is_course {
 8775:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8776:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8777: 
 8778:     return unless $cdom and $cnum;
 8779: 
 8780:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8781:         '.');
 8782: 
 8783:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8784:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8785: }
 8786: 
 8787: sub store_userdata {
 8788:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8789:     my $result;
 8790:     if ($datakey ne '') {
 8791:         if (ref($storehash) eq 'HASH') {
 8792:             if ($udom eq '' || $uname eq '') {
 8793:                 $udom = $env{'user.domain'};
 8794:                 $uname = $env{'user.name'};
 8795:             }
 8796:             my $uhome=&homeserver($uname,$udom);
 8797:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8798:                 $result = 'error: no_host';
 8799:             } else {
 8800:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8801:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8802: 
 8803:                 my $namevalue='';
 8804:                 foreach my $key (keys(%{$storehash})) {
 8805:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8806:                 }
 8807:                 $namevalue=~s/\&$//;
 8808:                 unless ($namespace eq 'courserequests') {
 8809:                     $datakey = &escape($datakey);
 8810:                 }
 8811:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8812:                                   $namevalue,$uhome);
 8813:             }
 8814:         } else {
 8815:             $result = 'error: data to store was not a hash reference'; 
 8816:         }
 8817:     } else {
 8818:         $result= 'error: invalid requestkey'; 
 8819:     }
 8820:     return $result;
 8821: }
 8822: 
 8823: # ---------------------------------------------------------- Assign Custom Role
 8824: 
 8825: sub assigncustomrole {
 8826:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8827:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8828:                        $end,$start,$deleteflag,$selfenroll,$context);
 8829: }
 8830: 
 8831: # ----------------------------------------------------------------- Revoke Role
 8832: 
 8833: sub revokerole {
 8834:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8835:     my $now=time;
 8836:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8837: }
 8838: 
 8839: # ---------------------------------------------------------- Revoke Custom Role
 8840: 
 8841: sub revokecustomrole {
 8842:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8843:     my $now=time;
 8844:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8845:            $deleteflag,$selfenroll,$context);
 8846: }
 8847: 
 8848: # ------------------------------------------------------------ Disk usage
 8849: sub diskusage {
 8850:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8851:     $directorypath =~ s/\/$//;
 8852:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8853:                        .&escape($getpropath).':'.&escape($uname).':'
 8854:                        .&escape($udom),homeserver($uname,$udom));
 8855:     if ($listing eq 'unknown_cmd') {
 8856:         if ($getpropath) {
 8857:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8858:         }
 8859:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8860:     }
 8861:     return $listing;
 8862: }
 8863: 
 8864: sub is_locked {
 8865:     my ($file_name, $domain, $user, $which) = @_;
 8866:     my @check;
 8867:     my $is_locked;
 8868:     push (@check,$file_name);
 8869:     my %locked = &get('file_permissions',\@check,
 8870: 		      $env{'user.domain'},$env{'user.name'});
 8871:     my ($tmp)=keys(%locked);
 8872:     if ($tmp=~/^error:/) { undef(%locked); }
 8873:     
 8874:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8875:         $is_locked = 'false';
 8876:         foreach my $entry (@{$locked{$file_name}}) {
 8877:            if (ref($entry) eq 'ARRAY') {
 8878:                $is_locked = 'true';
 8879:                if (ref($which) eq 'ARRAY') {
 8880:                    push(@{$which},$entry);
 8881:                } else {
 8882:                    last;
 8883:                }
 8884:            }
 8885:        }
 8886:     } else {
 8887:         $is_locked = 'false';
 8888:     }
 8889:     return $is_locked;
 8890: }
 8891: 
 8892: sub declutter_portfile {
 8893:     my ($file) = @_;
 8894:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8895:     return $file;
 8896: }
 8897: 
 8898: # ------------------------------------------------------------- Mark as Read Only
 8899: 
 8900: sub mark_as_readonly {
 8901:     my ($domain,$user,$files,$what) = @_;
 8902:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8903:     my ($tmp)=keys(%current_permissions);
 8904:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8905:     foreach my $file (@{$files}) {
 8906: 	$file = &declutter_portfile($file);
 8907:         push(@{$current_permissions{$file}},$what);
 8908:     }
 8909:     &put('file_permissions',\%current_permissions,$domain,$user);
 8910:     return;
 8911: }
 8912: 
 8913: # ------------------------------------------------------------Save Selected Files
 8914: 
 8915: sub save_selected_files {
 8916:     my ($user, $path, @files) = @_;
 8917:     my $filename = $user."savedfiles";
 8918:     my @other_files = &files_not_in_path($user, $path);
 8919:     open (OUT, '>'.$tmpdir.$filename);
 8920:     foreach my $file (@files) {
 8921:         print (OUT $env{'form.currentpath'}.$file."\n");
 8922:     }
 8923:     foreach my $file (@other_files) {
 8924:         print (OUT $file."\n");
 8925:     }
 8926:     close (OUT);
 8927:     return 'ok';
 8928: }
 8929: 
 8930: sub clear_selected_files {
 8931:     my ($user) = @_;
 8932:     my $filename = $user."savedfiles";
 8933:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8934:     print (OUT undef);
 8935:     close (OUT);
 8936:     return ("ok");    
 8937: }
 8938: 
 8939: sub files_in_path {
 8940:     my ($user, $path) = @_;
 8941:     my $filename = $user."savedfiles";
 8942:     my %return_files;
 8943:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8944:     while (my $line_in = <IN>) {
 8945:         chomp ($line_in);
 8946:         my @paths_and_file = split (m!/!, $line_in);
 8947:         my $file_part = pop (@paths_and_file);
 8948:         my $path_part = join ('/', @paths_and_file);
 8949:         $path_part.='/';
 8950:         my $path_and_file = $path_part.$file_part;
 8951:         if ($path_part eq $path) {
 8952:             $return_files{$file_part}= 'selected';
 8953:         }
 8954:     }
 8955:     close (IN);
 8956:     return (\%return_files);
 8957: }
 8958: 
 8959: # called in portfolio select mode, to show files selected NOT in current directory
 8960: sub files_not_in_path {
 8961:     my ($user, $path) = @_;
 8962:     my $filename = $user."savedfiles";
 8963:     my @return_files;
 8964:     my $path_part;
 8965:     open(IN, '<'.LONCAPA::.$filename);
 8966:     while (my $line = <IN>) {
 8967:         #ok, I know it's clunky, but I want it to work
 8968:         my @paths_and_file = split(m|/|, $line);
 8969:         my $file_part = pop(@paths_and_file);
 8970:         chomp($file_part);
 8971:         my $path_part = join('/', @paths_and_file);
 8972:         $path_part .= '/';
 8973:         my $path_and_file = $path_part.$file_part;
 8974:         if ($path_part ne $path) {
 8975:             push(@return_files, ($path_and_file));
 8976:         }
 8977:     }
 8978:     close(OUT);
 8979:     return (@return_files);
 8980: }
 8981: 
 8982: #----------------------------------------------Get portfolio file permissions
 8983: 
 8984: sub get_portfile_permissions {
 8985:     my ($domain,$user) = @_;
 8986:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8987:     my ($tmp)=keys(%current_permissions);
 8988:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8989:     return \%current_permissions;
 8990: }
 8991: 
 8992: #---------------------------------------------Get portfolio file access controls
 8993: 
 8994: sub get_access_controls {
 8995:     my ($current_permissions,$group,$file) = @_;
 8996:     my %access;
 8997:     my $real_file = $file;
 8998:     $file =~ s/\.meta$//;
 8999:     if (defined($file)) {
 9000:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9001:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9002:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9003:             }
 9004:         }
 9005:     } else {
 9006:         foreach my $key (keys(%{$current_permissions})) {
 9007:             if ($key =~ /\0accesscontrol$/) {
 9008:                 if (defined($group)) {
 9009:                     if ($key !~ m-^\Q$group\E/-) {
 9010:                         next;
 9011:                     }
 9012:                 }
 9013:                 my ($fullpath) = split(/\0/,$key);
 9014:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9015:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9016:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9017:                     }
 9018:                 }
 9019:             }
 9020:         }
 9021:     }
 9022:     return %access;
 9023: }
 9024: 
 9025: sub modify_access_controls {
 9026:     my ($file_name,$changes,$domain,$user)=@_;
 9027:     my ($outcome,$deloutcome);
 9028:     my %store_permissions;
 9029:     my %new_values;
 9030:     my %new_control;
 9031:     my %translation;
 9032:     my @deletions = ();
 9033:     my $now = time;
 9034:     if (exists($$changes{'activate'})) {
 9035:         if (ref($$changes{'activate'}) eq 'HASH') {
 9036:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9037:             my $numnew = scalar(@newitems);
 9038:             for (my $i=0; $i<$numnew; $i++) {
 9039:                 my $newkey = $newitems[$i];
 9040:                 my $newid = &Apache::loncommon::get_cgi_id();
 9041:                 if ($newkey =~ /^\d+:/) { 
 9042:                     $newkey =~ s/^(\d+)/$newid/;
 9043:                     $translation{$1} = $newid;
 9044:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9045:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9046:                     $translation{$1} = $newid;
 9047:                 }
 9048:                 $new_values{$file_name."\0".$newkey} = 
 9049:                                           $$changes{'activate'}{$newitems[$i]};
 9050:                 $new_control{$newkey} = $now;
 9051:             }
 9052:         }
 9053:     }
 9054:     my %todelete;
 9055:     my %changed_items;
 9056:     foreach my $action ('delete','update') {
 9057:         if (exists($$changes{$action})) {
 9058:             if (ref($$changes{$action}) eq 'HASH') {
 9059:                 foreach my $key (keys(%{$$changes{$action}})) {
 9060:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9061:                     if ($action eq 'delete') { 
 9062:                         $todelete{$itemnum} = 1;
 9063:                     } else {
 9064:                         $changed_items{$itemnum} = $key;
 9065:                     }
 9066:                 }
 9067:             }
 9068:         }
 9069:     }
 9070:     # get lock on access controls for file.
 9071:     my $lockhash = {
 9072:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9073:                                                        ':'.$env{'user.domain'},
 9074:                    }; 
 9075:     my $tries = 0;
 9076:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9077:    
 9078:     while (($gotlock ne 'ok') && $tries <3) {
 9079:         $tries ++;
 9080:         sleep 1;
 9081:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9082:     }
 9083:     if ($gotlock eq 'ok') {
 9084:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9085:         my ($tmp)=keys(%curr_permissions);
 9086:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9087:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9088:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9089:             if (ref($curr_controls) eq 'HASH') {
 9090:                 foreach my $control_item (keys(%{$curr_controls})) {
 9091:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9092:                     if (defined($todelete{$itemnum})) {
 9093:                         push(@deletions,$file_name."\0".$control_item);
 9094:                     } else {
 9095:                         if (defined($changed_items{$itemnum})) {
 9096:                             $new_control{$changed_items{$itemnum}} = $now;
 9097:                             push(@deletions,$file_name."\0".$control_item);
 9098:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9099:                         } else {
 9100:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9101:                         }
 9102:                     }
 9103:                 }
 9104:             }
 9105:         }
 9106:         my ($group);
 9107:         if (&is_course($domain,$user)) {
 9108:             ($group,my $file) = split(/\//,$file_name,2);
 9109:         }
 9110:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9111:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9112:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9113:         #  remove lock
 9114:         my @del_lock = ($file_name."\0".'locked_access_records');
 9115:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9116:         my $sqlresult =
 9117:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9118:                                     $group);
 9119:     } else {
 9120:         $outcome = "error: could not obtain lockfile\n";  
 9121:     }
 9122:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9123: }
 9124: 
 9125: sub make_public_indefinitely {
 9126:     my ($requrl) = @_;
 9127:     my $now = time;
 9128:     my $action = 'activate';
 9129:     my $aclnum = 0;
 9130:     if (&is_portfolio_url($requrl)) {
 9131:         my (undef,$udom,$unum,$file_name,$group) =
 9132:             &parse_portfolio_url($requrl);
 9133:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9134:         my %access_controls = &get_access_controls($current_perms,
 9135:                                                    $group,$file_name);
 9136:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9137:             my ($num,$scope,$end,$start) = 
 9138:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9139:             if ($scope eq 'public') {
 9140:                 if ($start <= $now && $end == 0) {
 9141:                     $action = 'none';
 9142:                 } else {
 9143:                     $action = 'update';
 9144:                     $aclnum = $num;
 9145:                 }
 9146:                 last;
 9147:             }
 9148:         }
 9149:         if ($action eq 'none') {
 9150:              return 'ok';
 9151:         } else {
 9152:             my %changes;
 9153:             my $newend = 0;
 9154:             my $newstart = $now;
 9155:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9156:             $changes{$action}{$newkey} = {
 9157:                 type => 'public',
 9158:                 time => {
 9159:                     start => $newstart,
 9160:                     end   => $newend,
 9161:                 },
 9162:             };
 9163:             my ($outcome,$deloutcome,$new_values,$translation) =
 9164:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9165:             return $outcome;
 9166:         }
 9167:     } else {
 9168:         return 'invalid';
 9169:     }
 9170: }
 9171: 
 9172: #------------------------------------------------------Get Marked as Read Only
 9173: 
 9174: sub get_marked_as_readonly {
 9175:     my ($domain,$user,$what,$group) = @_;
 9176:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9177:     my @readonly_files;
 9178:     my $cmp1=$what;
 9179:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9180:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9181:         if (defined($group)) {
 9182:             if ($file_name !~ m-^\Q$group\E/-) {
 9183:                 next;
 9184:             }
 9185:         }
 9186:         if (ref($value) eq "ARRAY"){
 9187:             foreach my $stored_what (@{$value}) {
 9188:                 my $cmp2=$stored_what;
 9189:                 if (ref($stored_what) eq 'ARRAY') {
 9190:                     $cmp2=join('',@{$stored_what});
 9191:                 }
 9192:                 if ($cmp1 eq $cmp2) {
 9193:                     push(@readonly_files, $file_name);
 9194:                     last;
 9195:                 } elsif (!defined($what)) {
 9196:                     push(@readonly_files, $file_name);
 9197:                     last;
 9198:                 }
 9199:             }
 9200:         }
 9201:     }
 9202:     return @readonly_files;
 9203: }
 9204: #-----------------------------------------------------------Get Marked as Read Only Hash
 9205: 
 9206: sub get_marked_as_readonly_hash {
 9207:     my ($current_permissions,$group,$what) = @_;
 9208:     my %readonly_files;
 9209:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9210:         if (defined($group)) {
 9211:             if ($file_name !~ m-^\Q$group\E/-) {
 9212:                 next;
 9213:             }
 9214:         }
 9215:         if (ref($value) eq "ARRAY"){
 9216:             foreach my $stored_what (@{$value}) {
 9217:                 if (ref($stored_what) eq 'ARRAY') {
 9218:                     foreach my $lock_descriptor(@{$stored_what}) {
 9219:                         if ($lock_descriptor eq 'graded') {
 9220:                             $readonly_files{$file_name} = 'graded';
 9221:                         } elsif ($lock_descriptor eq 'handback') {
 9222:                             $readonly_files{$file_name} = 'handback';
 9223:                         } else {
 9224:                             if (!exists($readonly_files{$file_name})) {
 9225:                                 $readonly_files{$file_name} = 'locked';
 9226:                             }
 9227:                         }
 9228:                     }
 9229:                 } 
 9230:             }
 9231:         } 
 9232:     }
 9233:     return %readonly_files;
 9234: }
 9235: # ------------------------------------------------------------ Unmark as Read Only
 9236: 
 9237: sub unmark_as_readonly {
 9238:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9239:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9240:     my ($domain,$user,$what,$file_name,$group) = @_;
 9241:     $file_name = &declutter_portfile($file_name);
 9242:     my $symb_crs = $what;
 9243:     if (ref($what)) { $symb_crs=join('',@$what); }
 9244:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9245:     my ($tmp)=keys(%current_permissions);
 9246:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9247:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9248:     foreach my $file (@readonly_files) {
 9249: 	my $clean_file = &declutter_portfile($file);
 9250: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9251: 	my $current_locks = $current_permissions{$file};
 9252:         my @new_locks;
 9253:         my @del_keys;
 9254:         if (ref($current_locks) eq "ARRAY"){
 9255:             foreach my $locker (@{$current_locks}) {
 9256:                 my $compare=$locker;
 9257:                 if (ref($locker) eq 'ARRAY') {
 9258:                     $compare=join('',@{$locker});
 9259:                     if ($compare ne $symb_crs) {
 9260:                         push(@new_locks, $locker);
 9261:                     }
 9262:                 }
 9263:             }
 9264:             if (scalar(@new_locks) > 0) {
 9265:                 $current_permissions{$file} = \@new_locks;
 9266:             } else {
 9267:                 push(@del_keys, $file);
 9268:                 &del('file_permissions',\@del_keys, $domain, $user);
 9269:                 delete($current_permissions{$file});
 9270:             }
 9271:         }
 9272:     }
 9273:     &put('file_permissions',\%current_permissions,$domain,$user);
 9274:     return;
 9275: }
 9276: 
 9277: # ------------------------------------------------------------ Directory lister
 9278: 
 9279: sub dirlist {
 9280:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9281:     $uri=~s/^\///;
 9282:     $uri=~s/\/$//;
 9283:     my ($udom, $uname);
 9284:     if ($getuserdir) {
 9285:         $udom = $userdomain;
 9286:         $uname = $username;
 9287:     } else {
 9288:         (undef,$udom,$uname)=split(/\//,$uri);
 9289:         if(defined($userdomain)) {
 9290:             $udom = $userdomain;
 9291:         }
 9292:         if(defined($username)) {
 9293:             $uname = $username;
 9294:         }
 9295:     }
 9296:     my ($dirRoot,$listing,@listing_results);
 9297: 
 9298:     $dirRoot = $perlvar{'lonDocRoot'};
 9299:     if (defined($getpropath)) {
 9300:         $dirRoot = &propath($udom,$uname);
 9301:         $dirRoot =~ s/\/$//;
 9302:     } elsif (defined($getuserdir)) {
 9303:         my $subdir=$uname.'__';
 9304:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9305:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9306:                    ."/$udom/$subdir/$uname";
 9307:     } elsif (defined($alternateRoot)) {
 9308:         $dirRoot = $alternateRoot;
 9309:     }
 9310: 
 9311:     if($udom) {
 9312:         if($uname) {
 9313:             my $uhome = &homeserver($uname,$udom);
 9314:             if ($uhome eq 'no_host') {
 9315:                 return ([],'no_host');
 9316:             }
 9317:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9318:                               .$getuserdir.':'.&escape($dirRoot)
 9319:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9320:             if ($listing eq 'unknown_cmd') {
 9321:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9322:             } else {
 9323:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9324:             }
 9325:             if ($listing eq 'unknown_cmd') {
 9326:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9327:                 @listing_results = split(/:/,$listing);
 9328:             } else {
 9329:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9330:             }
 9331:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9332:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9333:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9334:                 return ([],$listing);
 9335:             } else {
 9336:                 return (\@listing_results);
 9337:             }
 9338:         } elsif(!$alternateRoot) {
 9339:             my (%allusers,%listerror);
 9340: 	    my %servers = &get_servers($udom,'library');
 9341:  	    foreach my $tryserver (keys(%servers)) {
 9342:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9343:                                   &escape($udom),$tryserver);
 9344:                 if ($listing eq 'unknown_cmd') {
 9345: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9346: 				      $udom, $tryserver);
 9347:                 } else {
 9348:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9349:                 }
 9350: 		if ($listing eq 'unknown_cmd') {
 9351: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9352: 				      $udom, $tryserver);
 9353: 		    @listing_results = split(/:/,$listing);
 9354: 		} else {
 9355: 		    @listing_results =
 9356: 			map { &unescape($_); } split(/:/,$listing);
 9357: 		}
 9358:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9359:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9360:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9361:                     $listerror{$tryserver} = $listing;
 9362:                 } else {
 9363: 		    foreach my $line (@listing_results) {
 9364: 			my ($entry) = split(/&/,$line,2);
 9365: 			$allusers{$entry} = 1;
 9366: 		    }
 9367: 		}
 9368:             }
 9369:             my @alluserslist=();
 9370:             foreach my $user (sort(keys(%allusers))) {
 9371:                 push(@alluserslist,$user.'&user');
 9372:             }
 9373:             return (\@alluserslist);
 9374:         } else {
 9375:             return ([],'missing username');
 9376:         }
 9377:     } elsif(!defined($getpropath)) {
 9378:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9379:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9380:         return (\@all_domains);
 9381:     } else {
 9382:         return ([],'missing domain');
 9383:     }
 9384: }
 9385: 
 9386: # --------------------------------------------- GetFileTimestamp
 9387: # This function utilizes dirlist and returns the date stamp for
 9388: # when it was last modified.  It will also return an error of -1
 9389: # if an error occurs
 9390: 
 9391: sub GetFileTimestamp {
 9392:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9393:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9394:     $studentName   = &LONCAPA::clean_username($studentName);
 9395:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9396:                                     undef,$getuserdir);
 9397:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9398:         return -1;
 9399:     }
 9400:     if (ref($fileref) eq 'ARRAY') {
 9401:         my @stats = split('&',$fileref->[0]);
 9402:         # @stats contains first the filename, then the stat output
 9403:         return $stats[10]; # so this is 10 instead of 9.
 9404:     } else {
 9405:         return -1;
 9406:     }
 9407: }
 9408: 
 9409: sub stat_file {
 9410:     my ($uri) = @_;
 9411:     $uri = &clutter_with_no_wrapper($uri);
 9412: 
 9413:     my ($udom,$uname,$file);
 9414:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9415: 	($udom,$uname,$file) =
 9416: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9417: 	$file = 'userfiles/'.$file;
 9418:     }
 9419:     if ($uri =~ m-^/res/-) {
 9420: 	($udom,$uname) = 
 9421: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9422: 	$file = $uri;
 9423:     }
 9424: 
 9425:     if (!$udom || !$uname || !$file) {
 9426: 	# unable to handle the uri
 9427: 	return ();
 9428:     }
 9429:     my $getpropath;
 9430:     if ($file =~ /^userfiles\//) {
 9431:         $getpropath = 1;
 9432:     }
 9433:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9434:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9435:         return ();
 9436:     } else {
 9437:         if (ref($listref) eq 'ARRAY') {
 9438:             my @stats = split('&',$listref->[0]);
 9439: 	    shift(@stats); #filename is first
 9440: 	    return @stats;
 9441:         }
 9442:     }
 9443:     return ();
 9444: }
 9445: 
 9446: # -------------------------------------------------------- Value of a Condition
 9447: 
 9448: # gets the value of a specific preevaluated condition
 9449: #    stored in the string  $env{user.state.<cid>}
 9450: # or looks up a condition reference in the bighash and if if hasn't
 9451: # already been evaluated recurses into docondval to get the value of
 9452: # the condition, then memoizing it to 
 9453: #   $env{user.state.<cid>.<condition>}
 9454: sub directcondval {
 9455:     my $number=shift;
 9456:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9457: 	&Apache::lonuserstate::evalstate();
 9458:     }
 9459:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9460: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9461:     } elsif ($number =~ /^_/) {
 9462: 	my $sub_condition;
 9463: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9464: 		&GDBM_READER(),0640)) {
 9465: 	    $sub_condition=$bighash{'conditions'.$number};
 9466: 	    untie(%bighash);
 9467: 	}
 9468: 	my $value = &docondval($sub_condition);
 9469: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9470: 	return $value;
 9471:     }
 9472:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9473:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9474:     } else {
 9475:        return 2;
 9476:     }
 9477: }
 9478: 
 9479: # get the collection of conditions for this resource
 9480: sub condval {
 9481:     my $condidx=shift;
 9482:     my $allpathcond='';
 9483:     foreach my $cond (split(/\|/,$condidx)) {
 9484: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9485: 	    $allpathcond.=
 9486: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9487: 	}
 9488:     }
 9489:     $allpathcond=~s/\|$//;
 9490:     return &docondval($allpathcond);
 9491: }
 9492: 
 9493: #evaluates an expression of conditions
 9494: sub docondval {
 9495:     my ($allpathcond) = @_;
 9496:     my $result=0;
 9497:     if ($env{'request.course.id'}
 9498: 	&& defined($allpathcond)) {
 9499: 	my $operand='|';
 9500: 	my @stack;
 9501: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9502: 	    if ($chunk eq '(') {
 9503: 		push @stack,($operand,$result);
 9504: 	    } elsif ($chunk eq ')') {
 9505: 		my $before=pop @stack;
 9506: 		if (pop @stack eq '&') {
 9507: 		    $result=$result>$before?$before:$result;
 9508: 		} else {
 9509: 		    $result=$result>$before?$result:$before;
 9510: 		}
 9511: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9512: 		$operand=$chunk;
 9513: 	    } else {
 9514: 		my $new=directcondval($chunk);
 9515: 		if ($operand eq '&') {
 9516: 		    $result=$result>$new?$new:$result;
 9517: 		} else {
 9518: 		    $result=$result>$new?$result:$new;
 9519: 		}
 9520: 	    }
 9521: 	}
 9522:     }
 9523:     return $result;
 9524: }
 9525: 
 9526: # ---------------------------------------------------- Devalidate courseresdata
 9527: 
 9528: sub devalidatecourseresdata {
 9529:     my ($coursenum,$coursedomain)=@_;
 9530:     my $hashid=$coursenum.':'.$coursedomain;
 9531:     &devalidate_cache_new('courseres',$hashid);
 9532: }
 9533: 
 9534: 
 9535: # --------------------------------------------------- Course Resourcedata Query
 9536: #
 9537: #  Parameters:
 9538: #      $coursenum    - Number of the course.
 9539: #      $coursedomain - Domain at which the course was created.
 9540: #  Returns:
 9541: #     A hash of the course parameters along (I think) with timestamps
 9542: #     and version info.
 9543: 
 9544: sub get_courseresdata {
 9545:     my ($coursenum,$coursedomain)=@_;
 9546:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9547:     my $hashid=$coursenum.':'.$coursedomain;
 9548:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9549:     my %dumpreply;
 9550:     unless (defined($cached)) {
 9551: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9552: 	$result=\%dumpreply;
 9553: 	my ($tmp) = keys(%dumpreply);
 9554: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9555: 	    &do_cache_new('courseres',$hashid,$result,600);
 9556: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9557: 	    return $tmp;
 9558: 	} elsif ($tmp =~ /^(error)/) {
 9559: 	    $result=undef;
 9560: 	    &do_cache_new('courseres',$hashid,$result,600);
 9561: 	}
 9562:     }
 9563:     return $result;
 9564: }
 9565: 
 9566: sub devalidateuserresdata {
 9567:     my ($uname,$udom)=@_;
 9568:     my $hashid="$udom:$uname";
 9569:     &devalidate_cache_new('userres',$hashid);
 9570: }
 9571: 
 9572: sub get_userresdata {
 9573:     my ($uname,$udom)=@_;
 9574:     #most student don\'t have any data set, check if there is some data
 9575:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9576: 
 9577:     my $hashid="$udom:$uname";
 9578:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9579:     if (!defined($cached)) {
 9580: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9581: 	$result=\%resourcedata;
 9582: 	&do_cache_new('userres',$hashid,$result,600);
 9583:     }
 9584:     my ($tmp)=keys(%$result);
 9585:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9586: 	return $result;
 9587:     }
 9588:     #error 2 occurs when the .db doesn't exist
 9589:     if ($tmp!~/error: 2 /) {
 9590: 	&logthis("<font color=\"blue\">WARNING:".
 9591: 		 " Trying to get resource data for ".
 9592: 		 $uname." at ".$udom.": ".
 9593: 		 $tmp."</font>");
 9594:     } elsif ($tmp=~/error: 2 /) {
 9595: 	#&EXT_cache_set($udom,$uname);
 9596: 	&do_cache_new('userres',$hashid,undef,600);
 9597: 	undef($tmp); # not really an error so don't send it back
 9598:     }
 9599:     return $tmp;
 9600: }
 9601: #----------------------------------------------- resdata - return resource data
 9602: #  Purpose:
 9603: #    Return resource data for either users or for a course.
 9604: #  Parameters:
 9605: #     $name      - Course/user name.
 9606: #     $domain    - Name of the domain the user/course is registered on.
 9607: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9608: #     @which     - Array of names of resources desired.
 9609: #  Returns:
 9610: #     The value of the first reasource in @which that is found in the
 9611: #     resource hash.
 9612: #  Exceptional Conditions:
 9613: #     If the $type passed in is not valid (not the string 'course' or 
 9614: #     'user', an undefined  reference is returned.
 9615: #     If none of the resources are found, an undef is returned
 9616: sub resdata {
 9617:     my ($name,$domain,$type,@which)=@_;
 9618:     my $result;
 9619:     if ($type eq 'course') {
 9620: 	$result=&get_courseresdata($name,$domain);
 9621:     } elsif ($type eq 'user') {
 9622: 	$result=&get_userresdata($name,$domain);
 9623:     }
 9624:     if (!ref($result)) { return $result; }    
 9625:     foreach my $item (@which) {
 9626: 	if (defined($result->{$item->[0]})) {
 9627: 	    return [$result->{$item->[0]},$item->[1]];
 9628: 	}
 9629:     }
 9630:     return undef;
 9631: }
 9632: 
 9633: #
 9634: # EXT resource caching routines
 9635: #
 9636: 
 9637: sub clear_EXT_cache_status {
 9638:     &delenv('cache.EXT.');
 9639: }
 9640: 
 9641: sub EXT_cache_status {
 9642:     my ($target_domain,$target_user) = @_;
 9643:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9644:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9645:         # We know already the user has no data
 9646:         return 1;
 9647:     } else {
 9648:         return 0;
 9649:     }
 9650: }
 9651: 
 9652: sub EXT_cache_set {
 9653:     my ($target_domain,$target_user) = @_;
 9654:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9655:     #&appenv({$cachename => time});
 9656: }
 9657: 
 9658: # --------------------------------------------------------- Value of a Variable
 9659: sub EXT {
 9660: 
 9661:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9662:     unless ($varname) { return ''; }
 9663:     #get real user name/domain, courseid and symb
 9664:     my $courseid;
 9665:     my $publicuser;
 9666:     if ($symbparm) {
 9667: 	$symbparm=&get_symb_from_alias($symbparm);
 9668:     }
 9669:     if (!($uname && $udom)) {
 9670:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9671:       if (!$symbparm) {	$symbparm=$cursymb; }
 9672:     } else {
 9673: 	$courseid=$env{'request.course.id'};
 9674:     }
 9675:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9676:     my $rest;
 9677:     if (defined($therest[0])) {
 9678:        $rest=join('.',@therest);
 9679:     } else {
 9680:        $rest='';
 9681:     }
 9682: 
 9683:     my $qualifierrest=$qualifier;
 9684:     if ($rest) { $qualifierrest.='.'.$rest; }
 9685:     my $spacequalifierrest=$space;
 9686:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9687:     if ($realm eq 'user') {
 9688: # --------------------------------------------------------------- user.resource
 9689: 	if ($space eq 'resource') {
 9690: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9691: 		  || defined($Apache::lonhomework::parsing_a_task))
 9692: 		 &&
 9693: 		 ($symbparm eq &symbread()) ) {	
 9694: 		# if we are in the middle of processing the resource the
 9695: 		# get the value we are planning on committing
 9696:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9697:                     return $Apache::lonhomework::results{$qualifierrest};
 9698:                 } else {
 9699:                     return $Apache::lonhomework::history{$qualifierrest};
 9700:                 }
 9701: 	    } else {
 9702: 		my %restored;
 9703: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9704: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9705: 		} else {
 9706: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9707: 		}
 9708: 		return $restored{$qualifierrest};
 9709: 	    }
 9710: # ----------------------------------------------------------------- user.access
 9711:         } elsif ($space eq 'access') {
 9712: 	    # FIXME - not supporting calls for a specific user
 9713:             return &allowed($qualifier,$rest);
 9714: # ------------------------------------------ user.preferences, user.environment
 9715:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9716: 	    if (($uname eq $env{'user.name'}) &&
 9717: 		($udom eq $env{'user.domain'})) {
 9718: 		return $env{join('.',('environment',$qualifierrest))};
 9719: 	    } else {
 9720: 		my %returnhash;
 9721: 		if (!$publicuser) {
 9722: 		    %returnhash=&userenvironment($udom,$uname,
 9723: 						 $qualifierrest);
 9724: 		}
 9725: 		return $returnhash{$qualifierrest};
 9726: 	    }
 9727: # ----------------------------------------------------------------- user.course
 9728:         } elsif ($space eq 'course') {
 9729: 	    # FIXME - not supporting calls for a specific user
 9730:             return $env{join('.',('request.course',$qualifier))};
 9731: # ------------------------------------------------------------------- user.role
 9732:         } elsif ($space eq 'role') {
 9733: 	    # FIXME - not supporting calls for a specific user
 9734:             my ($role,$where)=split(/\./,$env{'request.role'});
 9735:             if ($qualifier eq 'value') {
 9736: 		return $role;
 9737:             } elsif ($qualifier eq 'extent') {
 9738:                 return $where;
 9739:             }
 9740: # ----------------------------------------------------------------- user.domain
 9741:         } elsif ($space eq 'domain') {
 9742:             return $udom;
 9743: # ------------------------------------------------------------------- user.name
 9744:         } elsif ($space eq 'name') {
 9745:             return $uname;
 9746: # ---------------------------------------------------- Any other user namespace
 9747:         } else {
 9748: 	    my %reply;
 9749: 	    if (!$publicuser) {
 9750: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9751: 	    }
 9752: 	    return $reply{$qualifierrest};
 9753:         }
 9754:     } elsif ($realm eq 'query') {
 9755: # ---------------------------------------------- pull stuff out of query string
 9756:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9757: 						[$spacequalifierrest]);
 9758: 	return $env{'form.'.$spacequalifierrest}; 
 9759:    } elsif ($realm eq 'request') {
 9760: # ------------------------------------------------------------- request.browser
 9761:         if ($space eq 'browser') {
 9762:             return $env{'browser.'.$qualifier};
 9763: # ------------------------------------------------------------ request.filename
 9764:         } else {
 9765:             return $env{'request.'.$spacequalifierrest};
 9766:         }
 9767:     } elsif ($realm eq 'course') {
 9768: # ---------------------------------------------------------- course.description
 9769:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9770:     } elsif ($realm eq 'resource') {
 9771: 
 9772: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9773: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9774: 	}
 9775: 
 9776:         if ($qualifier eq '') {
 9777: 	    if ($space eq 'title') {
 9778: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9779: 	        return &gettitle($symbparm);
 9780: 	    }
 9781: 	
 9782: 	    if ($space eq 'map') {
 9783: 	        my ($map) = &decode_symb($symbparm);
 9784: 	        return &symbread($map);
 9785: 	    }
 9786:             if ($space eq 'maptitle') {
 9787:                 my ($map) = &decode_symb($symbparm);
 9788:                 return &gettitle($map);
 9789:             }
 9790: 	    if ($space eq 'filename') {
 9791: 	        if ($symbparm) {
 9792: 		    return &clutter((&decode_symb($symbparm))[2]);
 9793: 	        }
 9794: 	        return &hreflocation('',$env{'request.filename'});
 9795: 	    }
 9796:         }
 9797: 
 9798:         if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9799:             if ($space eq 'visibleparts') {
 9800:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9801:                 my $item;
 9802:                 if (ref($navmap)) {
 9803:                     my $res = $navmap->getBySymb($symbparm);
 9804:                     my $parts = $res->parts();
 9805:                     if (ref($parts) eq 'ARRAY') {
 9806:                         $item = join(',',@{$parts});
 9807:                     }
 9808:                     undef($navmap);
 9809:                 }
 9810:                 return $item;
 9811:             }
 9812:         }
 9813: 
 9814: 	my ($section, $group, @groups);
 9815: 	my ($courselevelm,$courselevel);
 9816:         if (($courseid eq '') && ($cid)) {
 9817:             $courseid = $cid;
 9818:         }
 9819: 	if (($symbparm && $courseid) && 
 9820: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9821: 
 9822: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9823: 
 9824: # ----------------------------------------------------- Cascading lookup scheme
 9825: 	    my $symbp=$symbparm;
 9826: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9827: 
 9828: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9829: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9830: 
 9831: 	    if (($env{'user.name'} eq $uname) &&
 9832: 		($env{'user.domain'} eq $udom)) {
 9833: 		$section=$env{'request.course.sec'};
 9834:                 @groups = split(/:/,$env{'request.course.groups'});  
 9835:                 @groups=&sort_course_groups($courseid,@groups); 
 9836: 	    } else {
 9837: 		if (! defined($usection)) {
 9838: 		    $section=&getsection($udom,$uname,$courseid);
 9839: 		} else {
 9840: 		    $section = $usection;
 9841: 		}
 9842:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9843: 	    }
 9844: 
 9845: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9846: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9847: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9848: 
 9849: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9850: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9851: 	    $courselevelm=$courseid.'.'.$mapparm;
 9852: 
 9853: # ----------------------------------------------------------- first, check user
 9854: 
 9855: 	    my $userreply=&resdata($uname,$udom,'user',
 9856: 				       ([$courselevelr,'resource'],
 9857: 					[$courselevelm,'map'     ],
 9858: 					[$courselevel, 'course'  ]));
 9859: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9860: 
 9861: # ------------------------------------------------ second, check some of course
 9862:             my $coursereply;
 9863:             if (@groups > 0) {
 9864:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9865:                                        $mapparm,$spacequalifierrest);
 9866:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9867:             }
 9868: 
 9869: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9870: 				  $env{'course.'.$courseid.'.domain'},
 9871: 				  'course',
 9872: 				  ([$seclevelr,   'resource'],
 9873: 				   [$seclevelm,   'map'     ],
 9874: 				   [$seclevel,    'course'  ],
 9875: 				   [$courselevelr,'resource']));
 9876: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9877: 
 9878: # ------------------------------------------------------ third, check map parms
 9879: 	    my %parmhash=();
 9880: 	    my $thisparm='';
 9881: 	    if (tie(%parmhash,'GDBM_File',
 9882: 		    $env{'request.course.fn'}.'_parms.db',
 9883: 		    &GDBM_READER(),0640)) {
 9884: 		$thisparm=$parmhash{$symbparm};
 9885: 		untie(%parmhash);
 9886: 	    }
 9887: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9888: 	}
 9889: # ------------------------------------------ fourth, look in resource metadata
 9890: 
 9891: 	$spacequalifierrest=~s/\./\_/;
 9892: 	my $filename;
 9893: 	if (!$symbparm) { $symbparm=&symbread(); }
 9894: 	if ($symbparm) {
 9895: 	    $filename=(&decode_symb($symbparm))[2];
 9896: 	} else {
 9897: 	    $filename=$env{'request.filename'};
 9898: 	}
 9899: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9900: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9901: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9902: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9903: 
 9904: # ---------------------------------------------- fourth, look in rest of course
 9905: 	if ($symbparm && defined($courseid) && 
 9906: 	    $courseid eq $env{'request.course.id'}) {
 9907: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9908: 				     $env{'course.'.$courseid.'.domain'},
 9909: 				     'course',
 9910: 				     ([$courselevelm,'map'   ],
 9911: 				      [$courselevel, 'course']));
 9912: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9913: 	}
 9914: # ------------------------------------------------------------------ Cascade up
 9915: 	unless ($space eq '0') {
 9916: 	    my @parts=split(/_/,$space);
 9917: 	    my $id=pop(@parts);
 9918: 	    my $part=join('_',@parts);
 9919: 	    if ($part eq '') { $part='0'; }
 9920: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9921: 				 $symbparm,$udom,$uname,$section,1);
 9922: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9923: 	}
 9924: 	if ($recurse) { return undef; }
 9925: 	my $pack_def=&packages_tab_default($filename,$varname);
 9926: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9927: # ---------------------------------------------------- Any other user namespace
 9928:     } elsif ($realm eq 'environment') {
 9929: # ----------------------------------------------------------------- environment
 9930: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9931: 	    return $env{'environment.'.$spacequalifierrest};
 9932: 	} else {
 9933: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9934: 		return '';
 9935: 	    }
 9936: 	    my %returnhash=&userenvironment($udom,$uname,
 9937: 					    $spacequalifierrest);
 9938: 	    return $returnhash{$spacequalifierrest};
 9939: 	}
 9940:     } elsif ($realm eq 'system') {
 9941: # ----------------------------------------------------------------- system.time
 9942: 	if ($space eq 'time') {
 9943: 	    return time;
 9944:         }
 9945:     } elsif ($realm eq 'server') {
 9946: # ----------------------------------------------------------------- system.time
 9947: 	if ($space eq 'name') {
 9948: 	    return $ENV{'SERVER_NAME'};
 9949:         }
 9950:     }
 9951:     return '';
 9952: }
 9953: 
 9954: sub get_reply {
 9955:     my ($reply_value) = @_;
 9956:     if (ref($reply_value) eq 'ARRAY') {
 9957:         if (wantarray) {
 9958: 	    return @$reply_value;
 9959:         }
 9960:         return $reply_value->[0];
 9961:     } else {
 9962:         return $reply_value;
 9963:     }
 9964: }
 9965: 
 9966: sub check_group_parms {
 9967:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9968:     my @groupitems = ();
 9969:     my $resultitem;
 9970:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9971:     foreach my $group (@{$groups}) {
 9972:         foreach my $level (@levels) {
 9973:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9974:              push(@groupitems,[$item,$level->[1]]);
 9975:         }
 9976:     }
 9977:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9978:                             $env{'course.'.$courseid.'.domain'},
 9979:                                      'course',@groupitems);
 9980:     return $coursereply;
 9981: }
 9982: 
 9983: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9984:     my ($courseid,@groups) = @_;
 9985:     @groups = sort(@groups);
 9986:     return @groups;
 9987: }
 9988: 
 9989: sub packages_tab_default {
 9990:     my ($uri,$varname)=@_;
 9991:     my (undef,$part,$name)=split(/\./,$varname);
 9992: 
 9993:     my (@extension,@specifics,$do_default);
 9994:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9995: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9996: 	if ($pack_type eq 'default') {
 9997: 	    $do_default=1;
 9998: 	} elsif ($pack_type eq 'extension') {
 9999: 	    push(@extension,[$package,$pack_type,$pack_part]);
10000: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10001: 	    # only look at packages defaults for packages that this id is
10002: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10003: 	}
10004:     }
10005:     # first look for a package that matches the requested part id
10006:     foreach my $package (@specifics) {
10007: 	my (undef,$pack_type,$pack_part)=@{$package};
10008: 	next if ($pack_part ne $part);
10009: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10010: 	    return $packagetab{"$pack_type&$name&default"};
10011: 	}
10012:     }
10013:     # look for any possible matching non extension_ package
10014:     foreach my $package (@specifics) {
10015: 	my (undef,$pack_type,$pack_part)=@{$package};
10016: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10017: 	    return $packagetab{"$pack_type&$name&default"};
10018: 	}
10019: 	if ($pack_type eq 'part') { $pack_part='0'; }
10020: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10021: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10022: 	}
10023:     }
10024:     # look for any posible extension_ match
10025:     foreach my $package (@extension) {
10026: 	my ($package,$pack_type)=@{$package};
10027: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10028: 	    return $packagetab{"$pack_type&$name&default"};
10029: 	}
10030: 	if (defined($packagetab{$package."&$name&default"})) {
10031: 	    return $packagetab{$package."&$name&default"};
10032: 	}
10033:     }
10034:     # look for a global default setting
10035:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10036: 	return $packagetab{"default&$name&default"};
10037:     }
10038:     return undef;
10039: }
10040: 
10041: sub add_prefix_and_part {
10042:     my ($prefix,$part)=@_;
10043:     my $keyroot;
10044:     if (defined($prefix) && $prefix !~ /^__/) {
10045: 	# prefix that has a part already
10046: 	$keyroot=$prefix;
10047:     } elsif (defined($prefix)) {
10048: 	# prefix that is missing a part
10049: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10050:     } else {
10051: 	# no prefix at all
10052: 	if (defined($part)) { $keyroot='_'.$part; }
10053:     }
10054:     return $keyroot;
10055: }
10056: 
10057: # ---------------------------------------------------------------- Get metadata
10058: 
10059: my %metaentry;
10060: my %importedpartids;
10061: sub metadata {
10062:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10063:     $uri=&declutter($uri);
10064:     # if it is a non metadata possible uri return quickly
10065:     if (($uri eq '') || 
10066: 	(($uri =~ m|^/*adm/|) && 
10067: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10068:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10069: 	return undef;
10070:     }
10071:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10072: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10073: 	return undef;
10074:     }
10075:     my $filename=$uri;
10076:     $uri=~s/\.meta$//;
10077: #
10078: # Is the metadata already cached?
10079: # Look at timestamp of caching
10080: # Everything is cached by the main uri, libraries are never directly cached
10081: #
10082:     if (!defined($liburi)) {
10083: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10084: 	if (defined($cached)) { return $result->{':'.$what}; }
10085:     }
10086:     {
10087: # Imported parts would go here
10088:         my %importedids=();
10089:         my @origfileimportpartids=();
10090:         my $importedparts=0;
10091: #
10092: # Is this a recursive call for a library?
10093: #
10094: #	if (! exists($metacache{$uri})) {
10095: #	    $metacache{$uri}={};
10096: #	}
10097: 	my $cachetime = 60*60;
10098:         if ($liburi) {
10099: 	    $liburi=&declutter($liburi);
10100:             $filename=$liburi;
10101:         } else {
10102: 	    &devalidate_cache_new('meta',$uri);
10103: 	    undef(%metaentry);
10104: 	}
10105:         my %metathesekeys=();
10106:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10107: 	my $metastring;
10108: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10109: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10110: 	    $metastring = 
10111: 		&Apache::lonnet::ssi_body($which,
10112: 					  ('grade_target' => 'meta'));
10113: 	    $cachetime = 1; # only want this cached in the child not long term
10114: 	} elsif (($uri !~ m -^(editupload)/-) && 
10115:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10116: 	    my $file=&filelocation('',&clutter($filename));
10117: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10118: 	    $metastring=&getfile($file);
10119: 	}
10120:         my $parser=HTML::LCParser->new(\$metastring);
10121:         my $token;
10122:         undef %metathesekeys;
10123:         while ($token=$parser->get_token) {
10124: 	    if ($token->[0] eq 'S') {
10125: 		if (defined($token->[2]->{'package'})) {
10126: #
10127: # This is a package - get package info
10128: #
10129: 		    my $package=$token->[2]->{'package'};
10130: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10131: 		    if (defined($token->[2]->{'id'})) { 
10132: 			$keyroot.='_'.$token->[2]->{'id'}; 
10133: 		    }
10134: 		    if ($metaentry{':packages'}) {
10135: 			$metaentry{':packages'}.=','.$package.$keyroot;
10136: 		    } else {
10137: 			$metaentry{':packages'}=$package.$keyroot;
10138: 		    }
10139: 		    foreach my $pack_entry (keys(%packagetab)) {
10140: 			my $part=$keyroot;
10141: 			$part=~s/^\_//;
10142: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10143: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10144: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10145: 			    # ignore package.tab specified default values
10146:                             # here &package_tab_default() will fetch those
10147: 			    if ($subp eq 'default') { next; }
10148: 			    my $value=$packagetab{$pack_entry};
10149: 			    my $unikey;
10150: 			    if ($pack =~ /_0$/) {
10151: 				$unikey='parameter_0_'.$name;
10152: 				$part=0;
10153: 			    } else {
10154: 				$unikey='parameter'.$keyroot.'_'.$name;
10155: 			    }
10156: 			    if ($subp eq 'display') {
10157: 				$value.=' [Part: '.$part.']';
10158: 			    }
10159: 			    $metaentry{':'.$unikey.'.part'}=$part;
10160: 			    $metathesekeys{$unikey}=1;
10161: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10162: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10163: 			    }
10164: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10165: 				$metaentry{':'.$unikey}=
10166: 				    $metaentry{':'.$unikey.'.default'};
10167: 			    }
10168: 			}
10169: 		    }
10170: 		} else {
10171: #
10172: # This is not a package - some other kind of start tag
10173: #
10174: 		    my $entry=$token->[1];
10175: 		    my $unikey='';
10176: 
10177: 		    if ($entry eq 'import') {
10178: #
10179: # Importing a library here
10180: #
10181:                         my $location=$parser->get_text('/import');
10182:                         my $dir=$filename;
10183:                         $dir=~s|[^/]*$||;
10184:                         $location=&filelocation($dir,$location);
10185:                        
10186:                         my $importmode=$token->[2]->{'importmode'};
10187:                         if ($importmode eq 'problem') {
10188: # Import as problem/response
10189:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10190:                         } elsif ($importmode eq 'part') {
10191: # Import as part(s)
10192:                            $importedparts=1;
10193: # We need to get the original file and the imported file to get the part order correct
10194: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10195: # Load and inspect original file
10196:                            if ($#origfileimportpartids<0) {
10197:                               undef(%importedpartids);
10198:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10199:                               my $origfile=&getfile($origfilelocation);
10200:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10201:                            }
10202: 
10203: # Load and inspect imported file
10204:                            my $impfile=&getfile($location);
10205:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10206:                            if ($#impfilepartids>=0) {
10207: # This problem had parts
10208:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10209:                            } else {
10210: # Importing by turning a single problem into a problem part
10211: # It gets the import-tags ID as part-ID
10212:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10213:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10214:                            }
10215:                         } else {
10216: # Normal import
10217:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10218:                            if (defined($token->[2]->{'id'})) {
10219:                               $unikey.='_'.$token->[2]->{'id'};
10220:                            }
10221:                         }
10222: 
10223: 			if ($depthcount<20) {
10224: 			    my $metadata = 
10225: 				&metadata($uri,'keys', $location,$unikey,
10226: 					  $depthcount+1);
10227: 			    foreach my $meta (split(',',$metadata)) {
10228: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10229: 				$metathesekeys{$meta}=1;
10230: 			    }
10231: 			
10232:                         }
10233: 		    } else {
10234: #
10235: # Not importing, some other kind of non-package, non-library start tag
10236: # 
10237:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10238:                         if (defined($token->[2]->{'id'})) {
10239:                             $unikey.='_'.$token->[2]->{'id'};
10240:                         }
10241: 			if (defined($token->[2]->{'name'})) { 
10242: 			    $unikey.='_'.$token->[2]->{'name'}; 
10243: 			}
10244: 			$metathesekeys{$unikey}=1;
10245: 			foreach my $param (@{$token->[3]}) {
10246: 			    $metaentry{':'.$unikey.'.'.$param} =
10247: 				$token->[2]->{$param};
10248: 			}
10249: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10250: 			my $default=$metaentry{':'.$unikey.'.default'};
10251: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10252: 		 # only ws inside the tag, and not in default, so use default
10253: 		 # as value
10254: 			    $metaentry{':'.$unikey}=$default;
10255: 			} elsif ( $internaltext =~ /\S/ ) {
10256: 		  # something interesting inside the tag
10257: 			    $metaentry{':'.$unikey}=$internaltext;
10258: 			} else {
10259: 		  # no interesting values, don't set a default
10260: 			}
10261: # end of not-a-package not-a-library import
10262: 		    }
10263: # end of not-a-package start tag
10264: 		}
10265: # the next is the end of "start tag"
10266: 	    }
10267: 	}
10268: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10269: 	$extension = lc($extension);
10270: 	if ($extension eq 'htm') { $extension='html'; }
10271: 
10272: 	foreach my $key (keys(%packagetab)) {
10273: 	    #no specific packages #how's our extension
10274: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10275: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10276: 					 \%metathesekeys);
10277: 	}
10278: 
10279: 	if (!exists($metaentry{':packages'})
10280: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10281: 	    foreach my $key (keys(%packagetab)) {
10282: 		#no specific packages well let's get default then
10283: 		if ($key!~/^default&/) { next; }
10284: 		&metadata_create_package_def($uri,$key,'default',
10285: 					     \%metathesekeys);
10286: 	    }
10287: 	}
10288: # are there custom rights to evaluate
10289: 	if ($metaentry{':copyright'} eq 'custom') {
10290: 
10291:     #
10292:     # Importing a rights file here
10293:     #
10294: 	    unless ($depthcount) {
10295: 		my $location=$metaentry{':customdistributionfile'};
10296: 		my $dir=$filename;
10297: 		$dir=~s|[^/]*$||;
10298: 		$location=&filelocation($dir,$location);
10299: 		my $rights_metadata =
10300: 		    &metadata($uri,'keys',$location,'_rights',
10301: 			      $depthcount+1);
10302: 		foreach my $rights (split(',',$rights_metadata)) {
10303: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10304: 		    $metathesekeys{$rights}=1;
10305: 		}
10306: 	    }
10307: 	}
10308: 	# uniqifiy package listing
10309: 	my %seen;
10310: 	my @uniq_packages =
10311: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10312: 	$metaentry{':packages'} = join(',',@uniq_packages);
10313: 
10314:         if ($importedparts) {
10315: # We had imported parts and need to rebuild partorder
10316:            $metaentry{':partorder'}='';
10317:            $metathesekeys{'partorder'}=1;
10318:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10319:                if ($origfileimportpartids[$index] eq 'part') {
10320: # original part, part of the problem
10321:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10322:                } else {
10323: # we have imported parts at this position
10324:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10325:                }
10326:            }
10327:            $metaentry{':partorder'}=~s/^\,//;
10328:         }
10329: 
10330: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10331: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10332: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10333: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10334: # this is the end of "was not already recently cached
10335:     }
10336:     return $metaentry{':'.$what};
10337: }
10338: 
10339: sub metadata_create_package_def {
10340:     my ($uri,$key,$package,$metathesekeys)=@_;
10341:     my ($pack,$name,$subp)=split(/\&/,$key);
10342:     if ($subp eq 'default') { next; }
10343:     
10344:     if (defined($metaentry{':packages'})) {
10345: 	$metaentry{':packages'}.=','.$package;
10346:     } else {
10347: 	$metaentry{':packages'}=$package;
10348:     }
10349:     my $value=$packagetab{$key};
10350:     my $unikey;
10351:     $unikey='parameter_0_'.$name;
10352:     $metaentry{':'.$unikey.'.part'}=0;
10353:     $$metathesekeys{$unikey}=1;
10354:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10355: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10356:     }
10357:     if (defined($metaentry{':'.$unikey.'.default'})) {
10358: 	$metaentry{':'.$unikey}=
10359: 	    $metaentry{':'.$unikey.'.default'};
10360:     }
10361: }
10362: 
10363: sub metadata_generate_part0 {
10364:     my ($metadata,$metacache,$uri) = @_;
10365:     my %allnames;
10366:     foreach my $metakey (keys(%$metadata)) {
10367: 	if ($metakey=~/^parameter\_(.*)/) {
10368: 	  my $part=$$metacache{':'.$metakey.'.part'};
10369: 	  my $name=$$metacache{':'.$metakey.'.name'};
10370: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10371: 	    $allnames{$name}=$part;
10372: 	  }
10373: 	}
10374:     }
10375:     foreach my $name (keys(%allnames)) {
10376:       $$metadata{"parameter_0_$name"}=1;
10377:       my $key=":parameter_0_$name";
10378:       $$metacache{"$key.part"}='0';
10379:       $$metacache{"$key.name"}=$name;
10380:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10381: 					   $allnames{$name}.'_'.$name.
10382: 					   '.type'};
10383:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10384: 			     '.display'};
10385:       my $expr='[Part: '.$allnames{$name}.']';
10386:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10387:       $$metacache{"$key.display"}=$olddis;
10388:     }
10389: }
10390: 
10391: # ------------------------------------------------------ Devalidate title cache
10392: 
10393: sub devalidate_title_cache {
10394:     my ($url)=@_;
10395:     if (!$env{'request.course.id'}) { return; }
10396:     my $symb=&symbread($url);
10397:     if (!$symb) { return; }
10398:     my $key=$env{'request.course.id'}."\0".$symb;
10399:     &devalidate_cache_new('title',$key);
10400: }
10401: 
10402: # ------------------------------------------------- Get the title of a course
10403: 
10404: sub current_course_title {
10405:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10406: }
10407: # ------------------------------------------------- Get the title of a resource
10408: 
10409: sub gettitle {
10410:     my $urlsymb=shift;
10411:     my $symb=&symbread($urlsymb);
10412:     if ($symb) {
10413: 	my $key=$env{'request.course.id'}."\0".$symb;
10414: 	my ($result,$cached)=&is_cached_new('title',$key);
10415: 	if (defined($cached)) { 
10416: 	    return $result;
10417: 	}
10418: 	my ($map,$resid,$url)=&decode_symb($symb);
10419: 	my $title='';
10420: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10421: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10422: 	} else {
10423: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10424: 		    &GDBM_READER(),0640)) {
10425: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10426: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10427: 		untie(%bighash);
10428: 	    }
10429: 	}
10430: 	$title=~s/\&colon\;/\:/gs;
10431: 	if ($title) {
10432: # Remember both $symb and $title for dynamic metadata
10433:             $accesshash{$symb.'___crstitle'}=$title;
10434:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10435: # Cache this title and then return it
10436: 	    return &do_cache_new('title',$key,$title,600);
10437: 	}
10438: 	$urlsymb=$url;
10439:     }
10440:     my $title=&metadata($urlsymb,'title');
10441:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10442:     return $title;
10443: }
10444: 
10445: sub get_slot {
10446:     my ($which,$cnum,$cdom)=@_;
10447:     if (!$cnum || !$cdom) {
10448: 	(undef,my $courseid)=&whichuser();
10449: 	$cdom=$env{'course.'.$courseid.'.domain'};
10450: 	$cnum=$env{'course.'.$courseid.'.num'};
10451:     }
10452:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10453:     my %slotinfo;
10454:     if (exists($remembered{$key})) {
10455: 	$slotinfo{$which} = $remembered{$key};
10456:     } else {
10457: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10458: 	&Apache::lonhomework::showhash(%slotinfo);
10459: 	my ($tmp)=keys(%slotinfo);
10460: 	if ($tmp=~/^error:/) { return (); }
10461: 	$remembered{$key} = $slotinfo{$which};
10462:     }
10463:     if (ref($slotinfo{$which}) eq 'HASH') {
10464: 	return %{$slotinfo{$which}};
10465:     }
10466:     return $slotinfo{$which};
10467: }
10468: 
10469: sub get_reservable_slots {
10470:     my ($cnum,$cdom,$uname,$udom) = @_;
10471:     my $now = time;
10472:     my $reservable_info;
10473:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10474:     if (exists($remembered{$key})) {
10475:         $reservable_info = $remembered{$key};
10476:     } else {
10477:         my %resv;
10478:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10479:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10480:         $reservable_info = \%resv;
10481:         $remembered{$key} = $reservable_info;
10482:     }
10483:     return $reservable_info;
10484: }
10485: 
10486: sub get_course_slots {
10487:     my ($cnum,$cdom) = @_;
10488:     my $hashid=$cnum.':'.$cdom;
10489:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10490:     if (defined($cached)) {
10491:         if (ref($result) eq 'HASH') {
10492:             return %{$result};
10493:         }
10494:     } else {
10495:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10496:         my ($tmp) = keys(%slots);
10497:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10498:             &do_cache_new('allslots',$hashid,\%slots,600);
10499:             return %slots;
10500:         }
10501:     }
10502:     return;
10503: }
10504: 
10505: sub devalidate_slots_cache {
10506:     my ($cnum,$cdom)=@_;
10507:     my $hashid=$cnum.':'.$cdom;
10508:     &devalidate_cache_new('allslots',$hashid);
10509: }
10510: 
10511: sub get_coursechange {
10512:     my ($cdom,$cnum) = @_;
10513:     if ($cdom eq '' || $cnum eq '') {
10514:         return unless ($env{'request.course.id'});
10515:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10516:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10517:     }
10518:     my $hashid=$cdom.'_'.$cnum;
10519:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10520:     if ((defined($cached)) && ($change ne '')) {
10521:         return $change;
10522:     } else {
10523:         my %crshash;
10524:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10525:         if ($crshash{'internal.contentchange'} eq '') {
10526:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10527:             if ($change eq '') {
10528:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10529:                 $change = $crshash{'internal.created'};
10530:             }
10531:         } else {
10532:             $change = $crshash{'internal.contentchange'};
10533:         }
10534:         my $cachetime = 600;
10535:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10536:     }
10537:     return $change;
10538: }
10539: 
10540: sub devalidate_coursechange_cache {
10541:     my ($cnum,$cdom)=@_;
10542:     my $hashid=$cnum.':'.$cdom;
10543:     &devalidate_cache_new('crschange',$hashid);
10544: }
10545: 
10546: # ------------------------------------------------- Update symbolic store links
10547: 
10548: sub symblist {
10549:     my ($mapname,%newhash)=@_;
10550:     $mapname=&deversion(&declutter($mapname));
10551:     my %hash;
10552:     if (($env{'request.course.fn'}) && (%newhash)) {
10553:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10554:                       &GDBM_WRCREAT(),0640)) {
10555: 	    foreach my $url (keys(%newhash)) {
10556: 		next if ($url eq 'last_known'
10557: 			 && $env{'form.no_update_last_known'});
10558: 		$hash{declutter($url)}=&encode_symb($mapname,
10559: 						    $newhash{$url}->[1],
10560: 						    $newhash{$url}->[0]);
10561:             }
10562:             if (untie(%hash)) {
10563: 		return 'ok';
10564:             }
10565:         }
10566:     }
10567:     return 'error';
10568: }
10569: 
10570: # --------------------------------------------------------------- Verify a symb
10571: 
10572: sub symbverify {
10573:     my ($symb,$thisurl,$encstate)=@_;
10574:     my $thisfn=$thisurl;
10575:     $thisfn=&declutter($thisfn);
10576: # direct jump to resource in page or to a sequence - will construct own symbs
10577:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10578: # check URL part
10579:     my ($map,$resid,$url)=&decode_symb($symb);
10580: 
10581:     unless ($url eq $thisfn) { return 0; }
10582: 
10583:     $symb=&symbclean($symb);
10584:     $thisurl=&deversion($thisurl);
10585:     $thisfn=&deversion($thisfn);
10586: 
10587:     my %bighash;
10588:     my $okay=0;
10589: 
10590:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10591:                             &GDBM_READER(),0640)) {
10592:         my $noclutter;
10593:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10594:             $thisurl =~ s/\?.+$//;
10595:             if ($map =~ m{^uploaded/.+\.page$}) {
10596:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10597:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10598:                 $noclutter = 1;
10599:             }
10600:         }
10601:         my $ids;
10602:         if ($noclutter) {
10603:             $ids=$bighash{'ids_'.$thisurl};
10604:         } else {
10605:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10606:         }
10607:         unless ($ids) {
10608:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10609:             $ids=$bighash{$idkey};
10610:         }
10611:         if ($ids) {
10612: # ------------------------------------------------------------------- Has ID(s)
10613:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10614:                 $symb =~ s/\?.+$//;
10615:             }
10616: 	    foreach my $id (split(/\,/,$ids)) {
10617: 	       my ($mapid,$resid)=split(/\./,$id);
10618:                if (
10619:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10620:    eq $symb) {
10621:                    if (ref($encstate)) {
10622:                        $$encstate = $bighash{'encrypted_'.$id};
10623:                    }
10624: 		   if (($env{'request.role.adv'}) ||
10625: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10626:                        ($thisurl eq '/adm/navmaps')) {
10627: 		       $okay=1;
10628:                        last;
10629: 		   }
10630: 	       }
10631: 	   }
10632:         }
10633: 	untie(%bighash);
10634:     }
10635:     return $okay;
10636: }
10637: 
10638: # --------------------------------------------------------------- Clean-up symb
10639: 
10640: sub symbclean {
10641:     my $symb=shift;
10642:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10643: # remove version from map
10644:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10645: 
10646: # remove version from URL
10647:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10648: 
10649: # remove wrapper
10650: 
10651:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10652:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10653:     return $symb;
10654: }
10655: 
10656: # ---------------------------------------------- Split symb to find map and url
10657: 
10658: sub encode_symb {
10659:     my ($map,$resid,$url)=@_;
10660:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10661: }
10662: 
10663: sub decode_symb {
10664:     my $symb=shift;
10665:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10666:     my ($map,$resid,$url)=split(/___/,$symb);
10667:     return (&fixversion($map),$resid,&fixversion($url));
10668: }
10669: 
10670: sub fixversion {
10671:     my $fn=shift;
10672:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10673:     my %bighash;
10674:     my $uri=&clutter($fn);
10675:     my $key=$env{'request.course.id'}.'_'.$uri;
10676: # is this cached?
10677:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10678:     if (defined($cached)) { return $result; }
10679: # unfortunately not cached, or expired
10680:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10681: 	    &GDBM_READER(),0640)) {
10682:  	if ($bighash{'version_'.$uri}) {
10683:  	    my $version=$bighash{'version_'.$uri};
10684:  	    unless (($version eq 'mostrecent') || 
10685: 		    ($version==&getversion($uri))) {
10686:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10687:  	    }
10688:  	}
10689:  	untie %bighash;
10690:     }
10691:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10692: }
10693: 
10694: sub deversion {
10695:     my $url=shift;
10696:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10697:     return $url;
10698: }
10699: 
10700: # ------------------------------------------------------ Return symb list entry
10701: 
10702: sub symbread {
10703:     my ($thisfn,$donotrecurse)=@_;
10704:     my $cache_str;
10705:     if ($thisfn ne '') {
10706:         $cache_str='request.symbread.cached.'.$thisfn;
10707:         if ($env{$cache_str} ne '') {
10708:             return $env{$cache_str};
10709:         }
10710:     } else {
10711: # no filename provided? try from environment
10712:         if ($env{'request.symb'}) {
10713: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10714: 	}
10715: 	$thisfn=$env{'request.filename'};
10716:     }
10717:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10718: # is that filename actually a symb? Verify, clean, and return
10719:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10720: 	if (&symbverify($thisfn,$1)) {
10721: 	    return $env{$cache_str}=&symbclean($thisfn);
10722: 	}
10723:     }
10724:     $thisfn=declutter($thisfn);
10725:     my %hash;
10726:     my %bighash;
10727:     my $syval='';
10728:     if (($env{'request.course.fn'}) && ($thisfn)) {
10729:         my $targetfn = $thisfn;
10730:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10731:             $targetfn = 'adm/wrapper/'.$thisfn;
10732:         }
10733: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10734: 	    $targetfn=$1;
10735: 	}
10736:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10737:                       &GDBM_READER(),0640)) {
10738: 	    $syval=$hash{$targetfn};
10739:             untie(%hash);
10740:         }
10741: # ---------------------------------------------------------- There was an entry
10742:         if ($syval) {
10743: 	    #unless ($syval=~/\_\d+$/) {
10744: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10745: 		    #&appenv({'request.ambiguous' => $thisfn});
10746: 		    #return $env{$cache_str}='';
10747: 		#}    
10748: 		#$syval.=$1;
10749: 	    #}
10750:         } else {
10751: # ------------------------------------------------------- Was not in symb table
10752:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10753:                             &GDBM_READER(),0640)) {
10754: # ---------------------------------------------- Get ID(s) for current resource
10755:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10756:               unless ($ids) { 
10757:                  $ids=$bighash{'ids_/'.$thisfn};
10758:               }
10759:               unless ($ids) {
10760: # alias?
10761: 		  $ids=$bighash{'mapalias_'.$thisfn};
10762:               }
10763:               if ($ids) {
10764: # ------------------------------------------------------------------- Has ID(s)
10765:                  my @possibilities=split(/\,/,$ids);
10766:                  if ($#possibilities==0) {
10767: # ----------------------------------------------- There is only one possibility
10768: 		     my ($mapid,$resid)=split(/\./,$ids);
10769: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10770: 						    $resid,$thisfn);
10771:                  } elsif (!$donotrecurse) {
10772: # ------------------------------------------ There is more than one possibility
10773:                      my $realpossible=0;
10774:                      foreach my $id (@possibilities) {
10775: 			 my $file=$bighash{'src_'.$id};
10776:                          if (&allowed('bre',$file)) {
10777:          		    my ($mapid,$resid)=split(/\./,$id);
10778:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10779: 				$realpossible++;
10780:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10781: 						    $resid,$thisfn);
10782:                             }
10783: 			 }
10784:                      }
10785: 		     if ($realpossible!=1) { $syval=''; }
10786:                  } else {
10787:                      $syval='';
10788:                  }
10789: 	      }
10790:               untie(%bighash)
10791:            }
10792:         }
10793:         if ($syval) {
10794: 	    return $env{$cache_str}=$syval;
10795:         }
10796:     }
10797:     &appenv({'request.ambiguous' => $thisfn});
10798:     return $env{$cache_str}='';
10799: }
10800: 
10801: # ---------------------------------------------------------- Return random seed
10802: 
10803: sub numval {
10804:     my $txt=shift;
10805:     $txt=~tr/A-J/0-9/;
10806:     $txt=~tr/a-j/0-9/;
10807:     $txt=~tr/K-T/0-9/;
10808:     $txt=~tr/k-t/0-9/;
10809:     $txt=~tr/U-Z/0-5/;
10810:     $txt=~tr/u-z/0-5/;
10811:     $txt=~s/\D//g;
10812:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10813:     return int($txt);
10814: }
10815: 
10816: sub numval2 {
10817:     my $txt=shift;
10818:     $txt=~tr/A-J/0-9/;
10819:     $txt=~tr/a-j/0-9/;
10820:     $txt=~tr/K-T/0-9/;
10821:     $txt=~tr/k-t/0-9/;
10822:     $txt=~tr/U-Z/0-5/;
10823:     $txt=~tr/u-z/0-5/;
10824:     $txt=~s/\D//g;
10825:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10826:     my $total;
10827:     foreach my $val (@txts) { $total+=$val; }
10828:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10829:     return int($total);
10830: }
10831: 
10832: sub numval3 {
10833:     use integer;
10834:     my $txt=shift;
10835:     $txt=~tr/A-J/0-9/;
10836:     $txt=~tr/a-j/0-9/;
10837:     $txt=~tr/K-T/0-9/;
10838:     $txt=~tr/k-t/0-9/;
10839:     $txt=~tr/U-Z/0-5/;
10840:     $txt=~tr/u-z/0-5/;
10841:     $txt=~s/\D//g;
10842:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10843:     my $total;
10844:     foreach my $val (@txts) { $total+=$val; }
10845:     if ($_64bit) { $total=(($total<<32)>>32); }
10846:     return $total;
10847: }
10848: 
10849: sub digest {
10850:     my ($data)=@_;
10851:     my $digest=&Digest::MD5::md5($data);
10852:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10853:     my ($e,$f);
10854:     {
10855:         use integer;
10856:         $e=($a+$b);
10857:         $f=($c+$d);
10858:         if ($_64bit) {
10859:             $e=(($e<<32)>>32);
10860:             $f=(($f<<32)>>32);
10861:         }
10862:     }
10863:     if (wantarray) {
10864: 	return ($e,$f);
10865:     } else {
10866: 	my $g;
10867: 	{
10868: 	    use integer;
10869: 	    $g=($e+$f);
10870: 	    if ($_64bit) {
10871: 		$g=(($g<<32)>>32);
10872: 	    }
10873: 	}
10874: 	return $g;
10875:     }
10876: }
10877: 
10878: sub latest_rnd_algorithm_id {
10879:     return '64bit5';
10880: }
10881: 
10882: sub get_rand_alg {
10883:     my ($courseid)=@_;
10884:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10885:     if ($courseid) {
10886: 	return $env{"course.$courseid.rndseed"};
10887:     }
10888:     return &latest_rnd_algorithm_id();
10889: }
10890: 
10891: sub validCODE {
10892:     my ($CODE)=@_;
10893:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10894:     return 0;
10895: }
10896: 
10897: sub getCODE {
10898:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10899:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10900: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10901: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10902: 	return $Apache::lonhomework::history{'resource.CODE'};
10903:     }
10904:     return undef;
10905: }
10906: #
10907: #  Determines the random seed for a specific context:
10908: #
10909: # parameters:
10910: #   symb      - in course context the symb for the seed.
10911: #   course_id - The course id of the form domain_coursenum.
10912: #   domain    - Domain for the user.
10913: #   course    - Course for the user.
10914: #   cenv      - environment of the course.
10915: #
10916: # NOTE:
10917: #   All parameters are picked out of the environment if missing
10918: #   or not defined.
10919: #   If a symb cannot be determined the current time is used instead.
10920: #
10921: #  For a given well defined symb, courside, domain, username,
10922: #  and course environment, the seed is reproducible.
10923: #
10924: sub rndseed {
10925:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10926:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10927:     if (!defined($symb)) {
10928: 	unless ($symb=$wsymb) { return time; }
10929:     }
10930:     if (!defined $courseid) { 
10931: 	$courseid=$wcourseid; 
10932:     }
10933:     if (!defined $domain) { $domain=$wdomain; }
10934:     if (!defined $username) { $username=$wusername }
10935: 
10936:     my $which;
10937:     if (defined($cenv->{'rndseed'})) {
10938: 	$which = $cenv->{'rndseed'};
10939:     } else {
10940: 	$which =&get_rand_alg($courseid);
10941:     }
10942:     if (defined(&getCODE())) {
10943: 
10944: 	if ($which eq '64bit5') {
10945: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10946: 	} elsif ($which eq '64bit4') {
10947: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10948: 	} else {
10949: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10950: 	}
10951:     } elsif ($which eq '64bit5') {
10952: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10953:     } elsif ($which eq '64bit4') {
10954: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10955:     } elsif ($which eq '64bit3') {
10956: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10957:     } elsif ($which eq '64bit2') {
10958: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10959:     } elsif ($which eq '64bit') {
10960: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10961:     }
10962:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10963: }
10964: 
10965: sub rndseed_32bit {
10966:     my ($symb,$courseid,$domain,$username)=@_;
10967:     {
10968: 	use integer;
10969: 	my $symbchck=unpack("%32C*",$symb) << 27;
10970: 	my $symbseed=numval($symb) << 22;
10971: 	my $namechck=unpack("%32C*",$username) << 17;
10972: 	my $nameseed=numval($username) << 12;
10973: 	my $domainseed=unpack("%32C*",$domain) << 7;
10974: 	my $courseseed=unpack("%32C*",$courseid);
10975: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10976: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10977: 	#&logthis("rndseed :$num:$symb");
10978: 	if ($_64bit) { $num=(($num<<32)>>32); }
10979: 	return $num;
10980:     }
10981: }
10982: 
10983: sub rndseed_64bit {
10984:     my ($symb,$courseid,$domain,$username)=@_;
10985:     {
10986: 	use integer;
10987: 	my $symbchck=unpack("%32S*",$symb) << 21;
10988: 	my $symbseed=numval($symb) << 10;
10989: 	my $namechck=unpack("%32S*",$username);
10990: 	
10991: 	my $nameseed=numval($username) << 21;
10992: 	my $domainseed=unpack("%32S*",$domain) << 10;
10993: 	my $courseseed=unpack("%32S*",$courseid);
10994: 	
10995: 	my $num1=$symbchck+$symbseed+$namechck;
10996: 	my $num2=$nameseed+$domainseed+$courseseed;
10997: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10998: 	#&logthis("rndseed :$num:$symb");
10999: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11000: 	return "$num1,$num2";
11001:     }
11002: }
11003: 
11004: sub rndseed_64bit2 {
11005:     my ($symb,$courseid,$domain,$username)=@_;
11006:     {
11007: 	use integer;
11008: 	# strings need to be an even # of cahracters long, it it is odd the
11009:         # last characters gets thrown away
11010: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11011: 	my $symbseed=numval($symb) << 10;
11012: 	my $namechck=unpack("%32S*",$username.' ');
11013: 	
11014: 	my $nameseed=numval($username) << 21;
11015: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11016: 	my $courseseed=unpack("%32S*",$courseid.' ');
11017: 	
11018: 	my $num1=$symbchck+$symbseed+$namechck;
11019: 	my $num2=$nameseed+$domainseed+$courseseed;
11020: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11021: 	#&logthis("rndseed :$num:$symb");
11022: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11023: 	return "$num1,$num2";
11024:     }
11025: }
11026: 
11027: sub rndseed_64bit3 {
11028:     my ($symb,$courseid,$domain,$username)=@_;
11029:     {
11030: 	use integer;
11031: 	# strings need to be an even # of cahracters long, it it is odd the
11032:         # last characters gets thrown away
11033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11034: 	my $symbseed=numval2($symb) << 10;
11035: 	my $namechck=unpack("%32S*",$username.' ');
11036: 	
11037: 	my $nameseed=numval2($username) << 21;
11038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11039: 	my $courseseed=unpack("%32S*",$courseid.' ');
11040: 	
11041: 	my $num1=$symbchck+$symbseed+$namechck;
11042: 	my $num2=$nameseed+$domainseed+$courseseed;
11043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11044: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11046: 	
11047: 	return "$num1:$num2";
11048:     }
11049: }
11050: 
11051: sub rndseed_64bit4 {
11052:     my ($symb,$courseid,$domain,$username)=@_;
11053:     {
11054: 	use integer;
11055: 	# strings need to be an even # of cahracters long, it it is odd the
11056:         # last characters gets thrown away
11057: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11058: 	my $symbseed=numval3($symb) << 10;
11059: 	my $namechck=unpack("%32S*",$username.' ');
11060: 	
11061: 	my $nameseed=numval3($username) << 21;
11062: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11063: 	my $courseseed=unpack("%32S*",$courseid.' ');
11064: 	
11065: 	my $num1=$symbchck+$symbseed+$namechck;
11066: 	my $num2=$nameseed+$domainseed+$courseseed;
11067: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11068: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11069: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11070: 	
11071: 	return "$num1:$num2";
11072:     }
11073: }
11074: 
11075: sub rndseed_64bit5 {
11076:     my ($symb,$courseid,$domain,$username)=@_;
11077:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11078:     return "$num1:$num2";
11079: }
11080: 
11081: sub rndseed_CODE_64bit {
11082:     my ($symb,$courseid,$domain,$username)=@_;
11083:     {
11084: 	use integer;
11085: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11086: 	my $symbseed=numval2($symb);
11087: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11088: 	my $CODEseed=numval(&getCODE());
11089: 	my $courseseed=unpack("%32S*",$courseid.' ');
11090: 	my $num1=$symbseed+$CODEchck;
11091: 	my $num2=$CODEseed+$courseseed+$symbchck;
11092: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11093: 	#&logthis("rndseed :$num1:$num2:$symb");
11094: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11095: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11096: 	return "$num1:$num2";
11097:     }
11098: }
11099: 
11100: sub rndseed_CODE_64bit4 {
11101:     my ($symb,$courseid,$domain,$username)=@_;
11102:     {
11103: 	use integer;
11104: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11105: 	my $symbseed=numval3($symb);
11106: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11107: 	my $CODEseed=numval3(&getCODE());
11108: 	my $courseseed=unpack("%32S*",$courseid.' ');
11109: 	my $num1=$symbseed+$CODEchck;
11110: 	my $num2=$CODEseed+$courseseed+$symbchck;
11111: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11112: 	#&logthis("rndseed :$num1:$num2:$symb");
11113: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11114: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11115: 	return "$num1:$num2";
11116:     }
11117: }
11118: 
11119: sub rndseed_CODE_64bit5 {
11120:     my ($symb,$courseid,$domain,$username)=@_;
11121:     my $code = &getCODE();
11122:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11123:     return "$num1:$num2";
11124: }
11125: 
11126: sub setup_random_from_rndseed {
11127:     my ($rndseed)=@_;
11128:     if ($rndseed =~/([,:])/) {
11129: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11130: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11131:     } else {
11132: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11133:     }
11134: }
11135: 
11136: sub latest_receipt_algorithm_id {
11137:     return 'receipt3';
11138: }
11139: 
11140: sub recunique {
11141:     my $fucourseid=shift;
11142:     my $unique;
11143:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11144: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11145: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11146:     } else {
11147: 	$unique=$perlvar{'lonReceipt'};
11148:     }
11149:     return unpack("%32C*",$unique);
11150: }
11151: 
11152: sub recprefix {
11153:     my $fucourseid=shift;
11154:     my $prefix;
11155:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11156: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11157: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11158:     } else {
11159: 	$prefix=$perlvar{'lonHostID'};
11160:     }
11161:     return unpack("%32C*",$prefix);
11162: }
11163: 
11164: sub ireceipt {
11165:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11166: 
11167:     my $return =&recprefix($fucourseid).'-';
11168: 
11169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11170: 	$env{'request.state'} eq 'construct') {
11171: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11172: 	return $return;
11173:     }
11174: 
11175:     my $cuname=unpack("%32C*",$funame);
11176:     my $cudom=unpack("%32C*",$fudom);
11177:     my $cucourseid=unpack("%32C*",$fucourseid);
11178:     my $cusymb=unpack("%32C*",$fusymb);
11179:     my $cunique=&recunique($fucourseid);
11180:     my $cpart=unpack("%32S*",$part);
11181:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11182: 
11183: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11184: 			       
11185: 	$return.= ($cunique%$cuname+
11186: 		   $cunique%$cudom+
11187: 		   $cusymb%$cuname+
11188: 		   $cusymb%$cudom+
11189: 		   $cucourseid%$cuname+
11190: 		   $cucourseid%$cudom+
11191: 		   $cpart%$cuname+
11192: 		   $cpart%$cudom);
11193:     } else {
11194: 	$return.= ($cunique%$cuname+
11195: 		   $cunique%$cudom+
11196: 		   $cusymb%$cuname+
11197: 		   $cusymb%$cudom+
11198: 		   $cucourseid%$cuname+
11199: 		   $cucourseid%$cudom);
11200:     }
11201:     return $return;
11202: }
11203: 
11204: sub receipt {
11205:     my ($part)=@_;
11206:     my ($symb,$courseid,$domain,$name) = &whichuser();
11207:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11208: }
11209: 
11210: sub whichuser {
11211:     my ($passedsymb)=@_;
11212:     my ($symb,$courseid,$domain,$name,$publicuser);
11213:     if (defined($env{'form.grade_symb'})) {
11214: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11215: 	my $allowed=&allowed('vgr',$tmp_courseid);
11216: 	if (!$allowed &&
11217: 	    exists($env{'request.course.sec'}) &&
11218: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11219: 	    $allowed=&allowed('vgr',$tmp_courseid.
11220: 			      '/'.$env{'request.course.sec'});
11221: 	}
11222: 	if ($allowed) {
11223: 	    ($symb)=&get_env_multiple('form.grade_symb');
11224: 	    $courseid=$tmp_courseid;
11225: 	    ($domain)=&get_env_multiple('form.grade_domain');
11226: 	    ($name)=&get_env_multiple('form.grade_username');
11227: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11228: 	}
11229:     }
11230:     if (!$passedsymb) {
11231: 	$symb=&symbread();
11232:     } else {
11233: 	$symb=$passedsymb;
11234:     }
11235:     $courseid=$env{'request.course.id'};
11236:     $domain=$env{'user.domain'};
11237:     $name=$env{'user.name'};
11238:     if ($name eq 'public' && $domain eq 'public') {
11239: 	if (!defined($env{'form.username'})) {
11240: 	    $env{'form.username'}.=time.rand(10000000);
11241: 	}
11242: 	$name.=$env{'form.username'};
11243:     }
11244:     return ($symb,$courseid,$domain,$name,$publicuser);
11245: 
11246: }
11247: 
11248: # ------------------------------------------------------------ Serves up a file
11249: # returns either the contents of the file or 
11250: # -1 if the file doesn't exist
11251: #
11252: # if the target is a file that was uploaded via DOCS, 
11253: # a check will be made to see if a current copy exists on the local server,
11254: # if it does this will be served, otherwise a copy will be retrieved from
11255: # the home server for the course and stored in /home/httpd/html/userfiles on
11256: # the local server.   
11257: 
11258: sub getfile {
11259:     my ($file) = @_;
11260:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11261:     &repcopy($file);
11262:     return &readfile($file);
11263: }
11264: 
11265: sub repcopy_userfile {
11266:     my ($file)=@_;
11267:     my $londocroot = $perlvar{'lonDocRoot'};
11268:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11269:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11270:     my ($cdom,$cnum,$filename) = 
11271: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11272:     my $uri="/uploaded/$cdom/$cnum/$filename";
11273:     if (-e "$file") {
11274: # we already have a local copy, check it out
11275: 	my @fileinfo = stat($file);
11276: 	my $rtncode;
11277: 	my $info;
11278: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11279: 	if ($lwpresp ne 'ok') {
11280: # there is no such file anymore, even though we had a local copy
11281: 	    if ($rtncode eq '404') {
11282: 		unlink($file);
11283: 	    }
11284: 	    return -1;
11285: 	}
11286: 	if ($info < $fileinfo[9]) {
11287: # nice, the file we have is up-to-date, just say okay
11288: 	    return 'ok';
11289: 	} else {
11290: # the file is outdated, get rid of it
11291: 	    unlink($file);
11292: 	}
11293:     }
11294: # one way or the other, at this point, we don't have the file
11295: # construct the correct path for the file
11296:     my @parts = ($cdom,$cnum); 
11297:     if ($filename =~ m|^(.+)/[^/]+$|) {
11298: 	push @parts, split(/\//,$1);
11299:     }
11300:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11301:     foreach my $part (@parts) {
11302: 	$path .= '/'.$part;
11303: 	if (!-e $path) {
11304: 	    mkdir($path,0770);
11305: 	}
11306:     }
11307: # now the path exists for sure
11308: # get a user agent
11309:     my $ua=new LWP::UserAgent;
11310:     my $transferfile=$file.'.in.transfer';
11311: # FIXME: this should flock
11312:     if (-e $transferfile) { return 'ok'; }
11313:     my $request;
11314:     $uri=~s/^\///;
11315:     my $homeserver = &homeserver($cnum,$cdom);
11316:     my $protocol = $protocol{$homeserver};
11317:     $protocol = 'http' if ($protocol ne 'https');
11318:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11319:     my $response=$ua->request($request,$transferfile);
11320: # did it work?
11321:     if ($response->is_error()) {
11322: 	unlink($transferfile);
11323: 	&logthis("Userfile repcopy failed for $uri");
11324: 	return -1;
11325:     }
11326: # worked, rename the transfer file
11327:     rename($transferfile,$file);
11328:     return 'ok';
11329: }
11330: 
11331: sub tokenwrapper {
11332:     my $uri=shift;
11333:     $uri=~s|^https?\://([^/]+)||;
11334:     $uri=~s|^/||;
11335:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11336:     my $token=$1;
11337:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11338:     if ($udom && $uname && $file) {
11339: 	$file=~s|(\?\.*)*$||;
11340:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11341:         my $homeserver = &homeserver($uname,$udom);
11342:         my $protocol = $protocol{$homeserver};
11343:         $protocol = 'http' if ($protocol ne 'https');
11344:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11345:                (($uri=~/\?/)?'&':'?').'token='.$token.
11346:                                '&tokenissued='.$perlvar{'lonHostID'};
11347:     } else {
11348:         return '/adm/notfound.html';
11349:     }
11350: }
11351: 
11352: # call with reqtype HEAD: get last modification time
11353: # call with reqtype GET: get the file contents
11354: # Do not call this with reqtype GET for large files! It loads everything into memory
11355: #
11356: sub getuploaded {
11357:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11358:     $uri=~s/^\///;
11359:     my $homeserver = &homeserver($cnum,$cdom);
11360:     my $protocol = $protocol{$homeserver};
11361:     $protocol = 'http' if ($protocol ne 'https');
11362:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11363:     my $ua=new LWP::UserAgent;
11364:     my $request=new HTTP::Request($reqtype,$uri);
11365:     my $response=$ua->request($request);
11366:     $$rtncode = $response->code;
11367:     if (! $response->is_success()) {
11368: 	return 'failed';
11369:     }      
11370:     if ($reqtype eq 'HEAD') {
11371: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11372:     } elsif ($reqtype eq 'GET') {
11373: 	$$info = $response->content;
11374:     }
11375:     return 'ok';
11376: }
11377: 
11378: sub readfile {
11379:     my $file = shift;
11380:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11381:     my $fh;
11382:     open($fh,"<$file");
11383:     my $a='';
11384:     while (my $line = <$fh>) { $a .= $line; }
11385:     return $a;
11386: }
11387: 
11388: sub filelocation {
11389:     my ($dir,$file) = @_;
11390:     my $location;
11391:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11392: 
11393:     if ($file =~ m-^/adm/-) {
11394: 	$file=~s-^/adm/wrapper/-/-;
11395: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11396:     }
11397: 
11398:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11399:         $location = $file;
11400:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11401:         my ($udom,$uname,$filename)=
11402:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11403:         my $home=&homeserver($uname,$udom);
11404:         my $is_me=0;
11405:         my @ids=&current_machine_ids();
11406:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11407:         if ($is_me) {
11408:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11409:         } else {
11410:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11411:   	      $udom.'/'.$uname.'/'.$filename;
11412:         }
11413:     } elsif ($file =~ m-^/adm/-) {
11414: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11415:     } else {
11416:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11417:         $file=~s:^/(res|priv)/:/:;
11418:         my $space=$1;
11419:         if ( !( $file =~ m:^/:) ) {
11420:             $location = $dir. '/'.$file;
11421:         } else {
11422:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11423:         }
11424:     }
11425:     $location=~s://+:/:g; # remove duplicate /
11426:     while ($location=~m{/\.\./}) {
11427: 	if ($location =~ m{/[^/]+/\.\./}) {
11428: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11429: 	} else {
11430: 	    $location=~ s{/\.\./}{/}g;
11431: 	}
11432:     } #remove dir/..
11433:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11434:     return $location;
11435: }
11436: 
11437: sub hreflocation {
11438:     my ($dir,$file)=@_;
11439:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11440: 	$file=filelocation($dir,$file);
11441:     } elsif ($file=~m-^/adm/-) {
11442: 	$file=~s-^/adm/wrapper/-/-;
11443: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11444:     }
11445:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11446: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11447:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11448: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11449: 	        {/uploaded/$1/$2/}x;
11450:     }
11451:     if ($file=~ m{^/userfiles/}) {
11452: 	$file =~ s{^/userfiles/}{/uploaded/};
11453:     }
11454:     return $file;
11455: }
11456: 
11457: 
11458: 
11459: 
11460: 
11461: sub current_machine_domains {
11462:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11463: }
11464: 
11465: sub machine_domains {
11466:     my ($hostname) = @_;
11467:     my @domains;
11468:     my %hostname = &all_hostnames();
11469:     while( my($id, $name) = each(%hostname)) {
11470: #	&logthis("-$id-$name-$hostname-");
11471: 	if ($hostname eq $name) {
11472: 	    push(@domains,&host_domain($id));
11473: 	}
11474:     }
11475:     return @domains;
11476: }
11477: 
11478: sub current_machine_ids {
11479:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11480: }
11481: 
11482: sub machine_ids {
11483:     my ($hostname) = @_;
11484:     $hostname ||= &hostname($perlvar{'lonHostID'});
11485:     my @ids;
11486:     my %name_to_host = &all_names();
11487:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11488: 	return @{ $name_to_host{$hostname} };
11489:     }
11490:     return;
11491: }
11492: 
11493: sub additional_machine_domains {
11494:     my @domains;
11495:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11496:     while( my $line = <$fh>) {
11497:         $line =~ s/\s//g;
11498:         push(@domains,$line);
11499:     }
11500:     return @domains;
11501: }
11502: 
11503: sub default_login_domain {
11504:     my $domain = $perlvar{'lonDefDomain'};
11505:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11506:     foreach my $posdom (&current_machine_domains(),
11507:                         &additional_machine_domains()) {
11508:         if (lc($posdom) eq lc($testdomain)) {
11509:             $domain=$posdom;
11510:             last;
11511:         }
11512:     }
11513:     return $domain;
11514: }
11515: 
11516: # ------------------------------------------------------------- Declutters URLs
11517: 
11518: sub declutter {
11519:     my $thisfn=shift;
11520:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11521:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11522:     $thisfn=~s/^\///;
11523:     $thisfn=~s|^adm/wrapper/||;
11524:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11525:     $thisfn=~s/^res\///;
11526:     $thisfn=~s/^priv\///;
11527:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11528:         $thisfn=~s/\?.+$//;
11529:     }
11530:     return $thisfn;
11531: }
11532: 
11533: # ------------------------------------------------------------- Clutter up URLs
11534: 
11535: sub clutter {
11536:     my $thisfn='/'.&declutter(shift);
11537:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11538: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11539:        $thisfn='/res'.$thisfn; 
11540:     }
11541:     if ($thisfn !~m|^/adm|) {
11542: 	if ($thisfn =~ m|^/ext/|) {
11543: 	    $thisfn='/adm/wrapper'.$thisfn;
11544: 	} else {
11545: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11546: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11547: 	    if ($embstyle eq 'ssi'
11548: 		|| ($embstyle eq 'hdn')
11549: 		|| ($embstyle eq 'rat')
11550: 		|| ($embstyle eq 'prv')
11551: 		|| ($embstyle eq 'ign')) {
11552: 		#do nothing with these
11553: 	    } elsif (($embstyle eq 'img') 
11554: 		|| ($embstyle eq 'emb')
11555: 		|| ($embstyle eq 'wrp')) {
11556: 		$thisfn='/adm/wrapper'.$thisfn;
11557: 	    } elsif ($embstyle eq 'unk'
11558: 		     && $thisfn!~/\.(sequence|page)$/) {
11559: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11560: 	    } else {
11561: #		&logthis("Got a blank emb style");
11562: 	    }
11563: 	}
11564:     }
11565:     return $thisfn;
11566: }
11567: 
11568: sub clutter_with_no_wrapper {
11569:     my $uri = &clutter(shift);
11570:     if ($uri =~ m-^/adm/-) {
11571: 	$uri =~ s-^/adm/wrapper/-/-;
11572: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11573:     }
11574:     return $uri;
11575: }
11576: 
11577: sub freeze_escape {
11578:     my ($value)=@_;
11579:     if (ref($value)) {
11580: 	$value=&nfreeze($value);
11581: 	return '__FROZEN__'.&escape($value);
11582:     }
11583:     return &escape($value);
11584: }
11585: 
11586: 
11587: sub thaw_unescape {
11588:     my ($value)=@_;
11589:     if ($value =~ /^__FROZEN__/) {
11590: 	substr($value,0,10,undef);
11591: 	$value=&unescape($value);
11592: 	return &thaw($value);
11593:     }
11594:     return &unescape($value);
11595: }
11596: 
11597: sub correct_line_ends {
11598:     my ($result)=@_;
11599:     $$result =~s/\r\n/\n/mg;
11600:     $$result =~s/\r/\n/mg;
11601: }
11602: # ================================================================ Main Program
11603: 
11604: sub goodbye {
11605:    &logthis("Starting Shut down");
11606: #not converted to using infrastruture and probably shouldn't be
11607:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11608: #converted
11609: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11610:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11611: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11612: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11613: #1.1 only
11614: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11615: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11616: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11617: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11618:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11619:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11620:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11621:    &flushcourselogs();
11622:    &logthis("Shutting down");
11623: }
11624: 
11625: sub get_dns {
11626:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11627:     if (!$ignore_cache) {
11628: 	my ($content,$cached)=
11629: 	    &Apache::lonnet::is_cached_new('dns',$url);
11630: 	if ($cached) {
11631: 	    &$func($content,$hashref);
11632: 	    return;
11633: 	}
11634:     }
11635: 
11636:     my %alldns;
11637:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11638:     foreach my $dns (<$config>) {
11639: 	next if ($dns !~ /^\^(\S*)/x);
11640:         my $line = $1;
11641:         my ($host,$protocol) = split(/:/,$line);
11642:         if ($protocol ne 'https') {
11643:             $protocol = 'http';
11644:         }
11645: 	$alldns{$host} = $protocol;
11646:     }
11647:     while (%alldns) {
11648: 	my ($dns) = keys(%alldns);
11649: 	my $ua=new LWP::UserAgent;
11650:         $ua->timeout(30);
11651: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11652: 	my $response=$ua->request($request);
11653:         delete($alldns{$dns});
11654: 	next if ($response->is_error());
11655: 	my @content = split("\n",$response->content);
11656: 	unless ($nocache) {
11657: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11658: 	}
11659: 	&$func(\@content,$hashref);
11660: 	return;
11661:     }
11662:     close($config);
11663:     my $which = (split('/',$url))[3];
11664:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11665:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11666:     my @content = <$config>;
11667:     &$func(\@content,$hashref);
11668:     return;
11669: }
11670: 
11671: # ------------------------------------------------------Get DNS checksums file
11672: sub parse_dns_checksums_tab {
11673:     my ($lines,$hashref) = @_;
11674:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11675:     my $loncaparev = &get_server_loncaparev($machine_dom);
11676:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11677:     my (%chksum,%revnum);
11678:     if (ref($lines) eq 'ARRAY') {
11679:         chomp(@{$lines});
11680:         my $versions = shift(@{$lines});
11681:         my %supported;
11682:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11683:             my $releaseslist = $1;
11684:             if ($releaseslist =~ /,/) {
11685:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
11686:             } elsif ($releaseslist) {
11687:                 $supported{$releaseslist} = 1;
11688:             }
11689:         }
11690:         if ($supported{$release}) {  
11691:             my $matchthis = 0;
11692:             foreach my $line (@{$lines}) {
11693:                 if ($line =~ /^(\d[\w\.]+)$/) {
11694:                     if ($matchthis) {
11695:                         last;
11696:                     } elsif ($1 eq $release) {
11697:                         $matchthis = 1;
11698:                     }
11699:                 } elsif ($matchthis) {
11700:                     my ($file,$version,$shasum) = split(/,/,$line);
11701:                     $chksum{$file} = $shasum;
11702:                     $revnum{$file} = $version;
11703:                 }
11704:             }
11705:             if (ref($hashref) eq 'HASH') {
11706:                 %{$hashref} = (
11707:                                 sums     => \%chksum,
11708:                                 versions => \%revnum,
11709:                               );
11710:             }
11711:         }
11712:     }
11713:     return;
11714: }
11715: 
11716: sub fetch_dns_checksums {
11717:     my %checksums; 
11718:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11719:              \%checksums);
11720:     return \%checksums;
11721: }
11722: 
11723: # ------------------------------------------------------------ Read domain file
11724: {
11725:     my $loaded;
11726:     my %domain;
11727: 
11728:     sub parse_domain_tab {
11729: 	my ($lines) = @_;
11730: 	foreach my $line (@$lines) {
11731: 	    next if ($line =~ /^(\#|\s*$ )/x);
11732: 
11733: 	    chomp($line);
11734: 	    my ($name,@elements) = split(/:/,$line,9);
11735: 	    my %this_domain;
11736: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11737: 			       'lang_def', 'city', 'longi', 'lati',
11738: 			       'primary') {
11739: 		$this_domain{$field} = shift(@elements);
11740: 	    }
11741: 	    $domain{$name} = \%this_domain;
11742: 	}
11743:     }
11744: 
11745:     sub reset_domain_info {
11746: 	undef($loaded);
11747: 	undef(%domain);
11748:     }
11749: 
11750:     sub load_domain_tab {
11751: 	my ($ignore_cache) = @_;
11752: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11753: 	my $fh;
11754: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11755: 	    my @lines = <$fh>;
11756: 	    &parse_domain_tab(\@lines);
11757: 	}
11758: 	close($fh);
11759: 	$loaded = 1;
11760:     }
11761: 
11762:     sub domain {
11763: 	&load_domain_tab() if (!$loaded);
11764: 
11765: 	my ($name,$what) = @_;
11766: 	return if ( !exists($domain{$name}) );
11767: 
11768: 	if (!$what) {
11769: 	    return $domain{$name}{'description'};
11770: 	}
11771: 	return $domain{$name}{$what};
11772:     }
11773: 
11774:     sub domain_info {
11775:         &load_domain_tab() if (!$loaded);
11776:         return %domain;
11777:     }
11778: 
11779: }
11780: 
11781: 
11782: # ------------------------------------------------------------- Read hosts file
11783: {
11784:     my %hostname;
11785:     my %hostdom;
11786:     my %libserv;
11787:     my $loaded;
11788:     my %name_to_host;
11789:     my %internetdom;
11790:     my %LC_dns_serv;
11791: 
11792:     sub parse_hosts_tab {
11793: 	my ($file) = @_;
11794: 	foreach my $configline (@$file) {
11795: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11796:             chomp($configline);
11797: 	    if ($configline =~ /^\^/) {
11798:                 if ($configline =~ /^\^([\w.\-]+)/) {
11799:                     $LC_dns_serv{$1} = 1;
11800:                 }
11801:                 next;
11802:             }
11803: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11804: 	    $name=~s/\s//g;
11805: 	    if ($id && $domain && $role && $name) {
11806: 		$hostname{$id}=$name;
11807: 		push(@{$name_to_host{$name}}, $id);
11808: 		$hostdom{$id}=$domain;
11809: 		if ($role eq 'library') { $libserv{$id}=$name; }
11810:                 if (defined($protocol)) {
11811:                     if ($protocol eq 'https') {
11812:                         $protocol{$id} = $protocol;
11813:                     } else {
11814:                         $protocol{$id} = 'http'; 
11815:                     }
11816:                 } else {
11817:                     $protocol{$id} = 'http';
11818:                 }
11819:                 if (defined($intdom)) {
11820:                     $internetdom{$id} = $intdom;
11821:                 }
11822: 	    }
11823: 	}
11824:     }
11825:     
11826:     sub reset_hosts_info {
11827: 	&purge_remembered();
11828: 	&reset_domain_info();
11829: 	&reset_hosts_ip_info();
11830: 	undef(%name_to_host);
11831: 	undef(%hostname);
11832: 	undef(%hostdom);
11833: 	undef(%libserv);
11834: 	undef($loaded);
11835:     }
11836: 
11837:     sub load_hosts_tab {
11838: 	my ($ignore_cache) = @_;
11839: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11840: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11841: 	my @config = <$config>;
11842: 	&parse_hosts_tab(\@config);
11843: 	close($config);
11844: 	$loaded=1;
11845:     }
11846: 
11847:     sub hostname {
11848: 	&load_hosts_tab() if (!$loaded);
11849: 
11850: 	my ($lonid) = @_;
11851: 	return $hostname{$lonid};
11852:     }
11853: 
11854:     sub all_hostnames {
11855: 	&load_hosts_tab() if (!$loaded);
11856: 
11857: 	return %hostname;
11858:     }
11859: 
11860:     sub all_names {
11861: 	&load_hosts_tab() if (!$loaded);
11862: 
11863: 	return %name_to_host;
11864:     }
11865: 
11866:     sub all_host_domain {
11867:         &load_hosts_tab() if (!$loaded);
11868:         return %hostdom;
11869:     }
11870: 
11871:     sub is_library {
11872: 	&load_hosts_tab() if (!$loaded);
11873: 
11874: 	return exists($libserv{$_[0]});
11875:     }
11876: 
11877:     sub all_library {
11878: 	&load_hosts_tab() if (!$loaded);
11879: 
11880: 	return %libserv;
11881:     }
11882: 
11883:     sub unique_library {
11884: 	#2x reverse removes all hostnames that appear more than once
11885:         my %unique = reverse &all_library();
11886:         return reverse %unique;
11887:     }
11888: 
11889:     sub get_servers {
11890: 	&load_hosts_tab() if (!$loaded);
11891: 
11892: 	my ($domain,$type) = @_;
11893: 	my %possible_hosts = ($type eq 'library') ? %libserv
11894: 	                                          : %hostname;
11895: 	my %result;
11896: 	if (ref($domain) eq 'ARRAY') {
11897: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11898: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11899: 		    $result{$host} = $hostname;
11900: 		}
11901: 	    }
11902: 	} else {
11903: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11904: 		if ($hostdom{$host} eq $domain) {
11905: 		    $result{$host} = $hostname;
11906: 		}
11907: 	    }
11908: 	}
11909: 	return %result;
11910:     }
11911: 
11912:     sub get_unique_servers {
11913:         my %unique = reverse &get_servers(@_);
11914: 	return reverse %unique;
11915:     }
11916: 
11917:     sub host_domain {
11918: 	&load_hosts_tab() if (!$loaded);
11919: 
11920: 	my ($lonid) = @_;
11921: 	return $hostdom{$lonid};
11922:     }
11923: 
11924:     sub all_domains {
11925: 	&load_hosts_tab() if (!$loaded);
11926: 
11927: 	my %seen;
11928: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11929: 	return @uniq;
11930:     }
11931: 
11932:     sub internet_dom {
11933:         &load_hosts_tab() if (!$loaded);
11934: 
11935:         my ($lonid) = @_;
11936:         return $internetdom{$lonid};
11937:     }
11938: 
11939:     sub is_LC_dns {
11940:         &load_hosts_tab() if (!$loaded);
11941: 
11942:         my ($hostname) = @_;
11943:         return exists($LC_dns_serv{$hostname});
11944:     }
11945: 
11946: }
11947: 
11948: { 
11949:     my %iphost;
11950:     my %name_to_ip;
11951:     my %lonid_to_ip;
11952: 
11953:     sub get_hosts_from_ip {
11954: 	my ($ip) = @_;
11955: 	my %iphosts = &get_iphost();
11956: 	if (ref($iphosts{$ip})) {
11957: 	    return @{$iphosts{$ip}};
11958: 	}
11959: 	return;
11960:     }
11961:     
11962:     sub reset_hosts_ip_info {
11963: 	undef(%iphost);
11964: 	undef(%name_to_ip);
11965: 	undef(%lonid_to_ip);
11966:     }
11967: 
11968:     sub get_host_ip {
11969: 	my ($lonid) = @_;
11970: 	if (exists($lonid_to_ip{$lonid})) {
11971: 	    return $lonid_to_ip{$lonid};
11972: 	}
11973: 	my $name=&hostname($lonid);
11974:    	my $ip = gethostbyname($name);
11975: 	return if (!$ip || length($ip) ne 4);
11976: 	$ip=inet_ntoa($ip);
11977: 	$name_to_ip{$name}   = $ip;
11978: 	$lonid_to_ip{$lonid} = $ip;
11979: 	return $ip;
11980:     }
11981:     
11982:     sub get_iphost {
11983: 	my ($ignore_cache) = @_;
11984: 
11985: 	if (!$ignore_cache) {
11986: 	    if (%iphost) {
11987: 		return %iphost;
11988: 	    }
11989: 	    my ($ip_info,$cached)=
11990: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11991: 	    if ($cached) {
11992: 		%iphost      = %{$ip_info->[0]};
11993: 		%name_to_ip  = %{$ip_info->[1]};
11994: 		%lonid_to_ip = %{$ip_info->[2]};
11995: 		return %iphost;
11996: 	    }
11997: 	}
11998: 
11999: 	# get yesterday's info for fallback
12000: 	my %old_name_to_ip;
12001: 	my ($ip_info,$cached)=
12002: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12003: 	if ($cached) {
12004: 	    %old_name_to_ip = %{$ip_info->[1]};
12005: 	}
12006: 
12007: 	my %name_to_host = &all_names();
12008: 	foreach my $name (keys(%name_to_host)) {
12009: 	    my $ip;
12010: 	    if (!exists($name_to_ip{$name})) {
12011: 		$ip = gethostbyname($name);
12012: 		if (!$ip || length($ip) ne 4) {
12013: 		    if (defined($old_name_to_ip{$name})) {
12014: 			$ip = $old_name_to_ip{$name};
12015: 			&logthis("Can't find $name defaulting to old $ip");
12016: 		    } else {
12017: 			&logthis("Name $name no IP found");
12018: 			next;
12019: 		    }
12020: 		} else {
12021: 		    $ip=inet_ntoa($ip);
12022: 		}
12023: 		$name_to_ip{$name} = $ip;
12024: 	    } else {
12025: 		$ip = $name_to_ip{$name};
12026: 	    }
12027: 	    foreach my $id (@{ $name_to_host{$name} }) {
12028: 		$lonid_to_ip{$id} = $ip;
12029: 	    }
12030: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12031: 	}
12032: 	&do_cache_new('iphost','iphost',
12033: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12034: 		      48*60*60);
12035: 
12036: 	return %iphost;
12037:     }
12038: 
12039:     #
12040:     #  Given a DNS returns the loncapa host name for that DNS 
12041:     # 
12042:     sub host_from_dns {
12043:         my ($dns) = @_;
12044:         my @hosts;
12045:         my $ip;
12046: 
12047:         if (exists($name_to_ip{$dns})) {
12048:             $ip = $name_to_ip{$dns};
12049:         }
12050:         if (!$ip) {
12051:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12052:             if (length($ip) == 4) { 
12053: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12054:             }
12055:         }
12056:         if ($ip) {
12057: 	    @hosts = get_hosts_from_ip($ip);
12058: 	    return $hosts[0];
12059:         }
12060:         return undef;
12061:     }
12062: 
12063:     sub get_internet_names {
12064:         my ($lonid) = @_;
12065:         return if ($lonid eq '');
12066:         my ($idnref,$cached)=
12067:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12068:         if ($cached) {
12069:             return $idnref;
12070:         }
12071:         my $ip = &get_host_ip($lonid);
12072:         my @hosts = &get_hosts_from_ip($ip);
12073:         my %iphost = &get_iphost();
12074:         my (@idns,%seen);
12075:         foreach my $id (@hosts) {
12076:             my $dom = &host_domain($id);
12077:             my $prim_id = &domain($dom,'primary');
12078:             my $prim_ip = &get_host_ip($prim_id);
12079:             next if ($seen{$prim_ip});
12080:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12081:                 foreach my $id (@{$iphost{$prim_ip}}) {
12082:                     my $intdom = &internet_dom($id);
12083:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12084:                         push(@idns,$intdom);
12085:                     }
12086:                 }
12087:             }
12088:             $seen{$prim_ip} = 1;
12089:         }
12090:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12091:     }
12092: 
12093: }
12094: 
12095: sub all_loncaparevs {
12096:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
12097: }
12098: 
12099: # ---------------------------------------------------------- Read loncaparev table
12100: {
12101:     sub load_loncaparevs { 
12102:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12103:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12104:                 while (my $configline=<$config>) {
12105:                     chomp($configline);
12106:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12107:                     $loncaparevs{$hostid}=$loncaparev;
12108:                 }
12109:                 close($config);
12110:             }
12111:         }
12112:     }
12113: }
12114: 
12115: # ---------------------------------------------------------- Read serverhostID table
12116: {
12117:     sub load_serverhomeIDs {
12118:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12119:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12120:                 while (my $configline=<$config>) {
12121:                     chomp($configline);
12122:                     my ($name,$id)=split(/:/,$configline);
12123:                     $serverhomeIDs{$name}=$id;
12124:                 }
12125:                 close($config);
12126:             }
12127:         }
12128:     }
12129: }
12130: 
12131: 
12132: BEGIN {
12133: 
12134: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12135:     unless ($readit) {
12136: {
12137:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12138:     %perlvar = (%perlvar,%{$configvars});
12139: }
12140: 
12141: 
12142: # ------------------------------------------------------ Read spare server file
12143: {
12144:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12145: 
12146:     while (my $configline=<$config>) {
12147:        chomp($configline);
12148:        if ($configline) {
12149: 	   my ($host,$type) = split(':',$configline,2);
12150: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12151: 	   push(@{ $spareid{$type} }, $host);
12152:        }
12153:     }
12154:     close($config);
12155: }
12156: # ------------------------------------------------------------ Read permissions
12157: {
12158:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12159: 
12160:     while (my $configline=<$config>) {
12161: 	chomp($configline);
12162: 	if ($configline) {
12163: 	    my ($role,$perm)=split(/ /,$configline);
12164: 	    if ($perm ne '') { $pr{$role}=$perm; }
12165: 	}
12166:     }
12167:     close($config);
12168: }
12169: 
12170: # -------------------------------------------- Read plain texts for permissions
12171: {
12172:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12173: 
12174:     while (my $configline=<$config>) {
12175: 	chomp($configline);
12176: 	if ($configline) {
12177: 	    my ($short,@plain)=split(/:/,$configline);
12178:             %{$prp{$short}} = ();
12179: 	    if (@plain > 0) {
12180:                 $prp{$short}{'std'} = $plain[0];
12181:                 for (my $i=1; $i<@plain; $i++) {
12182:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12183:                 }
12184:             }
12185: 	}
12186:     }
12187:     close($config);
12188: }
12189: 
12190: # ---------------------------------------------------------- Read package table
12191: {
12192:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12193: 
12194:     while (my $configline=<$config>) {
12195: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12196: 	chomp($configline);
12197: 	my ($short,$plain)=split(/:/,$configline);
12198: 	my ($pack,$name)=split(/\&/,$short);
12199: 	if ($plain ne '') {
12200: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12201: 	    $packagetab{$short}=$plain; 
12202: 	}
12203:     }
12204:     close($config);
12205: }
12206: 
12207: # ---------------------------------------------------------- Read loncaparev table
12208: 
12209: &load_loncaparevs();
12210: 
12211: # ---------------------------------------------------------- Read serverhostID table
12212: 
12213: &load_serverhomeIDs();
12214: 
12215: # ---------------------------------------------------------- Read releaseslist XML
12216: {
12217:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12218:     if (-e $file) {
12219:         my $parser = HTML::LCParser->new($file);
12220:         while (my $token = $parser->get_token()) {
12221:             if ($token->[0] eq 'S') {
12222:                 my $item = $token->[1];
12223:                 my $name = $token->[2]{'name'};
12224:                 my $value = $token->[2]{'value'};
12225:                 if ($item ne '' && $name ne '' && $value ne '') {
12226:                     my $release = $parser->get_text();
12227:                     $release =~ s/(^\s*|\s*$ )//gx;
12228:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12229:                 }
12230:             }
12231:         }
12232:     }
12233: }
12234: 
12235: # ---------------------------------------------------------- Read managers table
12236: {
12237:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12238:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12239:             while (my $configline=<$config>) {
12240:                 chomp($configline);
12241:                 next if ($configline =~ /^\#/);
12242:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12243:                     $managerstab{$configline} = 1;
12244:                 }
12245:             }
12246:             close($config);
12247:         }
12248:     }
12249: }
12250: 
12251: # ------------- set up temporary directory
12252: {
12253:     $tmpdir = LONCAPA::tempdir();
12254: 
12255: }
12256: 
12257: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12258: 				'compress_threshold'=> 20_000,
12259:  			        });
12260: 
12261: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12262: $dumpcount=0;
12263: $locknum=0;
12264: 
12265: &logtouch();
12266: &logthis('<font color="yellow">INFO: Read configuration</font>');
12267: $readit=1;
12268:     {
12269: 	use integer;
12270: 	my $test=(2**32)+1;
12271: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12272: 	&logthis(" Detected 64bit platform ($_64bit)");
12273:     }
12274: 
12275:     {
12276:         eval {
12277:             ($apache) =
12278:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12279:         };
12280:         if ($@) {
12281:            $apache = 1.3;
12282:         }
12283:     }
12284: 
12285: }
12286: }
12287: 
12288: 1;
12289: __END__
12290: 
12291: =pod
12292: 
12293: =head1 NAME
12294: 
12295: Apache::lonnet - Subroutines to ask questions about things in the network.
12296: 
12297: =head1 SYNOPSIS
12298: 
12299: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12300: 
12301:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12302: 
12303: Common parameters:
12304: 
12305: =over 4
12306: 
12307: =item *
12308: 
12309: $uname : an internal username (if $cname expecting a course Id specifically)
12310: 
12311: =item *
12312: 
12313: $udom : a domain (if $cdom expecting a course's domain specifically)
12314: 
12315: =item *
12316: 
12317: $symb : a resource instance identifier
12318: 
12319: =item *
12320: 
12321: $namespace : the name of a .db file that contains the data needed or
12322: being set.
12323: 
12324: =back
12325: 
12326: =head1 OVERVIEW
12327: 
12328: lonnet provides subroutines which interact with the
12329: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12330: about classes, users, and resources.
12331: 
12332: For many of these objects you can also use this to store data about
12333: them or modify them in various ways.
12334: 
12335: =head2 Symbs
12336: 
12337: To identify a specific instance of a resource, LON-CAPA uses symbols
12338: or "symbs"X<symb>. These identifiers are built from the URL of the
12339: map, the resource number of the resource in the map, and the URL of
12340: the resource itself. The latter is somewhat redundant, but might help
12341: if maps change.
12342: 
12343: An example is
12344: 
12345:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12346: 
12347: The respective map entry is
12348: 
12349:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12350:   title="Problem 2">
12351:  </resource>
12352: 
12353: Symbs are used by the random number generator, as well as to store and
12354: restore data specific to a certain instance of for example a problem.
12355: 
12356: =head2 Storing And Retrieving Data
12357: 
12358: X<store()>X<cstore()>X<restore()>Three of the most important functions
12359: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12360: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12361: is is the non-critical message twin of cstore. These functions are for
12362: handlers to store a perl hash to a user's permanent data space in an
12363: easy manner, and to retrieve it again on another call. It is expected
12364: that a handler would use this once at the beginning to retrieve data,
12365: and then again once at the end to send only the new data back.
12366: 
12367: The data is stored in the user's data directory on the user's
12368: homeserver under the ID of the course.
12369: 
12370: The hash that is returned by restore will have all of the previous
12371: value for all of the elements of the hash.
12372: 
12373: Example:
12374: 
12375:  #creating a hash
12376:  my %hash;
12377:  $hash{'foo'}='bar';
12378: 
12379:  #storing it
12380:  &Apache::lonnet::cstore(\%hash);
12381: 
12382:  #changing a value
12383:  $hash{'foo'}='notbar';
12384: 
12385:  #adding a new value
12386:  $hash{'bar'}='foo';
12387:  &Apache::lonnet::cstore(\%hash);
12388: 
12389:  #retrieving the hash
12390:  my %history=&Apache::lonnet::restore();
12391: 
12392:  #print the hash
12393:  foreach my $key (sort(keys(%history))) {
12394:    print("\%history{$key} = $history{$key}");
12395:  }
12396: 
12397: Will print out:
12398: 
12399:  %history{1:foo} = bar
12400:  %history{1:keys} = foo:timestamp
12401:  %history{1:timestamp} = 990455579
12402:  %history{2:bar} = foo
12403:  %history{2:foo} = notbar
12404:  %history{2:keys} = foo:bar:timestamp
12405:  %history{2:timestamp} = 990455580
12406:  %history{bar} = foo
12407:  %history{foo} = notbar
12408:  %history{timestamp} = 990455580
12409:  %history{version} = 2
12410: 
12411: Note that the special hash entries C<keys>, C<version> and
12412: C<timestamp> were added to the hash. C<version> will be equal to the
12413: total number of versions of the data that have been stored. The
12414: C<timestamp> attribute will be the UNIX time the hash was
12415: stored. C<keys> is available in every historical section to list which
12416: keys were added or changed at a specific historical revision of a
12417: hash.
12418: 
12419: B<Warning>: do not store the hash that restore returns directly. This
12420: will cause a mess since it will restore the historical keys as if the
12421: were new keys. I.E. 1:foo will become 1:1:foo etc.
12422: 
12423: Calling convention:
12424: 
12425:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12426:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12427: 
12428: For more detailed information, see lonnet specific documentation.
12429: 
12430: =head1 RETURN MESSAGES
12431: 
12432: =over 4
12433: 
12434: =item * B<con_lost>: unable to contact remote host
12435: 
12436: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12437: when the connection is brought back up
12438: 
12439: =item * B<con_failed>: unable to contact remote host and unable to save message
12440: for later delivery
12441: 
12442: =item * B<error:>: an error a occurred, a description of the error follows the :
12443: 
12444: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12445: that was requested
12446: 
12447: =back
12448: 
12449: =head1 PUBLIC SUBROUTINES
12450: 
12451: =head2 Session Environment Functions
12452: 
12453: =over 4
12454: 
12455: =item * 
12456: X<appenv()>
12457: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12458: the user envirnoment file, and will be restored for each access this
12459: user makes during this session, also modifies the %env for the current
12460: process. Optional rolesarrayref - if defined contains a reference to an array
12461: of roles which are exempt from the restriction on modifying user.role entries 
12462: in the user's environment.db and in %env.    
12463: 
12464: =item *
12465: X<delenv()>
12466: B<delenv($delthis,$regexp)>: removes all items from the session
12467: environment file that begin with $delthis. If the 
12468: optional second arg - $regexp - is true, $delthis is treated as a 
12469: regular expression, otherwise \Q$delthis\E is used. 
12470: The values are also deleted from the current processes %env.
12471: 
12472: =item * get_env_multiple($name) 
12473: 
12474: gets $name from the %env hash, it seemlessly handles the cases where multiple
12475: values may be defined and end up as an array ref.
12476: 
12477: returns an array of values
12478: 
12479: =back
12480: 
12481: =head2 User Information
12482: 
12483: =over 4
12484: 
12485: =item *
12486: X<queryauthenticate()>
12487: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12488: authentication scheme
12489: 
12490: =item *
12491: X<authenticate()>
12492: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12493: authenticate user from domain's lib servers (first use the current
12494: one). C<$upass> should be the users password.
12495: $checkdefauth is optional (value is 1 if a check should be made to
12496:    authenticate user using default authentication method, and allow
12497:    account creation if username does not have account in the domain).
12498: $clientcancheckhost is optional (value is 1 if checking whether the
12499:    server can host will occur on the client side in lonauth.pm).   
12500: 
12501: =item *
12502: X<homeserver()>
12503: B<homeserver($uname,$udom)>: find the server which has
12504: the user's directory and files (there must be only one), this caches
12505: the answer, and also caches if there is a borken connection.
12506: 
12507: =item *
12508: X<idget()>
12509: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12510: (IDs are a unique resource in a domain, there must be only 1 ID per
12511: username, and only 1 username per ID in a specific domain) (returns
12512: hash: id=>name,id=>name)
12513: 
12514: =item *
12515: X<idrget()>
12516: B<idrget($udom,@unames)>: find the IDs behind a list of
12517: usernames (returns hash: name=>id,name=>id)
12518: 
12519: =item *
12520: X<idput()>
12521: B<idput($udom,%ids)>: store away a list of names and associated IDs
12522: 
12523: =item *
12524: X<rolesinit()>
12525: B<rolesinit($udom,$username)>: get user privileges.
12526: returns user role, first access and timer interval hashes
12527: 
12528: =item *
12529: X<privileged()>
12530: B<privileged($username,$domain)>: returns a true if user has a
12531: privileged and active role (i.e. su or dc), false otherwise.
12532: 
12533: =item *
12534: X<getsection()>
12535: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12536: course $cname, return section name/number or '' for "not in course"
12537: and '-1' for "no section"
12538: 
12539: =item *
12540: X<userenvironment()>
12541: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12542: passed in @what from the requested user's environment, returns a hash
12543: 
12544: =item * 
12545: X<userlog_query()>
12546: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12547: activity.log file. %filters defines filters applied when parsing the
12548: log file. These can be start or end timestamps, or the type of action
12549: - log to look for Login or Logout events, check for Checkin or
12550: Checkout, role for role selection. The response is in the form
12551: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12552: escaped strings of the action recorded in the activity.log file.
12553: 
12554: =back
12555: 
12556: =head2 User Roles
12557: 
12558: =over 4
12559: 
12560: =item *
12561: 
12562: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12563:  F: full access
12564:  U,I,K: authentication modes (cxx only)
12565:  '': forbidden
12566:  1: user needs to choose course
12567:  2: browse allowed
12568:  A: passphrase authentication needed
12569: 
12570: =item *
12571: 
12572: constructaccess($url,$setpriv) : check for access to construction space URL
12573: 
12574: See if the owner domain and name in the URL match those in the
12575: expected environment.  If so, return three element list
12576: ($ownername,$ownerdomain,$ownerhome).
12577: 
12578: Otherwise return the null string.
12579: 
12580: If second argument 'setpriv' is true, it assigns the privileges,
12581: and returns the same three element list, unless the owner has
12582: blocked "ad hoc" Domain Coordinator access to the Author Space,
12583: in which case the null string is returned.
12584: 
12585: =item *
12586: 
12587: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12588: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12589: and course level
12590: 
12591: =item *
12592: 
12593: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12594: (rolesplain.tab); plain text explanation of a user role term.
12595: $type is Course (default) or Community.
12596: If $forcedefault evaluates to true, text returned will be default 
12597: text for $type. Otherwise, if this is a course, the text returned 
12598: will be a custom name for the role (if defined in the course's 
12599: environment).  If no custom name is defined the default is returned.
12600:    
12601: =item *
12602: 
12603: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12604: All arguments are optional. Returns a hash of a roles, either for
12605: co-author/assistant author roles for a user's Construction Space
12606: (default), or if $context is 'userroles', roles for the user himself,
12607: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12608: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12609: For each key, value is set to colon-separated start and end times for
12610: the role.  If no username and domain are specified, will default to
12611: current user/domain. Types, roles, and roledoms are references to arrays
12612: of role statuses (active, future or previous), roles 
12613: (e.g., cc,in, st etc.) and domains of the roles which can be used
12614: to restrict the list of roles reported. If no array ref is 
12615: provided for types, will default to return only active roles.
12616: 
12617: =item *
12618: 
12619: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12620: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12621: 
12622: Additional optional arguments are: $type (if role checking is to be restricted 
12623: to certain user status types -- previous (expired roles), active (currently
12624: available roles) or future (roles available in the future), and
12625: $hideprivileged -- if true will not report course roles for users who
12626: have active Domain Coordinator role in course's domain or in additional
12627: domains (specified in 'Domains to check for privileged users' in course
12628: environment -- set via:  Course Settings -> Classlists and staff listing).
12629: 
12630: =item *
12631: 
12632: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12633: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12634: $possdomains and $possroles are optional array refs -- to domains to check and
12635: roles to check.  If $possdomains is not specified, a dump will be done of the
12636: users' roles.db to check for a dc or su role in any domain. This can be
12637: time consuming if &privileged is called repeatedly (e.g., when displaying a
12638: classlist), so in such cases, supplying a $possdomains array is preferred, as
12639: this then allows &privileged_by_domain() to be used, which caches the identity
12640: of privileged users, eliminating the need for repeated calls to &dump().
12641: 
12642: =item *
12643: 
12644: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12645: where the outer hash keys are domains specified in the $possdomains array ref,
12646: next inner hash keys are privileged roles specified in the $roles array ref,
12647: and the innermost hash contains key = value pairs for username:domain = end:start
12648: for active or future "privileged" users with that role in that domain. To avoid
12649: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12650: innerhash are cached using priv_$role and $dom as the identifiers.
12651: 
12652: =back
12653: 
12654: =head2 User Modification
12655: 
12656: =over 4
12657: 
12658: =item *
12659: 
12660: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12661: user for the level given by URL.  Optional start and end dates (leave empty
12662: string or zero for "no date")
12663: 
12664: =item *
12665: 
12666: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12667: change a users, password, possible return values are: ok,
12668: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12669: refused
12670: 
12671: =item *
12672: 
12673: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12674: 
12675: =item *
12676: 
12677: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12678:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12679: 
12680: will update user information (firstname,middlename,lastname,generation,
12681: permanentemail), and if forceid is true, student/employee ID also.
12682: A user's institutional affiliation(s) can also be updated.
12683: User information fields will not be overwritten with empty entries 
12684: unless the field is included in the $candelete array reference.
12685: This array is included when a single user is modified via "Manage Users",
12686: or when Autoupdate.pl is run by cron in a domain.
12687: 
12688: =item *
12689: 
12690: modifystudent
12691: 
12692: modify a student's enrollment and identification information.
12693: The course id is resolved based on the current users environment.  
12694: This means the envoking user must be a course coordinator or otherwise
12695: associated with a course.
12696: 
12697: This call is essentially a wrapper for lonnet::modifyuser and
12698: lonnet::modify_student_enrollment
12699: 
12700: Inputs: 
12701: 
12702: =over 4
12703: 
12704: =item B<$udom> Student's loncapa domain
12705: 
12706: =item B<$uname> Student's loncapa login name
12707: 
12708: =item B<$uid> Student/Employee ID
12709: 
12710: =item B<$umode> Student's authentication mode
12711: 
12712: =item B<$upass> Student's password
12713: 
12714: =item B<$first> Student's first name
12715: 
12716: =item B<$middle> Student's middle name
12717: 
12718: =item B<$last> Student's last name
12719: 
12720: =item B<$gene> Student's generation
12721: 
12722: =item B<$usec> Student's section in course
12723: 
12724: =item B<$end> Unix time of the roles expiration
12725: 
12726: =item B<$start> Unix time of the roles start date
12727: 
12728: =item B<$forceid> If defined, allow $uid to be changed
12729: 
12730: =item B<$desiredhome> server to use as home server for student
12731: 
12732: =item B<$email> Student's permanent e-mail address
12733: 
12734: =item B<$type> Type of enrollment (auto or manual)
12735: 
12736: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12737: 
12738: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12739: 
12740: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12741: 
12742: =item B<$context> role change context (shown in User Management Logs display in a course)
12743: 
12744: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12745: 
12746: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12747: 
12748: =back
12749: 
12750: =item *
12751: 
12752: modify_student_enrollment
12753: 
12754: Change a students enrollment status in a class.  The environment variable
12755: 'role.request.course' must be defined for this function to proceed.
12756: 
12757: Inputs:
12758: 
12759: =over 4
12760: 
12761: =item $udom, students domain
12762: 
12763: =item $uname, students name
12764: 
12765: =item $uid, students user id
12766: 
12767: =item $first, students first name
12768: 
12769: =item $middle
12770: 
12771: =item $last
12772: 
12773: =item $gene
12774: 
12775: =item $usec
12776: 
12777: =item $end
12778: 
12779: =item $start
12780: 
12781: =item $type
12782: 
12783: =item $locktype
12784: 
12785: =item $cid
12786: 
12787: =item $selfenroll
12788: 
12789: =item $context
12790: 
12791: =item $credits, number of credits student will earn from this class
12792: 
12793: =back
12794: 
12795: 
12796: =item *
12797: 
12798: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12799: custom role; give a custom role to a user for the level given by URL.  Specify
12800: name and domain of role author, and role name
12801: 
12802: =item *
12803: 
12804: revokerole($udom,$uname,$url,$role) : revoke a role for url
12805: 
12806: =item *
12807: 
12808: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12809: 
12810: =back
12811: 
12812: =head2 Course Infomation
12813: 
12814: =over 4
12815: 
12816: =item *
12817: 
12818: coursedescription($courseid,$options) : returns a hash of information about the
12819: specified course id, including all environment settings for the
12820: course, the description of the course will be in the hash under the
12821: key 'description'
12822: 
12823: $options is an optional parameter that if supplied is a hash reference that controls
12824: what how this function works.  It has the following key/values:
12825: 
12826: =over 4
12827: 
12828: =item freshen_cache
12829: 
12830: If defined, and the environment cache for the course is valid, it is 
12831: returned in the returned hash.
12832: 
12833: =item one_time
12834: 
12835: If defined, the last cache time is set to _now_
12836: 
12837: =item user
12838: 
12839: If defined, the supplied username is used instead of the current user.
12840: 
12841: 
12842: =back
12843: 
12844: =item *
12845: 
12846: resdata($name,$domain,$type,@which) : request for current parameter
12847: setting for a specific $type, where $type is either 'course' or 'user',
12848: @what should be a list of parameters to ask about. This routine caches
12849: answers for 5 minutes.
12850: 
12851: =item *
12852: 
12853: get_courseresdata($courseid, $domain) : dump the entire course resource
12854: data base, returning a hash that is keyed by the resource name and has
12855: values that are the resource value.  I believe that the timestamps and
12856: versions are also returned.
12857: 
12858: =back
12859: 
12860: =head2 Course Modification
12861: 
12862: =over 4
12863: 
12864: =item *
12865: 
12866: writecoursepref($courseid,%prefs) : write preferences (environment
12867: database) for a course
12868: 
12869: =item *
12870: 
12871: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12872: 
12873: =item *
12874: 
12875: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12876: 
12877: =item *
12878: 
12879: is_course($courseid), is_course($cdom, $cnum)
12880: 
12881: Accepts either a combined $courseid (in the form of domain_courseid) or the
12882: two component version $cdom, $cnum. It checks if the specified course exists.
12883: 
12884: Returns:
12885:     undef if the course doesn't exist, otherwise
12886:     in scalar context the combined courseid.
12887:     in list context the two components of the course identifier, domain and 
12888:     courseid.    
12889: 
12890: =back
12891: 
12892: =head2 Resource Subroutines
12893: 
12894: =over 4
12895: 
12896: =item *
12897: 
12898: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12899: 
12900: =item *
12901: 
12902: repcopy($filename) : subscribes to the requested file, and attempts to
12903: replicate from the owning library server, Might return
12904: 'unavailable', 'not_found', 'forbidden', 'ok', or
12905: 'bad_request', also attempts to grab the metadata for the
12906: resource. Expects the local filesystem pathname
12907: (/home/httpd/html/res/....)
12908: 
12909: =back
12910: 
12911: =head2 Resource Information
12912: 
12913: =over 4
12914: 
12915: =item *
12916: 
12917: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12918: and returns the value of a variety of different possible values,
12919: $varname should be a request string, and the other parameters can be
12920: used to specify who and what one is asking about. Ordinarily, $cid 
12921: does not need to be specified, as it is retrived from 
12922: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12923: within lonuserstate::loadmap() when initializing a course, before
12924: $env{'request.course.id'} has been set, so it needs to be provided
12925: in that one case.
12926: 
12927: Possible values for $varname are environment.lastname (or other item
12928: from the envirnment hash), user.name (or someother aspect about the
12929: user), resource.0.maxtries (or some other part and parameter of a
12930: resource)
12931: 
12932: =item *
12933: 
12934: directcondval($number) : get current value of a condition; reads from a state
12935: string
12936: 
12937: =item *
12938: 
12939: condval($condidx) : value of condition index based on state
12940: 
12941: =item *
12942: 
12943: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12944: resource's metadata, $what should be either a specific key, or either
12945: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12946: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12947: 
12948: this function automatically caches all requests
12949: 
12950: =item *
12951: 
12952: metadata_query($query,$custom,$customshow) : make a metadata query against the
12953: network of library servers; returns file handle of where SQL and regex results
12954: will be stored for query
12955: 
12956: =item *
12957: 
12958: symbread($filename) : return symbolic list entry (filename argument optional);
12959: returns the data handle
12960: 
12961: =item *
12962: 
12963: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12964: and is a possible symb for the URL in $thisfn, and if is an encrypted
12965: resource that the user accessed using /enc/ returns a 1 on success, 0
12966: on failure, user must be in a course, as it assumes the existence of
12967: the course initial hash, and uses $env('request.course.id'}.  The third
12968: arg is an optional reference to a scalar.  If this arg is passed in the 
12969: call to symbverify, it will be set to 1 if the symb has been set to be 
12970: encrypted; otherwise it will be null.  
12971: 
12972: =item *
12973: 
12974: symbclean($symb) : removes versions numbers from a symb, returns the
12975: cleaned symb
12976: 
12977: =item *
12978: 
12979: is_on_map($uri) : checks if the $uri is somewhere on the current
12980: course map, user must be in a course for it to work.
12981: 
12982: =item *
12983: 
12984: numval($salt) : return random seed value (addend for rndseed)
12985: 
12986: =item *
12987: 
12988: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12989: a random seed, all arguments are optional, if they aren't sent it uses the
12990: environment to derive them. Note: if symb isn't sent and it can't get one
12991: from &symbread it will use the current time as its return value
12992: 
12993: =item *
12994: 
12995: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12996: unfakeable, receipt
12997: 
12998: =item *
12999: 
13000: receipt() : API to ireceipt working off of env values; given out to users
13001: 
13002: =item *
13003: 
13004: countacc($url) : count the number of accesses to a given URL
13005: 
13006: =item *
13007: 
13008: 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
13009: 
13010: =item *
13011: 
13012: 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)
13013: 
13014: =item *
13015: 
13016: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13017: 
13018: =item *
13019: 
13020: devalidate($symb) : devalidate temporary spreadsheet calculations,
13021: forcing spreadsheet to reevaluate the resource scores next time.
13022: 
13023: =item * 
13024: 
13025: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13026: when viewing in course context.
13027: 
13028:  input: six args -- filename (decluttered), course number, course domain,
13029:                     url, symb (if registered) and group (if this is a 
13030:                     group item -- e.g., bulletin board, group page etc.).
13031: 
13032:  output: array of five scalars --
13033:          $cfile -- url for file editing if editable on current server
13034:          $home -- homeserver of resource (i.e., for author if published,
13035:                                           or course if uploaded.).
13036:          $switchserver --  1 if server switch will be needed.
13037:          $forceedit -- 1 if icon/link should be to go to edit mode 
13038:          $forceview -- 1 if icon/link should be to go to view mode
13039: 
13040: =item *
13041: 
13042: is_course_upload($file,$cnum,$cdom)
13043: 
13044: Used in course context to determine if current file was uploaded to 
13045: the course (i.e., would be found in /userfiles/docs on the course's 
13046: homeserver.
13047: 
13048:   input: 3 args -- filename (decluttered), course number and course domain.
13049:   output: boolean -- 1 if file was uploaded.
13050: 
13051: =back
13052: 
13053: =head2 Storing/Retreiving Data
13054: 
13055: =over 4
13056: 
13057: =item *
13058: 
13059: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13060: for this url; hashref needs to be given and should be a \%hashname; the
13061: remaining args aren't required and if they aren't passed or are '' they will
13062: be derived from the env
13063: 
13064: =item *
13065: 
13066: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13067: uses critical subroutine
13068: 
13069: =item *
13070: 
13071: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13072: all args are optional
13073: 
13074: =item *
13075: 
13076: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13077: dumps the complete (or key matching regexp) namespace into a hash
13078: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13079: normally &store()ed into
13080: 
13081: $range should be either an integer '100' (give me the first 100
13082:                                            matching records)
13083:               or be  two integers sperated by a - with no spaces
13084:                  '30-50' (give me the 30th through the 50th matching
13085:                           records)
13086: 
13087: 
13088: =item *
13089: 
13090: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13091: replaces a &store() version of data with a replacement set of data
13092: for a particular resource in a namespace passed in the $storehash hash 
13093: reference
13094: 
13095: =item *
13096: 
13097: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13098: works very similar to store/cstore, but all data is stored in a
13099: temporary location and can be reset using tmpreset, $storehash should
13100: be a hash reference, returns nothing on success
13101: 
13102: =item *
13103: 
13104: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13105: similar to restore, but all data is stored in a temporary location and
13106: can be reset using tmpreset. Returns a hash of values on success,
13107: error string otherwise.
13108: 
13109: =item *
13110: 
13111: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13112: deltes all keys for $symb form the temporary storage hash.
13113: 
13114: =item *
13115: 
13116: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13117: reference filled in from namesp ($udom and $uname are optional)
13118: 
13119: =item *
13120: 
13121: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13122: namesp ($udom and $uname are optional)
13123: 
13124: =item *
13125: 
13126: dump($namespace,$udom,$uname,$regexp,$range) : 
13127: dumps the complete (or key matching regexp) namespace into a hash
13128: ($udom, $uname, $regexp, $range are optional)
13129: 
13130: $range should be either an integer '100' (give me the first 100
13131:                                            matching records)
13132:               or be  two integers sperated by a - with no spaces
13133:                  '30-50' (give me the 30th through the 50th matching
13134:                           records)
13135: =item *
13136: 
13137: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13138: $store can be a scalar, an array reference, or if the amount to be 
13139: incremented is > 1, a hash reference.
13140: 
13141: ($udom and $uname are optional)
13142: 
13143: =item *
13144: 
13145: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13146: ($udom and $uname are optional)
13147: 
13148: =item *
13149: 
13150: cput($namespace,$storehash,$udom,$uname) : critical put
13151: ($udom and $uname are optional)
13152: 
13153: =item *
13154: 
13155: newput($namespace,$storehash,$udom,$uname) :
13156: 
13157: Attempts to store the items in the $storehash, but only if they don't
13158: currently exist, if this succeeds you can be certain that you have 
13159: successfully created a new key value pair in the $namespace db.
13160: 
13161: 
13162: Args:
13163:  $namespace: name of database to store values to
13164:  $storehash: hashref to store to the db
13165:  $udom: (optional) domain of user containing the db
13166:  $uname: (optional) name of user caontaining the db
13167: 
13168: Returns:
13169:  'ok' -> succeeded in storing all keys of $storehash
13170:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13171:                         least <key> already existed in the db (other
13172:                         requested keys may also already exist)
13173:  'error: <msg>' -> unable to tie the DB or other error occurred
13174:  'con_lost' -> unable to contact request server
13175:  'refused' -> action was not allowed by remote machine
13176: 
13177: 
13178: =item *
13179: 
13180: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13181: reference filled in from namesp (encrypts the return communication)
13182: ($udom and $uname are optional)
13183: 
13184: =item *
13185: 
13186: log($udom,$name,$home,$message) : write to permanent log for user; use
13187: critical subroutine
13188: 
13189: =item *
13190: 
13191: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13192: array reference filled in from namespace found in domain level on either
13193: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13194: 
13195: =item *
13196: 
13197: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13198: domain level either on specified domain server ($uhome) or primary domain 
13199: server ($udom and $uhome are optional)
13200: 
13201: =item * 
13202: 
13203: get_domain_defaults($target_domain) : returns hash with defaults for
13204: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13205: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13206: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13207: Values are retrieved from cache (if current), or from domain's configuration.db
13208: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13209: or lonTabs/domain.tab. 
13210: 
13211: %domdefaults = &get_auth_defaults($target_domain);
13212: 
13213: =back
13214: 
13215: =head2 Network Status Functions
13216: 
13217: =over 4
13218: 
13219: =item *
13220: 
13221: dirlist() : return directory list based on URI (first arg).
13222: 
13223: Inputs: 1 required, 5 optional.
13224: 
13225: =over
13226: 
13227: =item 
13228: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13229: 
13230: =item
13231: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13232: 
13233: =item
13234: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13235: 
13236: =item
13237: $getpropath - boolean: 1 if prepend path using &propath(). 
13238: 
13239: =item
13240: $getuserdir - boolean: 1 if prepend path for "userfiles".
13241: 
13242: =item 
13243: $alternateRoot - path to prepend in place of path from $uri.
13244: 
13245: =back
13246: 
13247: Returns: Array of up to two items.
13248: 
13249: =over
13250: 
13251: a reference to an array of files/subdirectories
13252: 
13253: =over
13254: 
13255: Each element in the array of files/subdirectories is a & separated list of
13256: item name and the result of running stat on the item.  If dirlist was requested
13257: for a file instead of a directory, the item name will be ''. For a directory 
13258: listing, if the item is a metadata file, the element will end &N&M 
13259: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13260: default copyright set (1).  
13261: 
13262: =back
13263: 
13264: a scalar containing error condition (if encountered).
13265: 
13266: =over
13267: 
13268: =item 
13269: no_host (no homeserver identified for $username:$domain).
13270: 
13271: =item 
13272: no_such_host (server contacted for listing not identified as valid host).
13273: 
13274: =item 
13275: con_lost (connection to remote server failed).
13276: 
13277: =item 
13278: refused (invalid $username:$domain received on lond side).
13279: 
13280: =item 
13281: no_such_dir (directory at specified path on lond side does not exist). 
13282: 
13283: =item 
13284: empty (directory at specified path on lond side is empty).
13285: 
13286: =over
13287: 
13288: This is currently not encountered because the &ls3, &ls2, 
13289: &ls (_handler) routines on the lond side do not filter out
13290: . and .. from a directory listing. 
13291: 
13292: =back
13293: 
13294: =back
13295: 
13296: =back
13297: 
13298: =item *
13299: 
13300: spareserver() : find server with least workload from spare.tab
13301: 
13302: 
13303: =item *
13304: 
13305: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13306: if there is no corresponding loncapa host.
13307: 
13308: =back
13309: 
13310: 
13311: =head2 Apache Request
13312: 
13313: =over 4
13314: 
13315: =item *
13316: 
13317: ssi($url,%hash) : server side include, does a complete request cycle on url to
13318: localhost, posts hash
13319: 
13320: =back
13321: 
13322: =head2 Data to String to Data
13323: 
13324: =over 4
13325: 
13326: =item *
13327: 
13328: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13329: and '&' separators, supports elements that are arrayrefs and hashrefs
13330: 
13331: =item *
13332: 
13333: hashref2str($hashref) : convert a hashref into a string complete with
13334: escaping and '=' and '&' separators, supports elements that are
13335: arrayrefs and hashrefs
13336: 
13337: =item *
13338: 
13339: arrayref2str($arrayref) : convert an arrayref into a string complete
13340: with escaping and '&' separators, supports elements that are arrayrefs
13341: and hashrefs
13342: 
13343: =item *
13344: 
13345: str2hash($string) : convert string to hash using unescaping and
13346: splitting on '=' and '&', supports elements that are arrayrefs and
13347: hashrefs
13348: 
13349: =item *
13350: 
13351: str2array($string) : convert string to hash using unescaping and
13352: splitting on '&', supports elements that are arrayrefs and hashrefs
13353: 
13354: =back
13355: 
13356: =head2 Logging Routines
13357: 
13358: 
13359: These routines allow one to make log messages in the lonnet.log and
13360: lonnet.perm logfiles.
13361: 
13362: =over 4
13363: 
13364: =item *
13365: 
13366: logtouch() : make sure the logfile, lonnet.log, exists
13367: 
13368: =item *
13369: 
13370: logthis() : append message to the normal lonnet.log file, it gets
13371: preiodically rolled over and deleted.
13372: 
13373: =item *
13374: 
13375: logperm() : append a permanent message to lonnet.perm.log, this log
13376: file never gets deleted by any automated portion of the system, only
13377: messages of critical importance should go in here.
13378: 
13379: 
13380: =back
13381: 
13382: =head2 General File Helper Routines
13383: 
13384: =over 4
13385: 
13386: =item *
13387: 
13388: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13389: (a) files in /uploaded
13390:   (i) If a local copy of the file exists - 
13391:       compares modification date of local copy with last-modified date for 
13392:       definitive version stored on home server for course. If local copy is 
13393:       stale, requests a new version from the home server and stores it. 
13394:       If the original has been removed from the home server, then local copy 
13395:       is unlinked.
13396:   (ii) If local copy does not exist -
13397:       requests the file from the home server and stores it. 
13398:   
13399:   If $caller is 'uploadrep':  
13400:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13401:     for request for files originally uploaded via DOCS. 
13402:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13403:   
13404:   Otherwise:
13405:      This indicates a call from the content generation phase of the request.
13406:      -  returns the entire contents of the file or -1.
13407:      
13408: (b) files in /res
13409:    - returns the entire contents of a file or -1; 
13410:    it properly subscribes to and replicates the file if neccessary.
13411: 
13412: 
13413: =item *
13414: 
13415: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13416:                   reference
13417: 
13418: returns either a stat() list of data about the file or an empty list
13419: if the file doesn't exist or couldn't find out about it (connection
13420: problems or user unknown)
13421: 
13422: =item *
13423: 
13424: filelocation($dir,$file) : returns file system location of a file
13425: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13426: directory that relative $file lookups are to looked in ($dir of /a/dir
13427: and a file of ../bob will become /a/bob)
13428: 
13429: =item *
13430: 
13431: hreflocation($dir,$file) : returns file system location or a URL; same as
13432: filelocation except for hrefs
13433: 
13434: =item *
13435: 
13436: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13437: 
13438: =back
13439: 
13440: =head2 Usererfile file routines (/uploaded*)
13441: 
13442: =over 4
13443: 
13444: =item *
13445: 
13446: userfileupload(): main rotine for putting a file in a user or course's
13447:                   filespace, arguments are,
13448: 
13449:  formname - required - this is the name of the element in $env where the
13450:            filename, and the contents of the file to create/modifed exist
13451:            the filename is in $env{'form.'.$formname.'.filename'} and the
13452:            contents of the file is located in $env{'form.'.$formname}
13453:  context - if coursedoc, store the file in the course of the active role
13454:              of the current user; 
13455:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13456:            if 'canceloverwrite': delete file in tmp/overwrites directory
13457:  subdir - required - subdirectory to put the file in under ../userfiles/
13458:          if undefined, it will be placed in "unknown"
13459: 
13460:  (This routine calls clean_filename() to remove any dangerous
13461:  characters from the filename, and then calls finuserfileupload() to
13462:  complete the transaction)
13463: 
13464:  returns either the url of the uploaded file (/uploaded/....) if successful
13465:  and /adm/notfound.html if unsuccessful
13466: 
13467: =item *
13468: 
13469: clean_filename(): routine for cleaing a filename up for storage in
13470:                  userfile space, argument is:
13471: 
13472:  filename - proposed filename
13473: 
13474: returns: the new clean filename
13475: 
13476: =item *
13477: 
13478: finishuserfileupload(): routine that creates and sends the file to
13479: userspace, probably shouldn't be called directly
13480: 
13481:   docuname: username or courseid of destination for the file
13482:   docudom: domain of user/course of destination for the file
13483:   formname: same as for userfileupload()
13484:   fname: filename (including subdirectories) for the file
13485:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13486:   allfiles: reference to hash used to store objects found by parser
13487:   codebase: reference to hash used for codebases of java objects found by parser
13488:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13489:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13490:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13491:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13492:   context: if 'overwrite', will move the uploaded file from its temporary location to
13493:             userfiles to facilitate overwriting a previously uploaded file with same name.
13494:   mimetype: reference to scalar to accommodate mime type determined
13495:             from File::MMagic if $parser = parse.
13496: 
13497:  returns either the url of the uploaded file (/uploaded/....) if successful
13498:  and /adm/notfound.html if unsuccessful (or an error message if context 
13499:  was 'overwrite').
13500:  
13501: 
13502: =item *
13503: 
13504: renameuserfile(): renames an existing userfile to a new name
13505: 
13506:   Args:
13507:    docuname: username or courseid of destination for the file
13508:    docudom: domain of user/course of destination for the file
13509:    old: current file name (including any subdirs under userfiles)
13510:    new: desired file name (including any subdirs under userfiles)
13511: 
13512: =item *
13513: 
13514: mkdiruserfile(): creates a directory is a userfiles dir
13515: 
13516:   Args:
13517:    docuname: username or courseid of destination for the file
13518:    docudom: domain of user/course of destination for the file
13519:    dir: dir to create (including any subdirs under userfiles)
13520: 
13521: =item *
13522: 
13523: removeuserfile(): removes a file that exists in userfiles
13524: 
13525:   Args:
13526:    docuname: username or courseid of destination for the file
13527:    docudom: domain of user/course of destination for the file
13528:    fname: filname to delete (including any subdirs under userfiles)
13529: 
13530: =item *
13531: 
13532: removeuploadedurl(): convience function for removeuserfile()
13533: 
13534:   Args:
13535:    url:  a full /uploaded/... url to delete
13536: 
13537: =item * 
13538: 
13539: get_portfile_permissions():
13540:   Args:
13541:     domain: domain of user or course contain the portfolio files
13542:     user: name of user or num of course contain the portfolio files
13543:   Returns:
13544:     hashref of a dump of the proper file_permissions.db
13545:    
13546: 
13547: =item * 
13548: 
13549: get_access_controls():
13550: 
13551: Args:
13552:   current_permissions: the hash ref returned from get_portfile_permissions()
13553:   group: (optional) the group you want the files associated with
13554:   file: (optional) the file you want access info on
13555: 
13556: Returns:
13557:     a hash (keys are file names) of hashes containing
13558:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13559:         values are XML containing access control settings (see below) 
13560: 
13561: Internal notes:
13562: 
13563:  access controls are stored in file_permissions.db as key=value pairs.
13564:     key -> path to file/file_name\0uniqueID:scope_end_start
13565:         where scope -> public,guest,course,group,domains or users.
13566:               end -> UNIX time for end of access (0 -> no end date)
13567:               start -> UNIX time for start of access
13568: 
13569:     value -> XML description of access control
13570:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13571:             <start></start>
13572:             <end></end>
13573: 
13574:             <password></password>  for scope type = guest
13575: 
13576:             <domain></domain>     for scope type = course or group
13577:             <number></number>
13578:             <roles id="">
13579:              <role></role>
13580:              <access></access>
13581:              <section></section>
13582:              <group></group>
13583:             </roles>
13584: 
13585:             <dom></dom>         for scope type = domains
13586: 
13587:             <users>             for scope type = users
13588:              <user>
13589:               <uname></uname>
13590:               <udom></udom>
13591:              </user>
13592:             </users>
13593:            </scope> 
13594:               
13595:  Access data is also aggregated for each file in an additional key=value pair:
13596:  key -> path to file/file_name\0accesscontrol 
13597:  value -> reference to hash
13598:           hash contains key = value pairs
13599:           where key = uniqueID:scope_end_start
13600:                 value = UNIX time record was last updated
13601: 
13602:           Used to improve speed of look-ups of access controls for each file.  
13603:  
13604:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13605: 
13606: =item *
13607: 
13608: modify_access_controls():
13609: 
13610: Modifies access controls for a portfolio file
13611: Args
13612: 1. file name
13613: 2. reference to hash of required changes,
13614: 3. domain
13615: 4. username
13616:   where domain,username are the domain of the portfolio owner 
13617:   (either a user or a course) 
13618: 
13619: Returns:
13620: 1. result of additions or updates ('ok' or 'error', with error message). 
13621: 2. result of deletions ('ok' or 'error', with error message).
13622: 3. reference to hash of any new or updated access controls.
13623: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13624:    key = integer (inbound ID)
13625:    value = uniqueID
13626: 
13627: =item *
13628: 
13629: get_timebased_id():
13630: 
13631: Attempts to get a unique timestamp-based suffix for use with items added to a 
13632: course via the Course Editor (e.g., folders, composite pages, 
13633: group bulletin boards).
13634: 
13635: Args: (first three required; six others optional)
13636: 
13637: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13638:    docssequence, or name of group
13639: 
13640: 2. keyid (alphanumeric): name of temporary locking key in hash,
13641:    e.g., num, boardids
13642: 
13643: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13644:    file will be named nohist_namespace.db
13645: 
13646: 4. cdom: domain of course; default is current course domain from %env
13647: 
13648: 5. cnum: course number; default is current course number from %env
13649: 
13650: 6. idtype: set to concat if an additional digit is to be appended to the 
13651:    unix timestamp to form the suffix, if the plain timestamp is already
13652:    in use.  Default is to not do this, but simply increment the unix 
13653:    timestamp by 1 until a unique key is obtained.
13654: 
13655: 7. who: holder of locking key; defaults to user:domain for user.
13656: 
13657: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13658:    retrying); default is 3.
13659: 
13660: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13661: 
13662: Returns:
13663: 
13664: 1. suffix obtained (numeric)
13665: 
13666: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13667: 
13668: 3. error: contains (localized) error message if an error occurred.
13669: 
13670: 
13671: =back
13672: 
13673: =head2 HTTP Helper Routines
13674: 
13675: =over 4
13676: 
13677: =item *
13678: 
13679: escape() : unpack non-word characters into CGI-compatible hex codes
13680: 
13681: =item *
13682: 
13683: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13684: 
13685: =back
13686: 
13687: =head1 PRIVATE SUBROUTINES
13688: 
13689: =head2 Underlying communication routines (Shouldn't call)
13690: 
13691: =over 4
13692: 
13693: =item *
13694: 
13695: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13696: 
13697: =item *
13698: 
13699: reply() : uses subreply to send a message to remote machine, logs all failures
13700: 
13701: =item *
13702: 
13703: critical() : passes a critical message to another server; if cannot
13704: get through then place message in connection buffer directory and
13705: returns con_delayed, if incapable of saving message, returns
13706: con_failed
13707: 
13708: =item *
13709: 
13710: reconlonc() : tries to reconnect lonc client processes.
13711: 
13712: =back
13713: 
13714: =head2 Resource Access Logging
13715: 
13716: =over 4
13717: 
13718: =item *
13719: 
13720: flushcourselogs() : flush (save) buffer logs and access logs
13721: 
13722: =item *
13723: 
13724: courselog($what) : save message for course in hash
13725: 
13726: =item *
13727: 
13728: courseacclog($what) : save message for course using &courselog().  Perform
13729: special processing for specific resource types (problems, exams, quizzes, etc).
13730: 
13731: =item *
13732: 
13733: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13734: as a PerlChildExitHandler
13735: 
13736: =back
13737: 
13738: =head2 Other
13739: 
13740: =over 4
13741: 
13742: =item *
13743: 
13744: symblist($mapname,%newhash) : update symbolic storage links
13745: 
13746: =back
13747: 
13748: =cut
13749: 

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