File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1243: download - view: text, annotated - select for diffs
Mon Oct 14 17:14:48 2013 UTC (10 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- iframe src can be a dependency for an uploaded HTML page, if
  (a) path is a relative path
  (b) path is an absolute path in the same docs/<folder>/<id> subdirectory
      in the uploaded area of the current course.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1243 2013/10/14 17:14:48 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,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640:     if (($r->user() eq '') && ($apache >= 2.4)) {
  641:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  642:             $r->user($disk_env{'user.name'});
  643:         } else {
  644:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  645:         }
  646:     }
  647:     return $handle;
  648: }
  649: 
  650: sub timed_flock {
  651:     my ($file,$lock_type) = @_;
  652:     my $failed=0;
  653:     eval {
  654: 	local $SIG{__DIE__}='DEFAULT';
  655: 	local $SIG{ALRM}=sub {
  656: 	    $failed=1;
  657: 	    die("failed lock");
  658: 	};
  659: 	alarm(13);
  660: 	flock($file,$lock_type);
  661: 	alarm(0);
  662:     };
  663:     if ($failed) {
  664: 	return undef;
  665:     } else {
  666: 	return 1;
  667:     }
  668: }
  669: 
  670: # ---------------------------------------------------------- Append Environment
  671: 
  672: sub appenv {
  673:     my ($newenv,$roles) = @_;
  674:     if (ref($newenv) eq 'HASH') {
  675:         foreach my $key (keys(%{$newenv})) {
  676:             my $refused = 0;
  677: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  678:                 $refused = 1;
  679:                 if (ref($roles) eq 'ARRAY') {
  680:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  681:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  682:                         $refused = 0;
  683:                     }
  684:                 }
  685:             }
  686:             if ($refused) {
  687:                 &logthis("<font color=\"blue\">WARNING: ".
  688:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  689:                          .'</font>');
  690: 	        delete($newenv->{$key});
  691:             } else {
  692:                 $env{$key}=$newenv->{$key};
  693:             }
  694:         }
  695:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  696:         if ($opened
  697: 	    && &timed_flock($env_file,LOCK_EX)
  698: 	    &&
  699: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  700: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  701: 	    while (my ($key,$value) = each(%{$newenv})) {
  702: 	        $disk_env{$key} = $value;
  703: 	    }
  704: 	    untie(%disk_env);
  705:         }
  706:     }
  707:     return 'ok';
  708: }
  709: # ----------------------------------------------------- Delete from Environment
  710: 
  711: sub delenv {
  712:     my ($delthis,$regexp,$roles) = @_;
  713:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  714:         my $refused = 1;
  715:         if (ref($roles) eq 'ARRAY') {
  716:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  717:             if (grep(/^\Q$role\E$/,@{$roles})) {
  718:                 $refused = 0;
  719:             }
  720:         }
  721:         if ($refused) {
  722:             &logthis("<font color=\"blue\">WARNING: ".
  723:                      "Attempt to delete from environment ".$delthis);
  724:             return 'error';
  725:         }
  726:     }
  727:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  728:     if ($opened
  729: 	&& &timed_flock($env_file,LOCK_EX)
  730: 	&&
  731: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  732: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  733: 	foreach my $key (keys(%disk_env)) {
  734: 	    if ($regexp) {
  735:                 if ($key=~/^$delthis/) {
  736:                     delete($env{$key});
  737:                     delete($disk_env{$key});
  738:                 } 
  739:             } else {
  740:                 if ($key=~/^\Q$delthis\E/) {
  741: 		    delete($env{$key});
  742: 		    delete($disk_env{$key});
  743: 	        }
  744:             }
  745: 	}
  746: 	untie(%disk_env);
  747:     }
  748:     return 'ok';
  749: }
  750: 
  751: sub get_env_multiple {
  752:     my ($name) = @_;
  753:     my @values;
  754:     if (defined($env{$name})) {
  755:         # exists is it an array
  756:         if (ref($env{$name})) {
  757:             @values=@{ $env{$name} };
  758:         } else {
  759:             $values[0]=$env{$name};
  760:         }
  761:     }
  762:     return(@values);
  763: }
  764: 
  765: # ------------------------------------------------------------------- Locking
  766: 
  767: sub set_lock {
  768:     my ($text)=@_;
  769:     $locknum++;
  770:     my $id=$$.'-'.$locknum;
  771:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  772:              'session.lock.'.$id => $text});
  773:     return $id;
  774: }
  775: 
  776: sub get_locks {
  777:     my $num=0;
  778:     my %texts=();
  779:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  780:        if ($lock=~/\w/) {
  781:           $num++;
  782:           $texts{$lock}=$env{'session.lock.'.$lock};
  783:        }
  784:    }
  785:    return ($num,%texts);
  786: }
  787: 
  788: sub remove_lock {
  789:     my ($id)=@_;
  790:     my $newlocks='';
  791:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  792:        if (($lock=~/\w/) && ($lock ne $id)) {
  793:           $newlocks.=','.$lock;
  794:        }
  795:     }
  796:     &appenv({'session.locks' => $newlocks});
  797:     &delenv('session.lock.'.$id);
  798: }
  799: 
  800: sub remove_all_locks {
  801:     my $activelocks=$env{'session.locks'};
  802:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  803:        if ($lock=~/\w/) {
  804:           &remove_lock($lock);
  805:        }
  806:     }
  807: }
  808: 
  809: 
  810: # ------------------------------------------ Find out current server userload
  811: sub userload {
  812:     my $numusers=0;
  813:     {
  814: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  815: 	my $filename;
  816: 	my $curtime=time;
  817: 	while ($filename=readdir(LONIDS)) {
  818: 	    next if ($filename eq '.' || $filename eq '..');
  819: 	    next if ($filename =~ /publicuser_\d+\.id/);
  820: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  821: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  822: 	}
  823: 	closedir(LONIDS);
  824:     }
  825:     my $userloadpercent=0;
  826:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  827:     if ($maxuserload) {
  828: 	$userloadpercent=100*$numusers/$maxuserload;
  829:     }
  830:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  831:     return $userloadpercent;
  832: }
  833: 
  834: # ------------------------------ Find server with least workload from spare.tab
  835: 
  836: sub spareserver {
  837:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  838:     my $spare_server;
  839:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  840:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  841:                                                      :  $userloadpercent;
  842:     my ($uint_dom,$remotesessions);
  843:     if (($udom ne '') && (&domain($udom) ne '')) {
  844:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  845:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  846:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  847:         $remotesessions = $udomdefaults{'remotesessions'};
  848:     }
  849:     my $spareshash = &this_host_spares($udom);
  850:     if (ref($spareshash) eq 'HASH') {
  851:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  852:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  853:                 if ($uint_dom) {
  854:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  855:                                                  $try_server));
  856:                 }
  857: 	        ($spare_server, $lowest_load) =
  858: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  859:             }
  860:         }
  861: 
  862:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  863: 
  864:         if (!$found_server) {
  865:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  866: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  867:                     if ($uint_dom) {
  868:                         next unless (&spare_can_host($udom,$uint_dom,
  869:                                                      $remotesessions,$try_server));
  870:                     }
  871: 	            ($spare_server, $lowest_load) =
  872: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  873:                 }
  874: 	    }
  875:         }
  876:     }
  877: 
  878:     if (!$want_server_name) {
  879:         my $protocol = 'http';
  880:         if ($protocol{$spare_server} eq 'https') {
  881:             $protocol = $protocol{$spare_server};
  882:         }
  883:         if (defined($spare_server)) {
  884:             my $hostname = &hostname($spare_server);
  885:             if (defined($hostname)) {
  886: 	        $spare_server = $protocol.'://'.$hostname;
  887:             }
  888:         }
  889:     }
  890:     return $spare_server;
  891: }
  892: 
  893: sub compare_server_load {
  894:     my ($try_server, $spare_server, $lowest_load) = @_;
  895: 
  896:     my $loadans     = &reply('load',    $try_server);
  897:     my $userloadans = &reply('userload',$try_server);
  898: 
  899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  901:     }
  902: 
  903:     my $load;
  904:     if ($loadans =~ /\d/) {
  905: 	if ($userloadans =~ /\d/) {
  906: 	    #both are numbers, pick the bigger one
  907: 	    $load = ($loadans > $userloadans) ? $loadans 
  908: 		                              : $userloadans;
  909: 	} else {
  910: 	    $load = $loadans;
  911: 	}
  912:     } else {
  913: 	$load = $userloadans;
  914:     }
  915: 
  916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  917: 	$spare_server = $try_server;
  918: 	$lowest_load  = $load;
  919:     }
  920:     return ($spare_server,$lowest_load);
  921: }
  922: 
  923: # --------------------------- ask offload servers if user already has a session
  924: sub find_existing_session {
  925:     my ($udom,$uname) = @_;
  926:     my $spareshash = &this_host_spares($udom);
  927:     if (ref($spareshash) eq 'HASH') {
  928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  931:             }
  932:         }
  933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:     }
  939:     return;
  940: }
  941: 
  942: # -------------------------------- ask if server already has a session for user
  943: sub has_user_session {
  944:     my ($lonid,$udom,$uname) = @_;
  945:     my $result = &reply(join(':','userhassession',
  946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  947:     return 1 if ($result eq 'ok');
  948: 
  949:     return 0;
  950: }
  951: 
  952: # --------- determine least loaded server in a user's domain which allows login
  953: 
  954: sub choose_server {
  955:     my ($udom,$checkloginvia) = @_;
  956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  957:     my %servers = &get_servers($udom);
  958:     my $lowest_load = 30000;
  959:     my ($login_host,$hostname,$portal_path,$isredirect);
  960:     foreach my $lonhost (keys(%servers)) {
  961:         my $loginvia;
  962:         if ($checkloginvia) {
  963:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  964:             if ($loginvia) {
  965:                 my ($server,$path) = split(/:/,$loginvia);
  966:                 ($login_host, $lowest_load) =
  967:                     &compare_server_load($server, $login_host, $lowest_load);
  968:                 if ($login_host eq $server) {
  969:                     $portal_path = $path;
  970:                     $isredirect = 1;
  971:                 }
  972:             } else {
  973:                 ($login_host, $lowest_load) =
  974:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  975:                 if ($login_host eq $lonhost) {
  976:                     $portal_path = '';
  977:                     $isredirect = ''; 
  978:                 }
  979:             }
  980:         } else {
  981:             ($login_host, $lowest_load) =
  982:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  983:         }
  984:     }
  985:     if ($login_host ne '') {
  986:         $hostname = &hostname($login_host);
  987:     }
  988:     return ($login_host,$hostname,$portal_path,$isredirect);
  989: }
  990: 
  991: # --------------------------------------------- Try to change a user's password
  992: 
  993: sub changepass {
  994:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  995:     $currentpass = &escape($currentpass);
  996:     $newpass     = &escape($newpass);
  997:     my $lonhost = $perlvar{'lonHostID'};
  998:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  999: 		       $server);
 1000:     if (! $answer) {
 1001: 	&logthis("No reply on password change request to $server ".
 1002: 		 "by $uname in domain $udom.");
 1003:     } elsif ($answer =~ "^ok") {
 1004:         &logthis("$uname in $udom successfully changed their password ".
 1005: 		 "on $server.");
 1006:     } elsif ($answer =~ "^pwchange_failure") {
 1007: 	&logthis("$uname in $udom was unable to change their password ".
 1008: 		 "on $server.  The action was blocked by either lcpasswd ".
 1009: 		 "or pwchange");
 1010:     } elsif ($answer =~ "^non_authorized") {
 1011:         &logthis("$uname in $udom did not get their password correct when ".
 1012: 		 "attempting to change it on $server.");
 1013:     } elsif ($answer =~ "^auth_mode_error") {
 1014:         &logthis("$uname in $udom attempted to change their password despite ".
 1015: 		 "not being locally or internally authenticated on $server.");
 1016:     } elsif ($answer =~ "^unknown_user") {
 1017:         &logthis("$uname in $udom attempted to change their password ".
 1018: 		 "on $server but were unable to because $server is not ".
 1019: 		 "their home server.");
 1020:     } elsif ($answer =~ "^refused") {
 1021: 	&logthis("$server refused to change $uname in $udom password because ".
 1022: 		 "it was sent an unencrypted request to change the password.");
 1023:     } elsif ($answer =~ "invalid_client") {
 1024:         &logthis("$server refused to change $uname in $udom password because ".
 1025:                  "it was a reset by e-mail originating from an invalid server.");
 1026:     }
 1027:     return $answer;
 1028: }
 1029: 
 1030: # ----------------------- Try to determine user's current authentication scheme
 1031: 
 1032: sub queryauthenticate {
 1033:     my ($uname,$udom)=@_;
 1034:     my $uhome=&homeserver($uname,$udom);
 1035:     if (!$uhome) {
 1036: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1037: 	return 'no_host';
 1038:     }
 1039:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1040:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1041: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1042:     }
 1043:     return $answer;
 1044: }
 1045: 
 1046: # --------- Try to authenticate user from domain's lib servers (first this one)
 1047: 
 1048: sub authenticate {
 1049:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1050:     $upass=&escape($upass);
 1051:     $uname= &LONCAPA::clean_username($uname);
 1052:     my $uhome=&homeserver($uname,$udom,1);
 1053:     my $newhome;
 1054:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1055: # Maybe the machine was offline and only re-appeared again recently?
 1056:         &reconlonc();
 1057: # One more
 1058: 	$uhome=&homeserver($uname,$udom,1);
 1059:         if (($uhome eq 'no_host') && $checkdefauth) {
 1060:             if (defined(&domain($udom,'primary'))) {
 1061:                 $newhome=&domain($udom,'primary');
 1062:             }
 1063:             if ($newhome ne '') {
 1064:                 $uhome = $newhome;
 1065:             }
 1066:         }
 1067: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1068: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1069: 	    return 'no_host';
 1070:         }
 1071:     }
 1072:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1073:     if ($answer eq 'authorized') {
 1074:         if ($newhome) {
 1075:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1076:             return 'no_account_on_host'; 
 1077:         } else {
 1078:             &logthis("User $uname at $udom authorized by $uhome");
 1079:             return $uhome;
 1080:         }
 1081:     }
 1082:     if ($answer eq 'non_authorized') {
 1083: 	&logthis("User $uname at $udom rejected by $uhome");
 1084: 	return 'no_host'; 
 1085:     }
 1086:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1087:     return 'no_host';
 1088: }
 1089: 
 1090: sub can_host_session {
 1091:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1092:     my $canhost = 1;
 1093:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1094:     if (ref($remotesessions) eq 'HASH') {
 1095:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1096:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1097:                 $canhost = 0;
 1098:             } else {
 1099:                 $canhost = 1;
 1100:             }
 1101:         }
 1102:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1103:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1104:                 $canhost = 1;
 1105:             } else {
 1106:                 $canhost = 0;
 1107:             }
 1108:         }
 1109:         if ($canhost) {
 1110:             if ($remotesessions->{'version'} ne '') {
 1111:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1112:                 if ($reqmajor ne '' && $reqminor ne '') {
 1113:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1114:                         my $major = $1;
 1115:                         my $minor = $2;
 1116:                         if (($major < $reqmajor ) ||
 1117:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1118:                             $canhost = 0;
 1119:                         }
 1120:                     } else {
 1121:                         $canhost = 0;
 1122:                     }
 1123:                 }
 1124:             }
 1125:         }
 1126:     }
 1127:     if ($canhost) {
 1128:         if (ref($hostedsessions) eq 'HASH') {
 1129:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1130:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1131:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1132:                 if (($uint_dom ne '') && 
 1133:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1134:                     $canhost = 0;
 1135:                 } else {
 1136:                     $canhost = 1;
 1137:                 }
 1138:             }
 1139:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1140:                 if (($uint_dom ne '') && 
 1141:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1142:                     $canhost = 1;
 1143:                 } else {
 1144:                     $canhost = 0;
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     return $canhost;
 1150: }
 1151: 
 1152: sub spare_can_host {
 1153:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1154:     my $canhost=1;
 1155:     my @intdoms;
 1156:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1157:     if (ref($internet_names) eq 'ARRAY') {
 1158:         @intdoms = @{$internet_names};
 1159:     }
 1160:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1161:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1162:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1163:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1164:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1165:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1166:                                      $remotesessions,
 1167:                                      $defdomdefaults{'hostedsessions'});
 1168:     }
 1169:     return $canhost;
 1170: }
 1171: 
 1172: sub this_host_spares {
 1173:     my ($dom) = @_;
 1174:     my ($dom_in_use,$lonhost_in_use,$result);
 1175:     my @hosts = &current_machine_ids();
 1176:     foreach my $lonhost (@hosts) {
 1177:         if (&host_domain($lonhost) eq $dom) {
 1178:             $dom_in_use = $dom;
 1179:             $lonhost_in_use = $lonhost;
 1180:             last;
 1181:         }
 1182:     }
 1183:     if ($dom_in_use ne '') {
 1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1185:     }
 1186:     if (ref($result) ne 'HASH') {
 1187:         $lonhost_in_use = $perlvar{'lonHostID'};
 1188:         $dom_in_use = &host_domain($lonhost_in_use);
 1189:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1190:         if (ref($result) ne 'HASH') {
 1191:             $result = \%spareid;
 1192:         }
 1193:     }
 1194:     return $result;
 1195: }
 1196: 
 1197: sub spares_for_offload  {
 1198:     my ($dom_in_use,$lonhost_in_use) = @_;
 1199:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1200:     if (defined($cached)) {
 1201:         return $result;
 1202:     } else {
 1203:         my $cachetime = 60*60*24;
 1204:         my %domconfig =
 1205:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1206:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1207:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1208:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1209:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1210:                 }
 1211:             }
 1212:         }
 1213:     }
 1214:     return;
 1215: }
 1216: 
 1217: sub get_lonbalancer_config {
 1218:     my ($servers) = @_;
 1219:     my ($currbalancer,$currtargets);
 1220:     if (ref($servers) eq 'HASH') {
 1221:         foreach my $server (keys(%{$servers})) {
 1222:             my %what = (
 1223:                          spareid => 1,
 1224:                          perlvar => 1,
 1225:                        );
 1226:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1227:             if ($result eq 'ok') {
 1228:                 if (ref($returnhash) eq 'HASH') {
 1229:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1230:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1231:                             $currbalancer = $server;
 1232:                             $currtargets = {};
 1233:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1234:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1236:                                 }
 1237:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1238:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1239:                                 }
 1240:                             }
 1241:                             last;
 1242:                         }
 1243:                     }
 1244:                 }
 1245:             }
 1246:         }
 1247:     }
 1248:     return ($currbalancer,$currtargets);
 1249: }
 1250: 
 1251: sub check_loadbalancing {
 1252:     my ($uname,$udom) = @_;
 1253:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1254:         $rule_in_effect,$offloadto,$otherserver);
 1255:     my $lonhost = $perlvar{'lonHostID'};
 1256:     my @hosts = &current_machine_ids();
 1257:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1258:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1259:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1260:     my $serverhomedom = &host_domain($lonhost);
 1261: 
 1262:     my $cachetime = 60*60*24;
 1263: 
 1264:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1265:         $dom_in_use = $udom;
 1266:         $homeintdom = 1;
 1267:     } else {
 1268:         $dom_in_use = $serverhomedom;
 1269:     }
 1270:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1271:     unless (defined($cached)) {
 1272:         my %domconfig =
 1273:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1274:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1275:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1276:         }
 1277:     }
 1278:     if (ref($result) eq 'HASH') {
 1279:         ($is_balancer,$currtargets,$currrules) = 
 1280:             &check_balancer_result($result,@hosts);
 1281:         if ($is_balancer) {
 1282:             if (ref($currrules) eq 'HASH') {
 1283:                 if ($homeintdom) {
 1284:                     if ($uname ne '') {
 1285:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1286:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1287:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1288:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1289:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1290:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1291:                             }
 1292:                         }
 1293:                         if ($rule_in_effect eq '') {
 1294:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1295:                             if ($userenv{'inststatus'} ne '') {
 1296:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1297:                                 my ($othertitle,$usertypes,$types) =
 1298:                                     &Apache::loncommon::sorted_inst_types($udom);
 1299:                                 if (ref($types) eq 'ARRAY') {
 1300:                                     foreach my $type (@{$types}) {
 1301:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1302:                                             if (exists($currrules->{$type})) {
 1303:                                                 $rule_in_effect = $currrules->{$type};
 1304:                                             }
 1305:                                         }
 1306:                                     }
 1307:                                 }
 1308:                             } else {
 1309:                                 if (exists($currrules->{'default'})) {
 1310:                                     $rule_in_effect = $currrules->{'default'};
 1311:                                 }
 1312:                             }
 1313:                         }
 1314:                     } else {
 1315:                         if (exists($currrules->{'default'})) {
 1316:                             $rule_in_effect = $currrules->{'default'};
 1317:                         }
 1318:                     }
 1319:                 } else {
 1320:                     if ($currrules->{'_LC_external'} ne '') {
 1321:                         $rule_in_effect = $currrules->{'_LC_external'};
 1322:                     }
 1323:                 }
 1324:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1325:                                                        $uname,$udom);
 1326:             }
 1327:         }
 1328:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1329:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1330:         unless (defined($cached)) {
 1331:             my %domconfig =
 1332:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1333:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1334:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1335:             }
 1336:         }
 1337:         if (ref($result) eq 'HASH') {
 1338:             ($is_balancer,$currtargets,$currrules) = 
 1339:                 &check_balancer_result($result,@hosts);
 1340:             if ($is_balancer) {
 1341:                 if (ref($currrules) eq 'HASH') {
 1342:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1343:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1344:                     }
 1345:                 }
 1346:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1347:                                                        $uname,$udom);
 1348:             }
 1349:         } else {
 1350:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1351:                 $is_balancer = 1;
 1352:                 $offloadto = &this_host_spares($dom_in_use);
 1353:             }
 1354:         }
 1355:     } else {
 1356:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1357:             $is_balancer = 1;
 1358:             $offloadto = &this_host_spares($dom_in_use);
 1359:         }
 1360:     }
 1361:     if ($is_balancer) {
 1362:         my $lowest_load = 30000;
 1363:         if (ref($offloadto) eq 'HASH') {
 1364:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1365:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1366:                     ($otherserver,$lowest_load) =
 1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1368:                 }
 1369:             }
 1370:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1371: 
 1372:             if (!$found_server) {
 1373:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1374:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1375:                         ($otherserver,$lowest_load) =
 1376:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                     }
 1378:                 }
 1379:             }
 1380:         } elsif (ref($offloadto) eq 'ARRAY') {
 1381:             if (@{$offloadto} == 1) {
 1382:                 $otherserver = $offloadto->[0];
 1383:             } elsif (@{$offloadto} > 1) {
 1384:                 foreach my $try_server (@{$offloadto}) {
 1385:                     ($otherserver,$lowest_load) =
 1386:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1387:                 }
 1388:             }
 1389:         }
 1390:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1391:             $is_balancer = 0;
 1392:             if ($uname ne '' && $udom ne '') {
 1393:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1394:                     
 1395:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1396:                              'user.loadbalcheck.time' => time});
 1397:                 }
 1398:             }
 1399:         }
 1400:     }
 1401:     return ($is_balancer,$otherserver);
 1402: }
 1403: 
 1404: sub check_balancer_result {
 1405:     my ($result,@hosts) = @_;
 1406:     my ($is_balancer,$currtargets,$currrules);
 1407:     if (ref($result) eq 'HASH') {
 1408:         if ($result->{'lonhost'} ne '') {
 1409:             my $currbalancer = $result->{'lonhost'};
 1410:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1411:                 $is_balancer = 1;
 1412:                 $currtargets = $result->{'targets'};
 1413:                 $currrules = $result->{'rules'};
 1414:             }
 1415:         } else {
 1416:             foreach my $key (keys(%{$result})) {
 1417:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1418:                     (ref($result->{$key}) eq 'HASH')) {
 1419:                     $is_balancer = 1;
 1420:                     $currrules = $result->{$key}{'rules'};
 1421:                     $currtargets = $result->{$key}{'targets'};
 1422:                     last;
 1423:                 }
 1424:             }
 1425:         }
 1426:     }
 1427:     return ($is_balancer,$currtargets,$currrules);
 1428: }
 1429: 
 1430: sub get_loadbalancer_targets {
 1431:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1432:     my $offloadto;
 1433:     if ($rule_in_effect eq 'none') {
 1434:         return [$perlvar{'lonHostID'}];
 1435:     } elsif ($rule_in_effect eq '') {
 1436:         $offloadto = $currtargets;
 1437:     } else {
 1438:         if ($rule_in_effect eq 'homeserver') {
 1439:             my $homeserver = &homeserver($uname,$udom);
 1440:             if ($homeserver ne 'no_host') {
 1441:                 $offloadto = [$homeserver];
 1442:             }
 1443:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1444:             my %domconfig =
 1445:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1446:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1447:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1448:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1449:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1450:                     }
 1451:                 }
 1452:             } else {
 1453:                 my %servers = &internet_dom_servers($udom);
 1454:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1455:                 if (&hostname($remotebalancer) ne '') {
 1456:                     $offloadto = [$remotebalancer];
 1457:                 }
 1458:             }
 1459:         } elsif (&hostname($rule_in_effect) ne '') {
 1460:             $offloadto = [$rule_in_effect];
 1461:         }
 1462:     }
 1463:     return $offloadto;
 1464: }
 1465: 
 1466: sub internet_dom_servers {
 1467:     my ($dom) = @_;
 1468:     my (%uniqservers,%servers);
 1469:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1470:     my @machinedoms = &machine_domains($primaryserver);
 1471:     foreach my $mdom (@machinedoms) {
 1472:         my %currservers = %servers;
 1473:         my %server = &get_servers($mdom);
 1474:         %servers = (%currservers,%server);
 1475:     }
 1476:     my %by_hostname;
 1477:     foreach my $id (keys(%servers)) {
 1478:         push(@{$by_hostname{$servers{$id}}},$id);
 1479:     }
 1480:     foreach my $hostname (sort(keys(%by_hostname))) {
 1481:         if (@{$by_hostname{$hostname}} > 1) {
 1482:             my $match = 0;
 1483:             foreach my $id (@{$by_hostname{$hostname}}) {
 1484:                 if (&host_domain($id) eq $dom) {
 1485:                     $uniqservers{$id} = $hostname;
 1486:                     $match = 1;
 1487:                 }
 1488:             }
 1489:             unless ($match) {
 1490:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:             }
 1492:         } else {
 1493:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1494:         }
 1495:     }
 1496:     return %uniqservers;
 1497: }
 1498: 
 1499: # ---------------------- Find the homebase for a user from domain's lib servers
 1500: 
 1501: my %homecache;
 1502: sub homeserver {
 1503:     my ($uname,$udom,$ignoreBadCache)=@_;
 1504:     my $index="$uname:$udom";
 1505: 
 1506:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1507: 
 1508:     my %servers = &get_servers($udom,'library');
 1509:     foreach my $tryserver (keys(%servers)) {
 1510:         next if ($ignoreBadCache ne 'true' && 
 1511: 		 exists($badServerCache{$tryserver}));
 1512: 
 1513: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1514: 	if ($answer eq 'found') {
 1515: 	    delete($badServerCache{$tryserver}); 
 1516: 	    return $homecache{$index}=$tryserver;
 1517: 	} elsif ($answer eq 'no_host') {
 1518: 	    $badServerCache{$tryserver}=1;
 1519: 	}
 1520:     }    
 1521:     return 'no_host';
 1522: }
 1523: 
 1524: # ------------------------------------- Find the usernames behind a list of IDs
 1525: 
 1526: sub idget {
 1527:     my ($udom,@ids)=@_;
 1528:     my %returnhash=();
 1529:     
 1530:     my %servers = &get_servers($udom,'library');
 1531:     foreach my $tryserver (keys(%servers)) {
 1532: 	my $idlist=join('&',@ids);
 1533: 	$idlist=~tr/A-Z/a-z/; 
 1534: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1535: 	my @answer=();
 1536: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1537: 	    @answer=split(/\&/,$reply);
 1538: 	}                    ;
 1539: 	my $i;
 1540: 	for ($i=0;$i<=$#ids;$i++) {
 1541: 	    if ($answer[$i]) {
 1542: 		$returnhash{$ids[$i]}=$answer[$i];
 1543: 	    } 
 1544: 	}
 1545:     } 
 1546:     return %returnhash;
 1547: }
 1548: 
 1549: # ------------------------------------- Find the IDs behind a list of usernames
 1550: 
 1551: sub idrget {
 1552:     my ($udom,@unames)=@_;
 1553:     my %returnhash=();
 1554:     foreach my $uname (@unames) {
 1555:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1556:     }
 1557:     return %returnhash;
 1558: }
 1559: 
 1560: # ------------------------------- Store away a list of names and associated IDs
 1561: 
 1562: sub idput {
 1563:     my ($udom,%ids)=@_;
 1564:     my %servers=();
 1565:     foreach my $uname (keys(%ids)) {
 1566: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1567:         my $uhom=&homeserver($uname,$udom);
 1568:         if ($uhom ne 'no_host') {
 1569:             my $id=&escape($ids{$uname});
 1570:             $id=~tr/A-Z/a-z/;
 1571:             my $esc_unam=&escape($uname);
 1572: 	    if ($servers{$uhom}) {
 1573: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1574:             } else {
 1575:                 $servers{$uhom}=$id.'='.$esc_unam;
 1576:             }
 1577:         }
 1578:     }
 1579:     foreach my $server (keys(%servers)) {
 1580:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1581:     }
 1582: }
 1583: 
 1584: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1585: 
 1586: sub iddel {
 1587:     my ($udom,$idshashref,$uhome)=@_;
 1588:     my %result=();
 1589:     unless (ref($idshashref) eq 'HASH') {
 1590:         return %result;
 1591:     }
 1592:     my %servers=();
 1593:     while (my ($id,$uname) = each(%{$idshashref})) {
 1594:         my $uhom;
 1595:         if ($uhome) {
 1596:             $uhom = $uhome;
 1597:         } else {
 1598:             $uhom=&homeserver($uname,$udom);
 1599:         }
 1600:         if ($uhom ne 'no_host') {
 1601:             if ($servers{$uhom}) {
 1602:                 $servers{$uhom}.='&'.&escape($id);
 1603:             } else {
 1604:                 $servers{$uhom}=&escape($id);
 1605:             }
 1606:         }
 1607:     }
 1608:     foreach my $server (keys(%servers)) {
 1609:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1610:     }
 1611:     return %result;
 1612: }
 1613: 
 1614: # ------------------------------dump from db file owned by domainconfig user
 1615: sub dump_dom {
 1616:     my ($namespace, $udom, $regexp) = @_;
 1617: 
 1618:     $udom ||= $env{'user.domain'};
 1619: 
 1620:     return () unless $udom;
 1621: 
 1622:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1623: }
 1624: 
 1625: # ------------------------------------------ get items from domain db files   
 1626: 
 1627: sub get_dom {
 1628:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1629:     my $items='';
 1630:     foreach my $item (@$storearr) {
 1631:         $items.=&escape($item).'&';
 1632:     }
 1633:     $items=~s/\&$//;
 1634:     if (!$udom) {
 1635:         $udom=$env{'user.domain'};
 1636:         if (defined(&domain($udom,'primary'))) {
 1637:             $uhome=&domain($udom,'primary');
 1638:         } else {
 1639:             undef($uhome);
 1640:         }
 1641:     } else {
 1642:         if (!$uhome) {
 1643:             if (defined(&domain($udom,'primary'))) {
 1644:                 $uhome=&domain($udom,'primary');
 1645:             }
 1646:         }
 1647:     }
 1648:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1649:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1650:         my %returnhash;
 1651:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1652:             return %returnhash;
 1653:         }
 1654:         my @pairs=split(/\&/,$rep);
 1655:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1656:             return @pairs;
 1657:         }
 1658:         my $i=0;
 1659:         foreach my $item (@$storearr) {
 1660:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1661:             $i++;
 1662:         }
 1663:         return %returnhash;
 1664:     } else {
 1665:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1666:     }
 1667: }
 1668: 
 1669: # -------------------------------------------- put items in domain db files 
 1670: 
 1671: sub put_dom {
 1672:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1673:     if (!$udom) {
 1674:         $udom=$env{'user.domain'};
 1675:         if (defined(&domain($udom,'primary'))) {
 1676:             $uhome=&domain($udom,'primary');
 1677:         } else {
 1678:             undef($uhome);
 1679:         }
 1680:     } else {
 1681:         if (!$uhome) {
 1682:             if (defined(&domain($udom,'primary'))) {
 1683:                 $uhome=&domain($udom,'primary');
 1684:             }
 1685:         }
 1686:     } 
 1687:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1688:         my $items='';
 1689:         foreach my $item (keys(%$storehash)) {
 1690:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1691:         }
 1692:         $items=~s/\&$//;
 1693:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1694:     } else {
 1695:         &logthis("put_dom failed - no homeserver and/or domain");
 1696:     }
 1697: }
 1698: 
 1699: # --------------------- newput for items in db file owned by domainconfig user
 1700: sub newput_dom {
 1701:     my ($namespace,$storehash,$udom) = @_;
 1702:     my $result;
 1703:     if (!$udom) {
 1704:         $udom=$env{'user.domain'};
 1705:     }
 1706:     if ($udom) {
 1707:         my $uname = &get_domainconfiguser($udom);
 1708:         $result = &newput($namespace,$storehash,$udom,$uname);
 1709:     }
 1710:     return $result;
 1711: }
 1712: 
 1713: # --------------------- delete for items in db file owned by domainconfig user
 1714: sub del_dom {
 1715:     my ($namespace,$storearr,$udom)=@_;
 1716:     if (ref($storearr) eq 'ARRAY') {
 1717:         if (!$udom) {
 1718:             $udom=$env{'user.domain'};
 1719:         }
 1720:         if ($udom) {
 1721:             my $uname = &get_domainconfiguser($udom); 
 1722:             return &del($namespace,$storearr,$udom,$uname);
 1723:         }
 1724:     }
 1725: }
 1726: 
 1727: # ----------------------------------construct domainconfig user for a domain 
 1728: sub get_domainconfiguser {
 1729:     my ($udom) = @_;
 1730:     return $udom.'-domainconfig';
 1731: }
 1732: 
 1733: sub retrieve_inst_usertypes {
 1734:     my ($udom) = @_;
 1735:     my (%returnhash,@order);
 1736:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1737:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1738:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1739:         %returnhash = %{$domdefs{'inststatustypes'}};
 1740:         @order = @{$domdefs{'inststatusorder'}};
 1741:     } else {
 1742:         if (defined(&domain($udom,'primary'))) {
 1743:             my $uhome=&domain($udom,'primary');
 1744:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1745:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1746:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1747:                 return (\%returnhash,\@order);
 1748:             }
 1749:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1750:             my @pairs=split(/\&/,$hashitems);
 1751:             foreach my $item (@pairs) {
 1752:                 my ($key,$value)=split(/=/,$item,2);
 1753:                 $key = &unescape($key);
 1754:                 next if ($key =~ /^error: 2 /);
 1755:                 $returnhash{$key}=&thaw_unescape($value);
 1756:             }
 1757:             my @esc_order = split(/\&/,$orderitems);
 1758:             foreach my $item (@esc_order) {
 1759:                 push(@order,&unescape($item));
 1760:             }
 1761:         } else {
 1762:             &logthis("get_dom failed - no primary domain server for $udom");
 1763:         }
 1764:     }
 1765:     return (\%returnhash,\@order);
 1766: }
 1767: 
 1768: sub is_domainimage {
 1769:     my ($url) = @_;
 1770:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1771:         if (&domain($1) ne '') {
 1772:             return '1';
 1773:         }
 1774:     }
 1775:     return;
 1776: }
 1777: 
 1778: sub inst_directory_query {
 1779:     my ($srch) = @_;
 1780:     my $udom = $srch->{'srchdomain'};
 1781:     my %results;
 1782:     my $homeserver = &domain($udom,'primary');
 1783:     my $outcome;
 1784:     if ($homeserver ne '') {
 1785: 	my $queryid=&reply("querysend:instdirsearch:".
 1786: 			   &escape($srch->{'srchby'}).':'.
 1787: 			   &escape($srch->{'srchterm'}).':'.
 1788: 			   &escape($srch->{'srchtype'}),$homeserver);
 1789: 	my $host=&hostname($homeserver);
 1790: 	if ($queryid !~/^\Q$host\E\_/) {
 1791: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1792: 	    return;
 1793: 	}
 1794: 	my $response = &get_query_reply($queryid);
 1795: 	my $maxtries = 5;
 1796: 	my $tries = 1;
 1797: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1798: 	    $response = &get_query_reply($queryid);
 1799: 	    $tries ++;
 1800: 	}
 1801: 
 1802:         if (!&error($response) && $response ne 'refused') {
 1803:             if ($response eq 'unavailable') {
 1804:                 $outcome = $response;
 1805:             } else {
 1806:                 $outcome = 'ok';
 1807:                 my @matches = split(/\n/,$response);
 1808:                 foreach my $match (@matches) {
 1809:                     my ($key,$value) = split(/=/,$match);
 1810:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1811:                 }
 1812:             }
 1813:         }
 1814:     }
 1815:     return ($outcome,%results);
 1816: }
 1817: 
 1818: sub usersearch {
 1819:     my ($srch) = @_;
 1820:     my $dom = $srch->{'srchdomain'};
 1821:     my %results;
 1822:     my %libserv = &all_library();
 1823:     my $query = 'usersearch';
 1824:     foreach my $tryserver (keys(%libserv)) {
 1825:         if (&host_domain($tryserver) eq $dom) {
 1826:             my $host=&hostname($tryserver);
 1827:             my $queryid=
 1828:                 &reply("querysend:".&escape($query).':'.
 1829:                        &escape($srch->{'srchby'}).':'.
 1830:                        &escape($srch->{'srchtype'}).':'.
 1831:                        &escape($srch->{'srchterm'}),$tryserver);
 1832:             if ($queryid !~/^\Q$host\E\_/) {
 1833:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1834:                 next;
 1835:             }
 1836:             my $reply = &get_query_reply($queryid);
 1837:             my $maxtries = 1;
 1838:             my $tries = 1;
 1839:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1840:                 $reply = &get_query_reply($queryid);
 1841:                 $tries ++;
 1842:             }
 1843:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1844:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1845:             } else {
 1846:                 my @matches;
 1847:                 if ($reply =~ /\n/) {
 1848:                     @matches = split(/\n/,$reply);
 1849:                 } else {
 1850:                     @matches = split(/\&/,$reply);
 1851:                 }
 1852:                 foreach my $match (@matches) {
 1853:                     my ($uname,$udom,%userhash);
 1854:                     foreach my $entry (split(/:/,$match)) {
 1855:                         my ($key,$value) =
 1856:                             map {&unescape($_);} split(/=/,$entry);
 1857:                         $userhash{$key} = $value;
 1858:                         if ($key eq 'username') {
 1859:                             $uname = $value;
 1860:                         } elsif ($key eq 'domain') {
 1861:                             $udom = $value;
 1862:                         }
 1863:                     }
 1864:                     $results{$uname.':'.$udom} = \%userhash;
 1865:                 }
 1866:             }
 1867:         }
 1868:     }
 1869:     return %results;
 1870: }
 1871: 
 1872: sub get_instuser {
 1873:     my ($udom,$uname,$id) = @_;
 1874:     my $homeserver = &domain($udom,'primary');
 1875:     my ($outcome,%results);
 1876:     if ($homeserver ne '') {
 1877:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1878:                            &escape($id).':'.&escape($udom),$homeserver);
 1879:         my $host=&hostname($homeserver);
 1880:         if ($queryid !~/^\Q$host\E\_/) {
 1881:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1882:             return;
 1883:         }
 1884:         my $response = &get_query_reply($queryid);
 1885:         my $maxtries = 5;
 1886:         my $tries = 1;
 1887:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1888:             $response = &get_query_reply($queryid);
 1889:             $tries ++;
 1890:         }
 1891:         if (!&error($response) && $response ne 'refused') {
 1892:             if ($response eq 'unavailable') {
 1893:                 $outcome = $response;
 1894:             } else {
 1895:                 $outcome = 'ok';
 1896:                 my @matches = split(/\n/,$response);
 1897:                 foreach my $match (@matches) {
 1898:                     my ($key,$value) = split(/=/,$match);
 1899:                     $results{&unescape($key)} = &thaw_unescape($value);
 1900:                 }
 1901:             }
 1902:         }
 1903:     }
 1904:     my %userinfo;
 1905:     if (ref($results{$uname}) eq 'HASH') {
 1906:         %userinfo = %{$results{$uname}};
 1907:     } 
 1908:     return ($outcome,%userinfo);
 1909: }
 1910: 
 1911: sub inst_rulecheck {
 1912:     my ($udom,$uname,$id,$item,$rules) = @_;
 1913:     my %returnhash;
 1914:     if ($udom ne '') {
 1915:         if (ref($rules) eq 'ARRAY') {
 1916:             @{$rules} = map {&escape($_);} (@{$rules});
 1917:             my $rulestr = join(':',@{$rules});
 1918:             my $homeserver=&domain($udom,'primary');
 1919:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1920:                 my $response;
 1921:                 if ($item eq 'username') {                
 1922:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1923:                                               ':'.&escape($uname).':'.$rulestr,
 1924:                                               $homeserver));
 1925:                 } elsif ($item eq 'id') {
 1926:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1927:                                               ':'.&escape($id).':'.$rulestr,
 1928:                                               $homeserver));
 1929:                 } elsif ($item eq 'selfcreate') {
 1930:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1931:                                                &escape($udom).':'.&escape($uname).
 1932:                                               ':'.$rulestr,$homeserver));
 1933:                 }
 1934:                 if ($response ne 'refused') {
 1935:                     my @pairs=split(/\&/,$response);
 1936:                     foreach my $item (@pairs) {
 1937:                         my ($key,$value)=split(/=/,$item,2);
 1938:                         $key = &unescape($key);
 1939:                         next if ($key =~ /^error: 2 /);
 1940:                         $returnhash{$key}=&thaw_unescape($value);
 1941:                     }
 1942:                 }
 1943:             }
 1944:         }
 1945:     }
 1946:     return %returnhash;
 1947: }
 1948: 
 1949: sub inst_userrules {
 1950:     my ($udom,$check) = @_;
 1951:     my (%ruleshash,@ruleorder);
 1952:     if ($udom ne '') {
 1953:         my $homeserver=&domain($udom,'primary');
 1954:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1955:             my $response;
 1956:             if ($check eq 'id') {
 1957:                 $response=&reply('instidrules:'.&escape($udom),
 1958:                                  $homeserver);
 1959:             } elsif ($check eq 'email') {
 1960:                 $response=&reply('instemailrules:'.&escape($udom),
 1961:                                  $homeserver);
 1962:             } else {
 1963:                 $response=&reply('instuserrules:'.&escape($udom),
 1964:                                  $homeserver);
 1965:             }
 1966:             if (($response ne 'refused') && ($response ne 'error') && 
 1967:                 ($response ne 'unknown_cmd') && 
 1968:                 ($response ne 'no_such_host')) {
 1969:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1970:                 my @pairs=split(/\&/,$hashitems);
 1971:                 foreach my $item (@pairs) {
 1972:                     my ($key,$value)=split(/=/,$item,2);
 1973:                     $key = &unescape($key);
 1974:                     next if ($key =~ /^error: 2 /);
 1975:                     $ruleshash{$key}=&thaw_unescape($value);
 1976:                 }
 1977:                 my @esc_order = split(/\&/,$orderitems);
 1978:                 foreach my $item (@esc_order) {
 1979:                     push(@ruleorder,&unescape($item));
 1980:                 }
 1981:             }
 1982:         }
 1983:     }
 1984:     return (\%ruleshash,\@ruleorder);
 1985: }
 1986: 
 1987: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1988: 
 1989: sub get_domain_defaults {
 1990:     my ($domain,$ignore_cache) = @_;
 1991:     return if (($domain eq '') || ($domain eq 'public'));
 1992:     my $cachetime = 60*60*24;
 1993:     unless ($ignore_cache) {
 1994:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1995:         if (defined($cached)) {
 1996:             if (ref($result) eq 'HASH') {
 1997:                 return %{$result};
 1998:             }
 1999:         }
 2000:     }
 2001:     my %domdefaults;
 2002:     my %domconfig =
 2003:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2004:                                   'requestcourses','inststatus',
 2005:                                   'coursedefaults','usersessions',
 2006:                                   'requestauthor'],$domain);
 2007:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2008:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2009:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2010:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2011:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2012:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2013:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2014:     } else {
 2015:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2016:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2017:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2018:     }
 2019:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2020:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2021:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2022:         } else {
 2023:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2024:         }
 2025:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2026:         foreach my $item (@usertools) {
 2027:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2028:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2029:             }
 2030:         }
 2031:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2032:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2033:         }
 2034:     }
 2035:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2036:         foreach my $item ('official','unofficial','community') {
 2037:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2038:         }
 2039:     }
 2040:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2041:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2042:     }
 2043:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2044:         foreach my $item ('inststatustypes','inststatusorder') {
 2045:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2046:         }
 2047:     }
 2048:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2049:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2050:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2051:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2052:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2053:         }
 2054:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2055:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2056:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2057:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2058:         }
 2059:     }
 2060:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2061:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2062:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2063:         }
 2064:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2065:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2066:         }
 2067:     }
 2068:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2069:     return %domdefaults;
 2070: }
 2071: 
 2072: # --------------------------------------------------- Assign a key to a student
 2073: 
 2074: sub assign_access_key {
 2075: #
 2076: # a valid key looks like uname:udom#comments
 2077: # comments are being appended
 2078: #
 2079:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2080:     $kdom=
 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2082:     $knum=
 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2084:     $cdom=
 2085:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2086:     $cnum=
 2087:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2088:     $udom=$env{'user.name'} unless (defined($udom));
 2089:     $uname=$env{'user.domain'} unless (defined($uname));
 2090:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2091:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2092:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2093:                                                   # assigned to this person
 2094:                                                   # - this should not happen,
 2095:                                                   # unless something went wrong
 2096:                                                   # the first time around
 2097: # ready to assign
 2098:         $logentry=$1.'; '.$logentry;
 2099:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2100:                                                  $kdom,$knum) eq 'ok') {
 2101: # key now belongs to user
 2102: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2103:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2104:                 &appenv({'environment.'.$envkey => $ckey});
 2105:                 return 'ok';
 2106:             } else {
 2107:                 return 
 2108:   'error: Count not permanently assign key, will need to be re-entered later.';
 2109: 	    }
 2110:         } else {
 2111:             return 'error: Could not assign key, try again later.';
 2112:         }
 2113:     } elsif (!$existing{$ckey}) {
 2114: # the key does not exist
 2115: 	return 'error: The key does not exist';
 2116:     } else {
 2117: # the key is somebody else's
 2118: 	return 'error: The key is already in use';
 2119:     }
 2120: }
 2121: 
 2122: # ------------------------------------------ put an additional comment on a key
 2123: 
 2124: sub comment_access_key {
 2125: #
 2126: # a valid key looks like uname:udom#comments
 2127: # comments are being appended
 2128: #
 2129:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2130:     $cdom=
 2131:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2132:     $cnum=
 2133:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2134:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2135:     if ($existing{$ckey}) {
 2136:         $existing{$ckey}.='; '.$logentry;
 2137: # ready to assign
 2138:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2139:                                                  $cdom,$cnum) eq 'ok') {
 2140: 	    return 'ok';
 2141:         } else {
 2142: 	    return 'error: Count not store comment.';
 2143:         }
 2144:     } else {
 2145: # the key does not exist
 2146: 	return 'error: The key does not exist';
 2147:     }
 2148: }
 2149: 
 2150: # ------------------------------------------------------ Generate a set of keys
 2151: 
 2152: sub generate_access_keys {
 2153:     my ($number,$cdom,$cnum,$logentry)=@_;
 2154:     $cdom=
 2155:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2156:     $cnum=
 2157:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2158:     unless (&allowed('mky',$cdom)) { return 0; }
 2159:     unless (($cdom) && ($cnum)) { return 0; }
 2160:     if ($number>10000) { return 0; }
 2161:     sleep(2); # make sure don't get same seed twice
 2162:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2163:     my $total=0;
 2164:     for (my $i=1;$i<=$number;$i++) {
 2165:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2166:                   sprintf("%lx",int(100000*rand)).'-'.
 2167:                   sprintf("%lx",int(100000*rand));
 2168:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2169:        $newkey=~s/0/h/g; # and also 0 and O
 2170:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2171:        if ($existing{$newkey}) {
 2172:            $i--;
 2173:        } else {
 2174: 	  if (&put('accesskeys',
 2175:               { $newkey => '# generated '.localtime().
 2176:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2177:                            '; '.$logentry },
 2178: 		   $cdom,$cnum) eq 'ok') {
 2179:               $total++;
 2180: 	  }
 2181:        }
 2182:     }
 2183:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2184:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2185:     return $total;
 2186: }
 2187: 
 2188: # ------------------------------------------------------- Validate an accesskey
 2189: 
 2190: sub validate_access_key {
 2191:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2192:     $cdom=
 2193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2194:     $cnum=
 2195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2196:     $udom=$env{'user.domain'} unless (defined($udom));
 2197:     $uname=$env{'user.name'} unless (defined($uname));
 2198:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2199:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2200: }
 2201: 
 2202: # ------------------------------------- Find the section of student in a course
 2203: sub devalidate_getsection_cache {
 2204:     my ($udom,$unam,$courseid)=@_;
 2205:     my $hashid="$udom:$unam:$courseid";
 2206:     &devalidate_cache_new('getsection',$hashid);
 2207: }
 2208: 
 2209: sub courseid_to_courseurl {
 2210:     my ($courseid) = @_;
 2211:     #already url style courseid
 2212:     return $courseid if ($courseid =~ m{^/});
 2213: 
 2214:     if (exists($env{'course.'.$courseid.'.num'})) {
 2215: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2216: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2217: 	return "/$cdom/$cnum";
 2218:     }
 2219: 
 2220:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2221:     if (exists($courseinfo{'num'})) {
 2222: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2223:     }
 2224: 
 2225:     return undef;
 2226: }
 2227: 
 2228: sub getsection {
 2229:     my ($udom,$unam,$courseid)=@_;
 2230:     my $cachetime=1800;
 2231: 
 2232:     my $hashid="$udom:$unam:$courseid";
 2233:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2234:     if (defined($cached)) { return $result; }
 2235: 
 2236:     my %Pending; 
 2237:     my %Expired;
 2238:     #
 2239:     # Each role can either have not started yet (pending), be active, 
 2240:     #    or have expired.
 2241:     #
 2242:     # If there is an active role, we are done.
 2243:     #
 2244:     # If there is more than one role which has not started yet, 
 2245:     #     choose the one which will start sooner
 2246:     # If there is one role which has not started yet, return it.
 2247:     #
 2248:     # If there is more than one expired role, choose the one which ended last.
 2249:     # If there is a role which has expired, return it.
 2250:     #
 2251:     $courseid = &courseid_to_courseurl($courseid);
 2252:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2253:     foreach my $key (keys(%roleshash)) {
 2254:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2255:         my $section=$1;
 2256:         if ($key eq $courseid.'_st') { $section=''; }
 2257:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2258:         my $now=time;
 2259:         if (defined($end) && $end && ($now > $end)) {
 2260:             $Expired{$end}=$section;
 2261:             next;
 2262:         }
 2263:         if (defined($start) && $start && ($now < $start)) {
 2264:             $Pending{$start}=$section;
 2265:             next;
 2266:         }
 2267:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2268:     }
 2269:     #
 2270:     # Presumedly there will be few matching roles from the above
 2271:     # loop and the sorting time will be negligible.
 2272:     if (scalar(keys(%Pending))) {
 2273:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2274:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2275:     } 
 2276:     if (scalar(keys(%Expired))) {
 2277:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2278:         my $time = pop(@sorted);
 2279:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2280:     }
 2281:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2282: }
 2283: 
 2284: sub save_cache {
 2285:     &purge_remembered();
 2286:     #&Apache::loncommon::validate_page();
 2287:     undef(%env);
 2288:     undef($env_loaded);
 2289: }
 2290: 
 2291: my $to_remember=-1;
 2292: my %remembered;
 2293: my %accessed;
 2294: my $kicks=0;
 2295: my $hits=0;
 2296: sub make_key {
 2297:     my ($name,$id) = @_;
 2298:     if (length($id) > 65 
 2299: 	&& length(&escape($id)) > 200) {
 2300: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2301:     }
 2302:     return &escape($name.':'.$id);
 2303: }
 2304: 
 2305: sub devalidate_cache_new {
 2306:     my ($name,$id,$debug) = @_;
 2307:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2308:     $id=&make_key($name,$id);
 2309:     $memcache->delete($id);
 2310:     delete($remembered{$id});
 2311:     delete($accessed{$id});
 2312: }
 2313: 
 2314: sub is_cached_new {
 2315:     my ($name,$id,$debug) = @_;
 2316:     $id=&make_key($name,$id);
 2317:     if (exists($remembered{$id})) {
 2318: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2319: 	$accessed{$id}=[&gettimeofday()];
 2320: 	$hits++;
 2321: 	return ($remembered{$id},1);
 2322:     }
 2323:     my $value = $memcache->get($id);
 2324:     if (!(defined($value))) {
 2325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2326: 	return (undef,undef);
 2327:     }
 2328:     if ($value eq '__undef__') {
 2329: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2330: 	$value=undef;
 2331:     }
 2332:     &make_room($id,$value,$debug);
 2333:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2334:     return ($value,1);
 2335: }
 2336: 
 2337: sub do_cache_new {
 2338:     my ($name,$id,$value,$time,$debug) = @_;
 2339:     $id=&make_key($name,$id);
 2340:     my $setvalue=$value;
 2341:     if (!defined($setvalue)) {
 2342: 	$setvalue='__undef__';
 2343:     }
 2344:     if (!defined($time) ) {
 2345: 	$time=600;
 2346:     }
 2347:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2348:     my $result = $memcache->set($id,$setvalue,$time);
 2349:     if (! $result) {
 2350: 	&logthis("caching of id -> $id  failed");
 2351: 	$memcache->disconnect_all();
 2352:     }
 2353:     # need to make a copy of $value
 2354:     &make_room($id,$value,$debug);
 2355:     return $value;
 2356: }
 2357: 
 2358: sub make_room {
 2359:     my ($id,$value,$debug)=@_;
 2360: 
 2361:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2362:                                     : $value;
 2363:     if ($to_remember<0) { return; }
 2364:     $accessed{$id}=[&gettimeofday()];
 2365:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2366:     my $to_kick;
 2367:     my $max_time=0;
 2368:     foreach my $other (keys(%accessed)) {
 2369: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2370: 	    $to_kick=$other;
 2371: 	    $max_time=&tv_interval($accessed{$other});
 2372: 	}
 2373:     }
 2374:     delete($remembered{$to_kick});
 2375:     delete($accessed{$to_kick});
 2376:     $kicks++;
 2377:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2378:     return;
 2379: }
 2380: 
 2381: sub purge_remembered {
 2382:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2383:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2384:     undef(%remembered);
 2385:     undef(%accessed);
 2386: }
 2387: # ------------------------------------- Read an entry from a user's environment
 2388: 
 2389: sub userenvironment {
 2390:     my ($udom,$unam,@what)=@_;
 2391:     my $items;
 2392:     foreach my $item (@what) {
 2393:         $items.=&escape($item).'&';
 2394:     }
 2395:     $items=~s/\&$//;
 2396:     my %returnhash=();
 2397:     my $uhome = &homeserver($unam,$udom);
 2398:     unless ($uhome eq 'no_host') {
 2399:         my @answer=split(/\&/, 
 2400:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2401:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2402:             return %returnhash;
 2403:         }
 2404:         my $i;
 2405:         for ($i=0;$i<=$#what;$i++) {
 2406: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2407:         }
 2408:     }
 2409:     return %returnhash;
 2410: }
 2411: 
 2412: # ---------------------------------------------------------- Get a studentphoto
 2413: sub studentphoto {
 2414:     my ($udom,$unam,$ext) = @_;
 2415:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2416:     if (defined($env{'request.course.id'})) {
 2417:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2418:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2419:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2420:             } else {
 2421:                 my ($result,$perm_reqd)=
 2422: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2423:                 if ($result eq 'ok') {
 2424:                     if (!($perm_reqd eq 'yes')) {
 2425:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2426:                     }
 2427:                 }
 2428:             }
 2429:         }
 2430:     } else {
 2431:         my ($result,$perm_reqd) = 
 2432: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2433:         if ($result eq 'ok') {
 2434:             if (!($perm_reqd eq 'yes')) {
 2435:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2436:             }
 2437:         }
 2438:     }
 2439:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2440: }
 2441: 
 2442: sub retrievestudentphoto {
 2443:     my ($udom,$unam,$ext,$type) = @_;
 2444:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2445:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2446:     if ($ret eq 'ok') {
 2447:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2448:         if ($type eq 'thumbnail') {
 2449:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2450:         }
 2451:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2452:         return $tokenurl;
 2453:     } else {
 2454:         if ($type eq 'thumbnail') {
 2455:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2456:         } else { 
 2457:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2458:         }
 2459:     }
 2460: }
 2461: 
 2462: # -------------------------------------------------------------------- New chat
 2463: 
 2464: sub chatsend {
 2465:     my ($newentry,$anon,$group)=@_;
 2466:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2468:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2469:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2470: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2471: 		   &escape($newentry)).':'.$group,$chome);
 2472: }
 2473: 
 2474: # ------------------------------------------ Find current version of a resource
 2475: 
 2476: sub getversion {
 2477:     my $fname=&clutter(shift);
 2478:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2479:     return &currentversion(&filelocation('',$fname));
 2480: }
 2481: 
 2482: sub currentversion {
 2483:     my $fname=shift;
 2484:     my $author=$fname;
 2485:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2486:     my ($udom,$uname)=split(/\//,$author);
 2487:     my $home=&homeserver($uname,$udom);
 2488:     if ($home eq 'no_host') { 
 2489:         return -1; 
 2490:     }
 2491:     my $answer=&reply("currentversion:$fname",$home);
 2492:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2493: 	return -1;
 2494:     }
 2495:     return $answer;
 2496: }
 2497: 
 2498: #
 2499: # Return special version number of resource if set by override, empty otherwise
 2500: #
 2501: sub usedversion {
 2502:     my $fname=shift;
 2503:     unless ($fname) { $fname=$env{'request.uri'}; }
 2504:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2505:     if ($urlversion) { return $urlversion; }
 2506:     return '';
 2507: }
 2508: 
 2509: # ----------------------------- Subscribe to a resource, return URL if possible
 2510: 
 2511: sub subscribe {
 2512:     my $fname=shift;
 2513:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2514:     $fname=~s/[\n\r]//g;
 2515:     my $author=$fname;
 2516:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2517:     my ($udom,$uname)=split(/\//,$author);
 2518:     my $home=homeserver($uname,$udom);
 2519:     if ($home eq 'no_host') {
 2520:         return 'not_found';
 2521:     }
 2522:     my $answer=reply("sub:$fname",$home);
 2523:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2524: 	$answer.=' by '.$home;
 2525:     }
 2526:     return $answer;
 2527: }
 2528:     
 2529: # -------------------------------------------------------------- Replicate file
 2530: 
 2531: sub repcopy {
 2532:     my $filename=shift;
 2533:     $filename=~s/\/+/\//g;
 2534:     my $londocroot = $perlvar{'lonDocRoot'};
 2535:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2536:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2537:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2538: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2539: 	return &repcopy_userfile($filename);
 2540:     }
 2541:     $filename=~s/[\n\r]//g;
 2542:     my $transname="$filename.in.transfer";
 2543: # FIXME: this should flock
 2544:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2545:     my $remoteurl=subscribe($filename);
 2546:     if ($remoteurl =~ /^con_lost by/) {
 2547: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2548:            return 'unavailable';
 2549:     } elsif ($remoteurl eq 'not_found') {
 2550: 	   #&logthis("Subscribe returned not_found: $filename");
 2551: 	   return 'not_found';
 2552:     } elsif ($remoteurl =~ /^rejected by/) {
 2553: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2554:            return 'forbidden';
 2555:     } elsif ($remoteurl eq 'directory') {
 2556:            return 'ok';
 2557:     } else {
 2558:         my $author=$filename;
 2559:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2560:         my ($udom,$uname)=split(/\//,$author);
 2561:         my $home=homeserver($uname,$udom);
 2562:         unless ($home eq $perlvar{'lonHostID'}) {
 2563:            my @parts=split(/\//,$filename);
 2564:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2565:            if ($path ne "$londocroot/res") {
 2566:                &logthis("Malconfiguration for replication: $filename");
 2567: 	       return 'bad_request';
 2568:            }
 2569:            my $count;
 2570:            for ($count=5;$count<$#parts;$count++) {
 2571:                $path.="/$parts[$count]";
 2572:                if ((-e $path)!=1) {
 2573: 		   mkdir($path,0777);
 2574:                }
 2575:            }
 2576:            my $ua=new LWP::UserAgent;
 2577:            my $request=new HTTP::Request('GET',"$remoteurl");
 2578:            my $response=$ua->request($request,$transname);
 2579:            if ($response->is_error()) {
 2580: 	       unlink($transname);
 2581:                my $message=$response->status_line;
 2582:                &logthis("<font color=\"blue\">WARNING:"
 2583:                        ." LWP get: $message: $filename</font>");
 2584:                return 'unavailable';
 2585:            } else {
 2586: 	       if ($remoteurl!~/\.meta$/) {
 2587:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2588:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2589:                   if ($mresponse->is_error()) {
 2590: 		      unlink($filename.'.meta');
 2591:                       &logthis(
 2592:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2593:                   }
 2594: 	       }
 2595:                rename($transname,$filename);
 2596:                return 'ok';
 2597:            }
 2598:        }
 2599:     }
 2600: }
 2601: 
 2602: # ------------------------------------------------ Get server side include body
 2603: sub ssi_body {
 2604:     my ($filelink,%form)=@_;
 2605:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2606:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2607:     }
 2608:     my $output='';
 2609:     my $response;
 2610:     if ($filelink=~/^https?\:/) {
 2611:        ($output,$response)=&externalssi($filelink);
 2612:     } else {
 2613:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2614:        $filelink .= 'inhibitmenu=yes';
 2615:        ($output,$response)=&ssi($filelink,%form);
 2616:     }
 2617:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2618:     $output=~s/^.*?\<body[^\>]*\>//si;
 2619:     $output=~s/\<\/body\s*\>.*?$//si;
 2620:     if (wantarray) {
 2621:         return ($output, $response);
 2622:     } else {
 2623:         return $output;
 2624:     }
 2625: }
 2626: 
 2627: # --------------------------------------------------------- Server Side Include
 2628: 
 2629: sub absolute_url {
 2630:     my ($host_name) = @_;
 2631:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2632:     if ($host_name eq '') {
 2633: 	$host_name = $ENV{'SERVER_NAME'};
 2634:     }
 2635:     return $protocol.$host_name;
 2636: }
 2637: 
 2638: #
 2639: #   Server side include.
 2640: # Parameters:
 2641: #  fn     Possibly encrypted resource name/id.
 2642: #  form   Hash that describes how the rendering should be done
 2643: #         and other things.
 2644: # Returns:
 2645: #   Scalar context: The content of the response.
 2646: #   Array context:  2 element list of the content and the full response object.
 2647: #     
 2648: sub ssi {
 2649: 
 2650:     my ($fn,%form)=@_;
 2651:     my $ua=new LWP::UserAgent;
 2652:     my $request;
 2653: 
 2654:     $form{'no_update_last_known'}=1;
 2655:     &Apache::lonenc::check_encrypt(\$fn);
 2656:     if (%form) {
 2657:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2658:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2659:     } else {
 2660:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2661:     }
 2662: 
 2663:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2664:     my $response= $ua->request($request);
 2665:     my $content = $response->content;
 2666: 
 2667: 
 2668:     if (wantarray) {
 2669: 	return ($content, $response);
 2670:     } else {
 2671: 	return $content;
 2672:     }
 2673: }
 2674: 
 2675: sub externalssi {
 2676:     my ($url)=@_;
 2677:     my $ua=new LWP::UserAgent;
 2678:     my $request=new HTTP::Request('GET',$url);
 2679:     my $response=$ua->request($request);
 2680:     if (wantarray) {
 2681:         return ($response->content, $response);
 2682:     } else {
 2683:         return $response->content;
 2684:     }
 2685: }
 2686: 
 2687: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2688: 
 2689: sub allowuploaded {
 2690:     my ($srcurl,$url)=@_;
 2691:     $url=&clutter(&declutter($url));
 2692:     my $dir=$url;
 2693:     $dir=~s/\/[^\/]+$//;
 2694:     my %httpref=();
 2695:     my $httpurl=&hreflocation('',$url);
 2696:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2697:     &Apache::lonnet::appenv(\%httpref);
 2698: }
 2699: 
 2700: #
 2701: # Determine if the current user should be able to edit a particular resource,
 2702: # when viewing in course context.
 2703: # (a) When viewing resource used to determine if "Edit" item is included in 
 2704: #     Functions.
 2705: # (b) When displaying folder contents in course editor, used to determine if
 2706: #     "Edit" link will be displayed alongside resource.
 2707: #
 2708: #  input: six args -- filename (decluttered), course number, course domain,
 2709: #                   url, symb (if registered) and group (if this is a group
 2710: #                   item -- e.g., bulletin board, group page etc.).
 2711: #  output: array of five scalars -- 
 2712: #          $cfile -- url for file editing if editable on current server
 2713: #          $home -- homeserver of resource (i.e., for author if published,
 2714: #                                           or course if uploaded.).
 2715: #          $switchserver --  1 if server switch will be needed.
 2716: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2717: #          $forceview -- 1 if icon/link should be to go to view mode
 2718: #
 2719: 
 2720: sub can_edit_resource {
 2721:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2722:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2723: #
 2724: # For aboutme pages user can only edit his/her own.
 2725: #
 2726:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2727:         my ($sdom,$sname) = ($1,$2);
 2728:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2729:             $home = $env{'user.home'};
 2730:             $cfile = $resurl;
 2731:             if ($env{'form.forceedit'}) {
 2732:                 $forceview = 1;
 2733:             } else {
 2734:                 $forceedit = 1;
 2735:             }
 2736:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2737:         } else {
 2738:             return;
 2739:         }
 2740:     }
 2741: 
 2742:     if ($env{'request.course.id'}) {
 2743:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2744:         if ($group ne '') {
 2745: # if this is a group homepage or group bulletin board, check group privs
 2746:             my $allowed = 0;
 2747:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2748:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2749:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2750:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2751:                     $allowed = 1;
 2752:                 }
 2753:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2754:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2755:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2756:                     $allowed = 1;
 2757:                 }
 2758:             }
 2759:             if ($allowed) {
 2760:                 $home=&homeserver($cnum,$cdom);
 2761:                 if ($env{'form.forceedit'}) {
 2762:                     $forceview = 1;
 2763:                 } else {
 2764:                     $forceedit = 1;
 2765:                 }
 2766:                 $cfile = $resurl;
 2767:             } else {
 2768:                 return;
 2769:             }
 2770:         } else {
 2771:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2772:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2773:                     return;
 2774:                 }
 2775:             } elsif (!$crsedit) {
 2776: #
 2777: # No edit allowed where CC has switched to student role.
 2778: #
 2779:                 return;
 2780:             }
 2781:         }
 2782:     }
 2783: 
 2784:     if ($file ne '') {
 2785:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2786:             if (&is_course_upload($file,$cnum,$cdom)) {
 2787:                 $uploaded = 1;
 2788:                 $incourse = 1;
 2789:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2790:                     $cfile = &hreflocation('',$file);
 2791:                     if ($env{'form.forceedit'}) {
 2792:                         $forceview = 1;
 2793:                     } else {
 2794:                         $forceedit = 1;
 2795:                     }
 2796:                 }
 2797:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2798:                 $incourse = 1;
 2799:                 if ($env{'form.forceedit'}) {
 2800:                     $forceview = 1;
 2801:                 } else {
 2802:                     $forceedit = 1;
 2803:                 }
 2804:                 $cfile = $resurl;
 2805:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2806:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2807:                     $incourse = 1;
 2808:                     if ($env{'form.forceedit'}) {
 2809:                         $forceview = 1;
 2810:                     } else {
 2811:                         $forceedit = 1;
 2812:                     }
 2813:                     $cfile = $resurl;
 2814:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2815:                     $incourse = 1;
 2816:                     $cfile = $resurl.'/smpedit';
 2817:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2818:                     $incourse = 1;
 2819:                     if ($env{'form.forceedit'}) {
 2820:                         $forceview = 1;
 2821:                     } else {
 2822:                         $forceedit = 1;
 2823:                     }
 2824:                     $cfile = $resurl;
 2825:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2826:                     $incourse = 1;
 2827:                     if ($env{'form.forceedit'}) {
 2828:                         $forceview = 1;
 2829:                     } else {
 2830:                         $forceedit = 1;
 2831:                     }
 2832:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2833:                 }
 2834:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2835:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2836:                 if (&is_on_map($template)) { 
 2837:                     $incourse = 1;
 2838:                     $forceview = 1;
 2839:                     $cfile = $template;
 2840:                 }
 2841:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2842:                     $incourse = 1;
 2843:                     if ($env{'form.forceedit'}) {
 2844:                         $forceview = 1;
 2845:                     } else {
 2846:                         $forceedit = 1;
 2847:                     }
 2848:                     $cfile = $resurl;
 2849:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2850:                 $incourse = 1;
 2851:                 $forceview = 1;
 2852:                 if ($symb) {
 2853:                     my ($map,$id,$res)=&decode_symb($symb);
 2854:                     $env{'request.symb'} = $symb;
 2855:                     $cfile = &clutter($res);
 2856:                 } else {
 2857:                     $cfile = $env{'form.suppurl'};
 2858:                     $cfile =~ s{^http://}{};
 2859:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2860:                 }
 2861:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2862:                 if ($env{'form.forceedit'}) {
 2863:                     $forceview = 1;
 2864:                 } else {
 2865:                     $forceedit = 1;
 2866:                 }
 2867:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2868:             }
 2869:         }
 2870:         if ($uploaded || $incourse) {
 2871:             $home=&homeserver($cnum,$cdom);
 2872:         } elsif ($file !~ m{/$}) {
 2873:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2874:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2875:             # Check that the user has permission to edit this resource
 2876:             my $setpriv = 1;
 2877:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2878:             if (defined($cfudom)) {
 2879:                 $home=&homeserver($cfuname,$cfudom);
 2880:                 $cfile=$file;
 2881:             }
 2882:         }
 2883:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2884:             (($home ne '') && ($home ne 'no_host'))) {
 2885:             my @ids=&current_machine_ids();
 2886:             unless (grep(/^\Q$home\E$/,@ids)) {
 2887:                 $switchserver=1;
 2888:             }
 2889:         }
 2890:     }
 2891:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2892: }
 2893: 
 2894: sub is_course_upload {
 2895:     my ($file,$cnum,$cdom) = @_;
 2896:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2897:     $uploadpath =~ s{^\/}{};
 2898:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2899:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2900:         return 1;
 2901:     }
 2902:     return;
 2903: }
 2904: 
 2905: sub in_course {
 2906:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2907:     if ($hideprivileged) {
 2908:         my $skipuser;
 2909:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2910:         my @possdoms = ($cdom);  
 2911:         if ($coursehash{'checkforpriv'}) { 
 2912:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2913:         }
 2914:         if (&privileged($uname,$udom,\@possdoms)) {
 2915:             $skipuser = 1;
 2916:             if ($coursehash{'nothideprivileged'}) {
 2917:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2918:                     my $user;
 2919:                     if ($item =~ /:/) {
 2920:                         $user = $item;
 2921:                     } else {
 2922:                         $user = join(':',split(/[\@]/,$item));
 2923:                     }
 2924:                     if ($user eq $uname.':'.$udom) {
 2925:                         undef($skipuser);
 2926:                         last;
 2927:                     }
 2928:                 }
 2929:             }
 2930:             if ($skipuser) {
 2931:                 return 0;
 2932:             }
 2933:         }
 2934:     }
 2935:     $type ||= 'any';
 2936:     if (!defined($cdom) || !defined($cnum)) {
 2937:         my $cid  = $env{'request.course.id'};
 2938:         $cdom = $env{'course.'.$cid.'.domain'};
 2939:         $cnum = $env{'course.'.$cid.'.num'};
 2940:     }
 2941:     my $typesref;
 2942:     if (($type eq 'any') || ($type eq 'all')) {
 2943:         $typesref = ['active','previous','future'];
 2944:     } elsif ($type eq 'previous' || $type eq 'future') {
 2945:         $typesref = [$type];
 2946:     }
 2947:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2948:                               $typesref,undef,[$cdom]);
 2949:     my ($tmp) = keys(%roles);
 2950:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2951:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2952:     if (@course_roles > 0) {
 2953:         return 1;
 2954:     }
 2955:     return 0;
 2956: }
 2957: 
 2958: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2959: # input: action, courseID, current domain, intended
 2960: #        path to file, source of file, instruction to parse file for objects,
 2961: #        ref to hash for embedded objects,
 2962: #        ref to hash for codebase of java objects.
 2963: #        reference to scalar to accommodate mime type determined
 2964: #          from File::MMagic if $parser = parse.
 2965: #
 2966: # output: url to file (if action was uploaddoc), 
 2967: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2968: #
 2969: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2970: # course.
 2971: #
 2972: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2973: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2974: #          course's home server.
 2975: #
 2976: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2977: #          be copied from $source (current location) to 
 2978: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2979: #         and will then be copied to
 2980: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2981: #         course's home server.
 2982: #
 2983: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2984: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2985: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2986: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2987: #         in course's home server.
 2988: #
 2989: 
 2990: sub process_coursefile {
 2991:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2992:         $mimetype)=@_;
 2993:     my $fetchresult;
 2994:     my $home=&homeserver($docuname,$docudom);
 2995:     if ($action eq 'propagate') {
 2996:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2997: 			     $home);
 2998:     } else {
 2999:         my $fpath = '';
 3000:         my $fname = $file;
 3001:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3002:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3003:         my $filepath = &build_filepath($fpath);
 3004:         if ($action eq 'copy') {
 3005:             if ($source eq '') {
 3006:                 $fetchresult = 'no source file';
 3007:                 return $fetchresult;
 3008:             } else {
 3009:                 my $destination = $filepath.'/'.$fname;
 3010:                 rename($source,$destination);
 3011:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3012:                                  $home);
 3013:             }
 3014:         } elsif ($action eq 'uploaddoc') {
 3015:             open(my $fh,'>'.$filepath.'/'.$fname);
 3016:             print $fh $env{'form.'.$source};
 3017:             close($fh);
 3018:             if ($parser eq 'parse') {
 3019:                 my $mm = new File::MMagic;
 3020:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3021:                 if ($type eq 'text/html') {
 3022:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3023:                     unless ($parse_result eq 'ok') {
 3024:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3025:                     }
 3026:                 }
 3027:                 if (ref($mimetype)) {
 3028:                     $$mimetype = $type;
 3029:                 } 
 3030:             }
 3031:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3032:                                  $home);
 3033:             if ($fetchresult eq 'ok') {
 3034:                 return '/uploaded/'.$fpath.'/'.$fname;
 3035:             } else {
 3036:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3037:                         ' to host '.$home.': '.$fetchresult);
 3038:                 return '/adm/notfound.html';
 3039:             }
 3040:         }
 3041:     }
 3042:     unless ( $fetchresult eq 'ok') {
 3043:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3044:              ' to host '.$home.': '.$fetchresult);
 3045:     }
 3046:     return $fetchresult;
 3047: }
 3048: 
 3049: sub build_filepath {
 3050:     my ($fpath) = @_;
 3051:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3052:     unless ($fpath eq '') {
 3053:         my @parts=split('/',$fpath);
 3054:         foreach my $part (@parts) {
 3055:             $filepath.= '/'.$part;
 3056:             if ((-e $filepath)!=1) {
 3057:                 mkdir($filepath,0777);
 3058:             }
 3059:         }
 3060:     }
 3061:     return $filepath;
 3062: }
 3063: 
 3064: sub store_edited_file {
 3065:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3066:     my $file = $primary_url;
 3067:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3068:     my $fpath = '';
 3069:     my $fname = $file;
 3070:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3071:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3072:     my $filepath = &build_filepath($fpath);
 3073:     open(my $fh,'>'.$filepath.'/'.$fname);
 3074:     print $fh $content;
 3075:     close($fh);
 3076:     my $home=&homeserver($docuname,$docudom);
 3077:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3078: 			  $home);
 3079:     if ($$fetchresult eq 'ok') {
 3080:         return '/uploaded/'.$fpath.'/'.$fname;
 3081:     } else {
 3082:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3083: 		 ' to host '.$home.': '.$$fetchresult);
 3084:         return '/adm/notfound.html';
 3085:     }
 3086: }
 3087: 
 3088: sub clean_filename {
 3089:     my ($fname,$args)=@_;
 3090: # Replace Windows backslashes by forward slashes
 3091:     $fname=~s/\\/\//g;
 3092:     if (!$args->{'keep_path'}) {
 3093:         # Get rid of everything but the actual filename
 3094: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3095:     }
 3096: # Replace spaces by underscores
 3097:     $fname=~s/\s+/\_/g;
 3098: # Replace all other weird characters by nothing
 3099:     $fname=~s{[^/\w\.\-]}{}g;
 3100: # Replace all .\d. sequences with _\d. so they no longer look like version
 3101: # numbers
 3102:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3103:     return $fname;
 3104: }
 3105: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3106: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3107: # image with the same aspect ratio as the original, but with dimensions which do 
 3108: # not exceed $resizewidth and $resizeheight.
 3109:  
 3110: sub resizeImage {
 3111:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3112:     my $ima = Image::Magick->new;
 3113:     my $resized;
 3114:     if (-e $img_path) {
 3115:         $ima->Read($img_path);
 3116:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3117:             my $width = $ima->Get('width');
 3118:             my $height = $ima->Get('height');
 3119:             if ($width > $resizewidth) {
 3120: 	        my $factor = $width/$resizewidth;
 3121:                 my $newheight = $height/$factor;
 3122:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3123:                 $resized = 1;
 3124:             }
 3125:         }
 3126:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3127:             my $width = $ima->Get('width');
 3128:             my $height = $ima->Get('height');
 3129:             if ($height > $resizeheight) {
 3130:                 my $factor = $height/$resizeheight;
 3131:                 my $newwidth = $width/$factor;
 3132:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3133:                 $resized = 1;
 3134:             }
 3135:         }
 3136:         if ($resized) {
 3137:             $ima->Write($img_path);
 3138:         }
 3139:     }
 3140:     return;
 3141: }
 3142: 
 3143: # --------------- Take an uploaded file and put it into the userfiles directory
 3144: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3145: #                    the desired filename is in $env{"form.$formname.filename"}
 3146: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3147: #                                    canceloverwrite, or ''. 
 3148: #                   if 'coursedoc': upload to the current course
 3149: #                   if 'existingfile': write file to tmp/overwrites directory 
 3150: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3151: #                   $context is passed as argument to &finishuserfileupload
 3152: #        $subdir - directory in userfile to store the file into
 3153: #        $parser - instruction to parse file for objects ($parser = parse)    
 3154: #        $allfiles - reference to hash for embedded objects
 3155: #        $codebase - reference to hash for codebase of java objects
 3156: #        $desuname - username for permanent storage of uploaded file
 3157: #        $dsetudom - domain for permanaent storage of uploaded file
 3158: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3159: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3160: #        $resizewidth - width (pixels) to which to resize uploaded image
 3161: #        $resizeheight - height (pixels) to which to resize uploaded image
 3162: #        $mimetype - reference to scalar to accommodate mime type determined
 3163: #                    from File::MMagic.
 3164: # 
 3165: # output: url of file in userspace, or error: <message> 
 3166: #             or /adm/notfound.html if failure to upload occurse
 3167: 
 3168: sub userfileupload {
 3169:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3170:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3171:     if (!defined($subdir)) { $subdir='unknown'; }
 3172:     my $fname=$env{'form.'.$formname.'.filename'};
 3173:     $fname=&clean_filename($fname);
 3174:     # See if there is anything left
 3175:     unless ($fname) { return 'error: no uploaded file'; }
 3176:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3177:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3178:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3179:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3180:         my $now = time;
 3181:         my $filepath;
 3182:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3183:              $filepath = 'tmp/helprequests/'.$now;
 3184:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3185:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3186:                          '_'.$env{'user.domain'}.'/pending';
 3187:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3188:             my ($docuname,$docudom);
 3189:             if ($destudom) {
 3190:                 $docudom = $destudom;
 3191:             } else {
 3192:                 $docudom = $env{'user.domain'};
 3193:             }
 3194:             if ($destuname) {
 3195:                 $docuname = $destuname;
 3196:             } else {
 3197:                 $docuname = $env{'user.name'};
 3198:             }
 3199:             if (exists($env{'form.group'})) {
 3200:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3201:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3202:             }
 3203:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3204:             if ($context eq 'canceloverwrite') {
 3205:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3206:                 if (-e  $tempfile) {
 3207:                     my @info = stat($tempfile);
 3208:                     if ($info[9] eq $env{'form.timestamp'}) {
 3209:                         unlink($tempfile);
 3210:                     }
 3211:                 }
 3212:                 return;
 3213:             }
 3214:         }
 3215:         # Create the directory if not present
 3216:         my @parts=split(/\//,$filepath);
 3217:         my $fullpath = $perlvar{'lonDaemons'};
 3218:         for (my $i=0;$i<@parts;$i++) {
 3219:             $fullpath .= '/'.$parts[$i];
 3220:             if ((-e $fullpath)!=1) {
 3221:                 mkdir($fullpath,0777);
 3222:             }
 3223:         }
 3224:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3225:         print $fh $env{'form.'.$formname};
 3226:         close($fh);
 3227:         if ($context eq 'existingfile') {
 3228:             my @info = stat($fullpath.'/'.$fname);
 3229:             return ($fullpath.'/'.$fname,$info[9]);
 3230:         } else {
 3231:             return $fullpath.'/'.$fname;
 3232:         }
 3233:     }
 3234:     if ($subdir eq 'scantron') {
 3235:         $fname = 'scantron_orig_'.$fname;
 3236:     } else {
 3237:         $fname="$subdir/$fname";
 3238:     }
 3239:     if ($context eq 'coursedoc') {
 3240: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3241: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3242:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3243:             return &finishuserfileupload($docuname,$docudom,
 3244: 					 $formname,$fname,$parser,$allfiles,
 3245: 					 $codebase,$thumbwidth,$thumbheight,
 3246:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3247:         } else {
 3248:             if ($env{'form.folder'}) {
 3249:                 $fname=$env{'form.folder'}.'/'.$fname;
 3250:             }
 3251:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3252: 				       $fname,$formname,$parser,
 3253: 				       $allfiles,$codebase,$mimetype);
 3254:         }
 3255:     } elsif (defined($destuname)) {
 3256:         my $docuname=$destuname;
 3257:         my $docudom=$destudom;
 3258: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3259: 				     $parser,$allfiles,$codebase,
 3260:                                      $thumbwidth,$thumbheight,
 3261:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3262:     } else {
 3263:         my $docuname=$env{'user.name'};
 3264:         my $docudom=$env{'user.domain'};
 3265:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3266:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3267:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3268:         }
 3269: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3270: 				     $parser,$allfiles,$codebase,
 3271:                                      $thumbwidth,$thumbheight,
 3272:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3273:     }
 3274: }
 3275: 
 3276: sub finishuserfileupload {
 3277:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3278:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3279:     my $path=$docudom.'/'.$docuname.'/';
 3280:     my $filepath=$perlvar{'lonDocRoot'};
 3281:   
 3282:     my ($fnamepath,$file,$fetchthumb);
 3283:     $file=$fname;
 3284:     if ($fname=~m|/|) {
 3285:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3286: 	$path.=$fnamepath.'/';
 3287:     }
 3288:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3289:     my $count;
 3290:     for ($count=4;$count<=$#parts;$count++) {
 3291:         $filepath.="/$parts[$count]";
 3292:         if ((-e $filepath)!=1) {
 3293: 	    mkdir($filepath,0777);
 3294:         }
 3295:     }
 3296: 
 3297: # Save the file
 3298:     {
 3299: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3300: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3301: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3302: 	    return '/adm/notfound.html';
 3303: 	}
 3304:         if ($context eq 'overwrite') {
 3305:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3306:             my $target = $filepath.'/'.$file;
 3307:             if (-e $source) {
 3308:                 my @info = stat($source);
 3309:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3310:                     unless (&File::Copy::move($source,$target)) {
 3311:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3312:                         return "Moving from $source failed";
 3313:                     }
 3314:                 } else {
 3315:                     return "Temporary file: $source had unexpected date/time for last modification";
 3316:                 }
 3317:             } else {
 3318:                 return "Temporary file: $source missing";
 3319:             }
 3320:         } elsif (!print FH ($env{'form.'.$formname})) {
 3321: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3322: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3323: 	    return '/adm/notfound.html';
 3324: 	}
 3325: 	close(FH);
 3326:         if ($resizewidth && $resizeheight) {
 3327:             my $mm = new File::MMagic;
 3328:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3329:             if ($mime_type =~ m{^image/}) {
 3330: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3331:             }  
 3332: 	}
 3333:     }
 3334:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3335:         if (ref($mimetype)) {
 3336:             if ($$mimetype eq '') {
 3337:                 my $mm = new File::MMagic;
 3338:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3339:                 $$mimetype = $type;
 3340:             }
 3341:         }
 3342:     }
 3343:     if ($parser eq 'parse') {
 3344:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3345:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3346:                                                        $allfiles,$codebase);
 3347:             unless ($parse_result eq 'ok') {
 3348:                 &logthis('Failed to parse '.$filepath.$file.
 3349: 	   	         ' for embedded media: '.$parse_result); 
 3350:             }
 3351:         }
 3352:     }
 3353:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3354:         my $input = $filepath.'/'.$file;
 3355:         my $output = $filepath.'/'.'tn-'.$file;
 3356:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3357:         system("convert -sample $thumbsize $input $output");
 3358:         if (-e $filepath.'/'.'tn-'.$file) {
 3359:             $fetchthumb  = 1; 
 3360:         }
 3361:     }
 3362:  
 3363: # Notify homeserver to grep it
 3364: #
 3365:     my $docuhome=&homeserver($docuname,$docudom);	
 3366:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3367:     if ($fetchresult eq 'ok') {
 3368:         if ($fetchthumb) {
 3369:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3370:             if ($thumbresult ne 'ok') {
 3371:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3372:                          $docuhome.': '.$thumbresult);
 3373:             }
 3374:         }
 3375: #
 3376: # Return the URL to it
 3377:         return '/uploaded/'.$path.$file;
 3378:     } else {
 3379:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3380: 		 ': '.$fetchresult);
 3381:         return '/adm/notfound.html';
 3382:     }
 3383: }
 3384: 
 3385: sub extract_embedded_items {
 3386:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3387:     my @state = ();
 3388:     my (%lastids,%related,%shockwave,%flashvars);
 3389:     my %javafiles = (
 3390:                       codebase => '',
 3391:                       code => '',
 3392:                       archive => ''
 3393:                     );
 3394:     my %mediafiles = (
 3395:                       src => '',
 3396:                       movie => '',
 3397:                      );
 3398:     my $p;
 3399:     if ($content) {
 3400:         $p = HTML::LCParser->new($content);
 3401:     } else {
 3402:         $p = HTML::LCParser->new($fullpath);
 3403:     }
 3404:     while (my $t=$p->get_token()) {
 3405: 	if ($t->[0] eq 'S') {
 3406: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3407: 	    push(@state, $tagname);
 3408:             if (lc($tagname) eq 'allow') {
 3409:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3410:             }
 3411: 	    if (lc($tagname) eq 'img') {
 3412: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3413: 	    }
 3414: 	    if (lc($tagname) eq 'a') {
 3415:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3416:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3417:                 }
 3418: 	    }
 3419:             if (lc($tagname) eq 'script') {
 3420:                 my $src;
 3421:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3422:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3423:                 } else {
 3424:                     if ($attr->{'src'} ne '') {
 3425:                         $src = $attr->{'src'};
 3426:                         &add_filetype($allfiles,$src,'src');
 3427:                     }
 3428:                 }
 3429:                 my $text = $p->get_trimmed_text();
 3430:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3431:                     my @swfargs = split(/,/,$1);
 3432:                     foreach my $item (@swfargs) {
 3433:                         $item =~ s/["']//g;
 3434:                         $item =~ s/^\s+//;
 3435:                         $item =~ s/\s+$//;
 3436:                     }
 3437:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3438:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3439:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3440:                         } else {
 3441:                             $related{$swfargs[0]} = [$swfargs[2]];
 3442:                         }
 3443:                     }
 3444:                 }
 3445:             }
 3446:             if (lc($tagname) eq 'link') {
 3447:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3448:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3449:                 }
 3450:             }
 3451: 	    if (lc($tagname) eq 'object' ||
 3452: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3453: 		foreach my $item (keys(%javafiles)) {
 3454: 		    $javafiles{$item} = '';
 3455: 		}
 3456:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3457:                     $lastids{lc($tagname)} = $attr->{'id'};
 3458:                 }
 3459: 	    }
 3460: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3461: 		my $name = lc($attr->{'name'});
 3462: 		foreach my $item (keys(%javafiles)) {
 3463: 		    if ($name eq $item) {
 3464: 			$javafiles{$item} = $attr->{'value'};
 3465: 			last;
 3466: 		    }
 3467: 		}
 3468:                 my $pathfrom;
 3469: 		foreach my $item (keys(%mediafiles)) {
 3470: 		    if ($name eq $item) {
 3471:                         $pathfrom = $attr->{'value'};
 3472:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3473: 			&add_filetype($allfiles,$pathfrom,$name);
 3474: 			last;
 3475: 		    }
 3476: 		}
 3477:                 if ($name eq 'flashvars') {
 3478:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3479:                 }
 3480:                 if ($pathfrom ne '') {
 3481:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3482:                                          $pathfrom);
 3483:                 }
 3484: 	    }
 3485: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3486: 		foreach my $item (keys(%javafiles)) {
 3487: 		    if ($attr->{$item}) {
 3488: 			$javafiles{$item} = $attr->{$item};
 3489: 			last;
 3490: 		    }
 3491: 		}
 3492: 		foreach my $item (keys(%mediafiles)) {
 3493: 		    if ($attr->{$item}) {
 3494: 			&add_filetype($allfiles,$attr->{$item},$item);
 3495: 			last;
 3496: 		    }
 3497: 		}
 3498:                 if (lc($tagname) eq 'embed') {
 3499:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3500:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3501:                                              $attr->{'src'});
 3502:                     }
 3503:                 }
 3504: 	    }
 3505:             if (lc($tagname) eq 'iframe') {
 3506:                 my $src = $attr->{'src'} ;
 3507:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3508:                     &add_filetype($allfiles,$src,'src');
 3509:                 } elsif ($src =~ m{^/}) {
 3510:                     if ($env{'request.course.id'}) {
 3511:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3512:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3513:                         my $url = &hreflocation('',$fullpath);
 3514:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3515:                             my $relpath = $1;
 3516:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3517:                                 &add_filetype($allfiles,$1,'src');
 3518:                             }
 3519:                         }
 3520:                     }
 3521:                 }
 3522:             }
 3523:             if ($t->[4] =~ m{/>$}) {
 3524:                 pop(@state);
 3525:             }
 3526: 	} elsif ($t->[0] eq 'E') {
 3527: 	    my ($tagname) = ($t->[1]);
 3528: 	    if ($javafiles{'codebase'} ne '') {
 3529: 		$javafiles{'codebase'} .= '/';
 3530: 	    }  
 3531: 	    if (lc($tagname) eq 'applet' ||
 3532: 		lc($tagname) eq 'object' ||
 3533: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3534: 		) {
 3535: 		foreach my $item (keys(%javafiles)) {
 3536: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3537: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3538: 			&add_filetype($allfiles,$file,$item);
 3539: 		    }
 3540: 		}
 3541: 	    } 
 3542: 	    pop @state;
 3543: 	}
 3544:     }
 3545:     foreach my $id (sort(keys(%flashvars))) {
 3546:         if ($shockwave{$id} ne '') {
 3547:             my @pairs = split(/\&/,$flashvars{$id});
 3548:             foreach my $pair (@pairs) {
 3549:                 my ($key,$value) = split(/\=/,$pair);
 3550:                 if ($key eq 'thumb') {
 3551:                     &add_filetype($allfiles,$value,$key);
 3552:                 } elsif ($key eq 'content') {
 3553:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3554:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3555:                     if ($ext ne '') {
 3556:                         &add_filetype($allfiles,$path.$value,$ext);
 3557:                     }
 3558:                 }
 3559:             }
 3560:         }
 3561:     }
 3562:     return 'ok';
 3563: }
 3564: 
 3565: sub add_filetype {
 3566:     my ($allfiles,$file,$type)=@_;
 3567:     if (exists($allfiles->{$file})) {
 3568: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3569: 	    push(@{$allfiles->{$file}}, &escape($type));
 3570: 	}
 3571:     } else {
 3572: 	@{$allfiles->{$file}} = (&escape($type));
 3573:     }
 3574: }
 3575: 
 3576: sub embedded_dependency {
 3577:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3578:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3579:         if (($identifier ne '') &&
 3580:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3581:             ($pathfrom ne '')) {
 3582:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3583:             foreach my $dep (@{$related->{$identifier}}) {
 3584:                 &add_filetype($allfiles,$path.$dep,'object');
 3585:             }
 3586:         }
 3587:     }
 3588:     return;
 3589: }
 3590: 
 3591: sub removeuploadedurl {
 3592:     my ($url)=@_;	
 3593:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3594:     return &removeuserfile($uname,$udom,$fname);
 3595: }
 3596: 
 3597: sub removeuserfile {
 3598:     my ($docuname,$docudom,$fname)=@_;
 3599:     my $home=&homeserver($docuname,$docudom);    
 3600:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3601:     if ($result eq 'ok') {	
 3602:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3603:             my $metafile = $fname.'.meta';
 3604:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3605: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3606:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3607:             my $sqlresult = 
 3608:                 &update_portfolio_table($docuname,$docudom,$file,
 3609:                                         'portfolio_metadata',$group,
 3610:                                         'delete');
 3611:         }
 3612:     }
 3613:     return $result;
 3614: }
 3615: 
 3616: sub mkdiruserfile {
 3617:     my ($docuname,$docudom,$dir)=@_;
 3618:     my $home=&homeserver($docuname,$docudom);
 3619:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3620: }
 3621: 
 3622: sub renameuserfile {
 3623:     my ($docuname,$docudom,$old,$new)=@_;
 3624:     my $home=&homeserver($docuname,$docudom);
 3625:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3626:                         &escape("$old").':'.&escape("$new"),$home);
 3627:     if ($result eq 'ok') {
 3628:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3629:             my $oldmeta = $old.'.meta';
 3630:             my $newmeta = $new.'.meta';
 3631:             my $metaresult = 
 3632:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3633: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3634:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3635:             my $sqlresult = 
 3636:                 &update_portfolio_table($docuname,$docudom,$file,
 3637:                                         'portfolio_metadata',$group,
 3638:                                         'delete');
 3639:         }
 3640:     }
 3641:     return $result;
 3642: }
 3643: 
 3644: # ------------------------------------------------------------------------- Log
 3645: 
 3646: sub log {
 3647:     my ($dom,$nam,$hom,$what)=@_;
 3648:     return critical("log:$dom:$nam:$what",$hom);
 3649: }
 3650: 
 3651: # ------------------------------------------------------------------ Course Log
 3652: #
 3653: # This routine flushes several buffers of non-mission-critical nature
 3654: #
 3655: 
 3656: sub flushcourselogs {
 3657:     &logthis('Flushing log buffers');
 3658: #
 3659: # course logs
 3660: # This is a log of all transactions in a course, which can be used
 3661: # for data mining purposes
 3662: #
 3663: # It also collects the courseid database, which lists last transaction
 3664: # times and course titles for all courseids
 3665: #
 3666:     my %courseidbuffer=();
 3667:     foreach my $crsid (keys(%courselogs)) {
 3668:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3669: 		          &escape($courselogs{$crsid}),
 3670: 		          $coursehombuf{$crsid}) eq 'ok') {
 3671: 	    delete $courselogs{$crsid};
 3672:         } else {
 3673:             &logthis('Failed to flush log buffer for '.$crsid);
 3674:             if (length($courselogs{$crsid})>40000) {
 3675:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3676:                         " exceeded maximum size, deleting.</font>");
 3677:                delete $courselogs{$crsid};
 3678:             }
 3679:         }
 3680:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3681:             'description' => $coursedescrbuf{$crsid},
 3682:             'inst_code'    => $courseinstcodebuf{$crsid},
 3683:             'type'        => $coursetypebuf{$crsid},
 3684:             'owner'       => $courseownerbuf{$crsid},
 3685:         };
 3686:     }
 3687: #
 3688: # Write course id database (reverse lookup) to homeserver of courses 
 3689: # Is used in pickcourse
 3690: #
 3691:     foreach my $crs_home (keys(%courseidbuffer)) {
 3692:         my $response = &courseidput(&host_domain($crs_home),
 3693:                                     $courseidbuffer{$crs_home},
 3694:                                     $crs_home,'timeonly');
 3695:     }
 3696: #
 3697: # File accesses
 3698: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3699: #
 3700:     foreach my $entry (keys(%accesshash)) {
 3701:         if ($entry =~ /___count$/) {
 3702:             my ($dom,$name);
 3703:             ($dom,$name,undef)=
 3704: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3705:             if (! defined($dom) || $dom eq '' || 
 3706:                 ! defined($name) || $name eq '') {
 3707:                 my $cid = $env{'request.course.id'};
 3708:                 $dom  = $env{'request.'.$cid.'.domain'};
 3709:                 $name = $env{'request.'.$cid.'.num'};
 3710:             }
 3711:             my $value = $accesshash{$entry};
 3712:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3713:             my %temphash=($url => $value);
 3714:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3715:             if ($result eq 'ok') {
 3716:                 delete $accesshash{$entry};
 3717:             }
 3718:         } else {
 3719:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3720:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3721:             my %temphash=($entry => $accesshash{$entry});
 3722:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3723:                 delete $accesshash{$entry};
 3724:             }
 3725:         }
 3726:     }
 3727: #
 3728: # Roles
 3729: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3730: #
 3731:     foreach my $entry (keys(%userrolehash)) {
 3732:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3733: 	    split(/\:/,$entry);
 3734:         if (&Apache::lonnet::put('nohist_userroles',
 3735:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3736:                 $rudom,$runame) eq 'ok') {
 3737: 	    delete $userrolehash{$entry};
 3738:         }
 3739:     }
 3740: #
 3741: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3742: #
 3743:     my %domrolebuffer = ();
 3744:     foreach my $entry (keys(%domainrolehash)) {
 3745:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3746:         if ($domrolebuffer{$rudom}) {
 3747:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3748:                       '='.&escape($domainrolehash{$entry});
 3749:         } else {
 3750:             $domrolebuffer{$rudom}.=&escape($entry).
 3751:                       '='.&escape($domainrolehash{$entry});
 3752:         }
 3753:         delete $domainrolehash{$entry};
 3754:     }
 3755:     foreach my $dom (keys(%domrolebuffer)) {
 3756: 	my %servers = &get_servers($dom,'library');
 3757: 	foreach my $tryserver (keys(%servers)) {
 3758: 	    unless (&reply('domroleput:'.$dom.':'.
 3759: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3760: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3761: 	    }
 3762:         }
 3763:     }
 3764:     $dumpcount++;
 3765: }
 3766: 
 3767: sub courselog {
 3768:     my $what=shift;
 3769:     $what=time.':'.$what;
 3770:     unless ($env{'request.course.id'}) { return ''; }
 3771:     $coursedombuf{$env{'request.course.id'}}=
 3772:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3773:     $coursenumbuf{$env{'request.course.id'}}=
 3774:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3775:     $coursehombuf{$env{'request.course.id'}}=
 3776:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3777:     $coursedescrbuf{$env{'request.course.id'}}=
 3778:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3779:     $courseinstcodebuf{$env{'request.course.id'}}=
 3780:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3781:     $courseownerbuf{$env{'request.course.id'}}=
 3782:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3783:     $coursetypebuf{$env{'request.course.id'}}=
 3784:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3785:     if (defined $courselogs{$env{'request.course.id'}}) {
 3786: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3787:     } else {
 3788: 	$courselogs{$env{'request.course.id'}}.=$what;
 3789:     }
 3790:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3791: 	&flushcourselogs();
 3792:     }
 3793: }
 3794: 
 3795: sub courseacclog {
 3796:     my $fnsymb=shift;
 3797:     unless ($env{'request.course.id'}) { return ''; }
 3798:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3799:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3800:         $what.=':POST';
 3801:         # FIXME: Probably ought to escape things....
 3802: 	foreach my $key (keys(%env)) {
 3803:             if ($key=~/^form\.(.*)/) {
 3804:                 my $formitem = $1;
 3805:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3806:                     $what.=':'.$formitem.'='.$env{$key};
 3807:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3808:                     $what.=':'.$formitem.'='.$env{$key};
 3809:                 }
 3810:             }
 3811:         }
 3812:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3813:         # FIXME: We should not be depending on a form parameter that someone
 3814:         # editing lonsearchcat.pm might change in the future.
 3815:         if ($env{'form.phase'} eq 'course_search') {
 3816:             $what.= ':POST';
 3817:             # FIXME: Probably ought to escape things....
 3818:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3819:                                  'crsdiscuss') {
 3820:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3821:             }
 3822:         }
 3823:     }
 3824:     &courselog($what);
 3825: }
 3826: 
 3827: sub countacc {
 3828:     my $url=&declutter(shift);
 3829:     return if (! defined($url) || $url eq '');
 3830:     unless ($env{'request.course.id'}) { return ''; }
 3831: #
 3832: # Mark that this url was used in this course
 3833: #
 3834:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3835: #
 3836: # Increase the access count for this resource in this child process
 3837: #
 3838:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3839:     $accesshash{$key}++;
 3840: }
 3841: 
 3842: sub linklog {
 3843:     my ($from,$to)=@_;
 3844:     $from=&declutter($from);
 3845:     $to=&declutter($to);
 3846:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3847:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3848: }
 3849: 
 3850: sub statslog {
 3851:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3852:     if ($users<2) { return; }
 3853:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3854:             'course'       => $env{'request.course.id'},
 3855:             'sections'     => '"all"',
 3856:             'num_students' => $users,
 3857:             'part'         => $part,
 3858:             'symb'         => $symb,
 3859:             'mean_tries'   => $av_attempts,
 3860:             'deg_of_diff'  => $degdiff});
 3861:     foreach my $key (keys(%dynstore)) {
 3862:         $accesshash{$key}=$dynstore{$key};
 3863:     }
 3864: }
 3865:   
 3866: sub userrolelog {
 3867:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3868:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3869:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3870:        $userrolehash
 3871:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3872:                     =$tend.':'.$tstart;
 3873:     }
 3874:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3875:        $userrolehash
 3876:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3877:                     =$tend.':'.$tstart;
 3878:     }
 3879:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3880:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3881:        $domainrolehash
 3882:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3883:                     = $tend.':'.$tstart;
 3884:     }
 3885: }
 3886: 
 3887: sub courserolelog {
 3888:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3889:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3890:         my $cdom = $1;
 3891:         my $cnum = $2;
 3892:         my $sec = $3;
 3893:         my $namespace = 'rolelog';
 3894:         my %storehash = (
 3895:                            role    => $trole,
 3896:                            start   => $tstart,
 3897:                            end     => $tend,
 3898:                            selfenroll => $selfenroll,
 3899:                            context    => $context,
 3900:                         );
 3901:         if ($trole eq 'gr') {
 3902:             $namespace = 'groupslog';
 3903:             $storehash{'group'} = $sec;
 3904:         } else {
 3905:             $storehash{'section'} = $sec;
 3906:         }
 3907:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3908:                    $domain,$cnum,$cdom);
 3909:         if (($trole ne 'st') || ($sec ne '')) {
 3910:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3911:         }
 3912:     }
 3913:     return;
 3914: }
 3915: 
 3916: sub domainrolelog {
 3917:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3918:     if ($area =~ m{^/($match_domain)/$}) {
 3919:         my $cdom = $1;
 3920:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3921:         my $namespace = 'rolelog';
 3922:         my %storehash = (
 3923:                            role    => $trole,
 3924:                            start   => $tstart,
 3925:                            end     => $tend,
 3926:                            context => $context,
 3927:                         );
 3928:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3929:                    $domain,$domconfiguser,$cdom);
 3930:     }
 3931:     return;
 3932: 
 3933: }
 3934: 
 3935: sub coauthorrolelog {
 3936:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3937:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3938:         my $audom = $1;
 3939:         my $auname = $2;
 3940:         my $namespace = 'rolelog';
 3941:         my %storehash = (
 3942:                            role    => $trole,
 3943:                            start   => $tstart,
 3944:                            end     => $tend,
 3945:                            context => $context,
 3946:                         );
 3947:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3948:                    $domain,$auname,$audom);
 3949:     }
 3950:     return;
 3951: }
 3952: 
 3953: sub get_course_adv_roles {
 3954:     my ($cid,$codes) = @_;
 3955:     $cid=$env{'request.course.id'} unless (defined($cid));
 3956:     my %coursehash=&coursedescription($cid);
 3957:     my $crstype = &Apache::loncommon::course_type($cid);
 3958:     my %nothide=();
 3959:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3960:         if ($user !~ /:/) {
 3961: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3962:         } else {
 3963:             $nothide{$user}=1;
 3964:         }
 3965:     }
 3966:     my @possdoms = ($coursehash{'domain'});
 3967:     if ($coursehash{'checkforpriv'}) {
 3968:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3969:     }
 3970:     my %returnhash=();
 3971:     my %dumphash=
 3972:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3973:     my $now=time;
 3974:     my %privileged;
 3975:     foreach my $entry (keys(%dumphash)) {
 3976: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3977:         if (($tstart) && ($tstart<0)) { next; }
 3978:         if (($tend) && ($tend<$now)) { next; }
 3979:         if (($tstart) && ($now<$tstart)) { next; }
 3980:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3981: 	if ($username eq '' || $domain eq '') { next; }
 3982:         if ((&privileged($username,$domain,\@possdoms)) &&
 3983:             (!$nothide{$username.':'.$domain})) { next; }
 3984: 	if ($role eq 'cr') { next; }
 3985:         if ($codes) {
 3986:             if ($section) { $role .= ':'.$section; }
 3987:             if ($returnhash{$role}) {
 3988:                 $returnhash{$role}.=','.$username.':'.$domain;
 3989:             } else {
 3990:                 $returnhash{$role}=$username.':'.$domain;
 3991:             }
 3992:         } else {
 3993:             my $key=&plaintext($role,$crstype);
 3994:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3995:             if ($returnhash{$key}) {
 3996: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3997:             } else {
 3998:                 $returnhash{$key}=$username.':'.$domain;
 3999:             }
 4000:         }
 4001:     }
 4002:     return %returnhash;
 4003: }
 4004: 
 4005: sub get_my_roles {
 4006:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4007:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4008:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4009:     my (%dumphash,%nothide);
 4010:     if ($context eq 'userroles') {
 4011:         %dumphash = &dump('roles',$udom,$uname);
 4012:     } else {
 4013:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4014:         if ($hidepriv) {
 4015:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4016:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4017:                 if ($user !~ /:/) {
 4018:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4019:                 } else {
 4020:                     $nothide{$user} = 1;
 4021:                 }
 4022:             }
 4023:         }
 4024:     }
 4025:     my %returnhash=();
 4026:     my $now=time;
 4027:     my %privileged;
 4028:     foreach my $entry (keys(%dumphash)) {
 4029:         my ($role,$tend,$tstart);
 4030:         if ($context eq 'userroles') {
 4031:             next if ($entry =~ /^rolesdef/);
 4032: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4033:         } else {
 4034:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4035:         }
 4036:         if (($tstart) && ($tstart<0)) { next; }
 4037:         my $status = 'active';
 4038:         if (($tend) && ($tend<=$now)) {
 4039:             $status = 'previous';
 4040:         } 
 4041:         if (($tstart) && ($now<$tstart)) {
 4042:             $status = 'future';
 4043:         }
 4044:         if (ref($types) eq 'ARRAY') {
 4045:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4046:                 next;
 4047:             } 
 4048:         } else {
 4049:             if ($status ne 'active') {
 4050:                 next;
 4051:             }
 4052:         }
 4053:         my ($rolecode,$username,$domain,$section,$area);
 4054:         if ($context eq 'userroles') {
 4055:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4056:             (undef,$domain,$username,$section) = split(/\//,$area);
 4057:         } else {
 4058:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4059:         }
 4060:         if (ref($roledoms) eq 'ARRAY') {
 4061:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4062:                 next;
 4063:             }
 4064:         }
 4065:         if (ref($roles) eq 'ARRAY') {
 4066:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4067:                 if ($role =~ /^cr\//) {
 4068:                     if (!grep(/^cr$/,@{$roles})) {
 4069:                         next;
 4070:                     }
 4071:                 } elsif ($role =~ /^gr\//) {
 4072:                     if (!grep(/^gr$/,@{$roles})) {
 4073:                         next;
 4074:                     }
 4075:                 } else {
 4076:                     next;
 4077:                 }
 4078:             }
 4079:         }
 4080:         if ($hidepriv) {
 4081:             my @privroles = ('dc','su');
 4082:             if ($context eq 'userroles') {
 4083:                 next if (grep(/^\Q$role\E$/,@privroles));
 4084:             } else {
 4085:                 my $possdoms = [$domain];
 4086:                 if (ref($roledoms) eq 'ARRAY') {
 4087:                    push(@{$possdoms},@{$roledoms}); 
 4088:                 }
 4089:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4090:                     if (!$nothide{$username.':'.$domain}) {
 4091:                         next;
 4092:                     }
 4093:                 }
 4094:             }
 4095:         }
 4096:         if ($withsec) {
 4097:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4098:                 $tstart.':'.$tend;
 4099:         } else {
 4100:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4101:         }
 4102:     }
 4103:     return %returnhash;
 4104: }
 4105: 
 4106: # ----------------------------------------------------- Frontpage Announcements
 4107: #
 4108: #
 4109: 
 4110: sub postannounce {
 4111:     my ($server,$text)=@_;
 4112:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4113:     unless ($text=~/\w/) { $text=''; }
 4114:     return &reply('setannounce:'.&escape($text),$server);
 4115: }
 4116: 
 4117: sub getannounce {
 4118: 
 4119:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4120: 	my $announcement='';
 4121: 	while (my $line = <$fh>) { $announcement .= $line; }
 4122: 	close($fh);
 4123: 	if ($announcement=~/\w/) { 
 4124: 	    return 
 4125:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4126:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4127: 	} else {
 4128: 	    return '';
 4129: 	}
 4130:     } else {
 4131: 	return '';
 4132:     }
 4133: }
 4134: 
 4135: # ---------------------------------------------------------- Course ID routines
 4136: # Deal with domain's nohist_courseid.db files
 4137: #
 4138: 
 4139: sub courseidput {
 4140:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4141:     return unless (ref($storehash) eq 'HASH');
 4142:     my $outcome;
 4143:     if ($caller eq 'timeonly') {
 4144:         my $cids = '';
 4145:         foreach my $item (keys(%$storehash)) {
 4146:             $cids.=&escape($item).'&';
 4147:         }
 4148:         $cids=~s/\&$//;
 4149:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4150:                           $coursehome);       
 4151:     } else {
 4152:         my $items = '';
 4153:         foreach my $item (keys(%$storehash)) {
 4154:             $items.= &escape($item).'='.
 4155:                      &freeze_escape($$storehash{$item}).'&';
 4156:         }
 4157:         $items=~s/\&$//;
 4158:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4159:                           $coursehome);
 4160:     }
 4161:     if ($outcome eq 'unknown_cmd') {
 4162:         my $what;
 4163:         foreach my $cid (keys(%$storehash)) {
 4164:             $what .= &escape($cid).'=';
 4165:             foreach my $item ('description','inst_code','owner','type') {
 4166:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4167:             }
 4168:             $what =~ s/\:$/&/;
 4169:         }
 4170:         $what =~ s/\&$//;  
 4171:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4172:     } else {
 4173:         return $outcome;
 4174:     }
 4175: }
 4176: 
 4177: sub courseiddump {
 4178:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4179:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4180:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4181:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4182:     my $as_hash = 1;
 4183:     my %returnhash;
 4184:     if (!$domfilter) { $domfilter=''; }
 4185:     my %libserv = &all_library();
 4186:     foreach my $tryserver (keys(%libserv)) {
 4187:         if ( (  $hostidflag == 1 
 4188: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4189: 	     || (!defined($hostidflag)) ) {
 4190: 
 4191: 	    if (($domfilter eq '') ||
 4192: 		(&host_domain($tryserver) eq $domfilter)) {
 4193:                 my $rep;
 4194:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4195:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4196:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4197:                                 &escape($descfilter), &escape($instcodefilter), 
 4198:                                 &escape($ownerfilter), &escape($coursefilter),
 4199:                                 &escape($typefilter), &escape($regexp_ok), 
 4200:                                 $as_hash, &escape($selfenrollonly), 
 4201:                                 &escape($catfilter), $showhidden, $caller, 
 4202:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4203:                                 &escape($createdbefore), &escape($createdafter), 
 4204:                                 &escape($creationcontext), $domcloner)));
 4205:                 } else {
 4206:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4207:                              $sincefilter.':'.&escape($descfilter).':'.
 4208:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4209:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4210:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4211:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4212:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4213:                              &escape($cc_clone).':'.$cloneonly.':'.
 4214:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4215:                              &escape($creationcontext).':'.$domcloner,
 4216:                              $tryserver);
 4217:                 }
 4218:                      
 4219:                 my @pairs=split(/\&/,$rep);
 4220:                 foreach my $item (@pairs) {
 4221:                     my ($key,$value)=split(/\=/,$item,2);
 4222:                     $key = &unescape($key);
 4223:                     next if ($key =~ /^error: 2 /);
 4224:                     my $result = &thaw_unescape($value);
 4225:                     if (ref($result) eq 'HASH') {
 4226:                         $returnhash{$key}=$result;
 4227:                     } else {
 4228:                         my @responses = split(/:/,$value);
 4229:                         my @items = ('description','inst_code','owner','type');
 4230:                         for (my $i=0; $i<@responses; $i++) {
 4231:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4232:                         }
 4233:                     }
 4234:                 }
 4235:             }
 4236:         }
 4237:     }
 4238:     return %returnhash;
 4239: }
 4240: 
 4241: sub courselastaccess {
 4242:     my ($cdom,$cnum,$hostidref) = @_;
 4243:     my %returnhash;
 4244:     if ($cdom && $cnum) {
 4245:         my $chome = &homeserver($cnum,$cdom);
 4246:         if ($chome ne 'no_host') {
 4247:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4248:             &extract_lastaccess(\%returnhash,$rep);
 4249:         }
 4250:     } else {
 4251:         if (!$cdom) { $cdom=''; }
 4252:         my %libserv = &all_library();
 4253:         foreach my $tryserver (keys(%libserv)) {
 4254:             if (ref($hostidref) eq 'ARRAY') {
 4255:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4256:             } 
 4257:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4258:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4259:                 &extract_lastaccess(\%returnhash,$rep);
 4260:             }
 4261:         }
 4262:     }
 4263:     return %returnhash;
 4264: }
 4265: 
 4266: sub extract_lastaccess {
 4267:     my ($returnhash,$rep) = @_;
 4268:     if (ref($returnhash) eq 'HASH') {
 4269:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4270:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4271:                  $rep eq '') {
 4272:             my @pairs=split(/\&/,$rep);
 4273:             foreach my $item (@pairs) {
 4274:                 my ($key,$value)=split(/\=/,$item,2);
 4275:                 $key = &unescape($key);
 4276:                 next if ($key =~ /^error: 2 /);
 4277:                 $returnhash->{$key} = &thaw_unescape($value);
 4278:             }
 4279:         }
 4280:     }
 4281:     return;
 4282: }
 4283: 
 4284: # ---------------------------------------------------------- DC e-mail
 4285: 
 4286: sub dcmailput {
 4287:     my ($domain,$msgid,$message,$server)=@_;
 4288:     my $status = &Apache::lonnet::critical(
 4289:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4290:        &escape($message),$server);
 4291:     return $status;
 4292: }
 4293: 
 4294: sub dcmaildump {
 4295:     my ($dom,$startdate,$enddate,$senders) = @_;
 4296:     my %returnhash=();
 4297: 
 4298:     if (defined(&domain($dom,'primary'))) {
 4299:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4300:                                                          &escape($enddate).':';
 4301: 	my @esc_senders=map { &escape($_)} @$senders;
 4302: 	$cmd.=&escape(join('&',@esc_senders));
 4303: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4304:             my ($key,$value) = split(/\=/,$line,2);
 4305:             if (($key) && ($value)) {
 4306:                 $returnhash{&unescape($key)} = &unescape($value);
 4307:             }
 4308:         }
 4309:     }
 4310:     return %returnhash;
 4311: }
 4312: # ---------------------------------------------------------- Domain roles
 4313: 
 4314: sub get_domain_roles {
 4315:     my ($dom,$roles,$startdate,$enddate)=@_;
 4316:     if ((!defined($startdate)) || ($startdate eq '')) {
 4317:         $startdate = '.';
 4318:     }
 4319:     if ((!defined($enddate)) || ($enddate eq '')) {
 4320:         $enddate = '.';
 4321:     }
 4322:     my $rolelist;
 4323:     if (ref($roles) eq 'ARRAY') {
 4324:         $rolelist = join('&',@{$roles});
 4325:     }
 4326:     my %personnel = ();
 4327: 
 4328:     my %servers = &get_servers($dom,'library');
 4329:     foreach my $tryserver (keys(%servers)) {
 4330: 	%{$personnel{$tryserver}}=();
 4331: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4332: 					    &escape($startdate).':'.
 4333: 					    &escape($enddate).':'.
 4334: 					    &escape($rolelist), $tryserver))) {
 4335: 	    my ($key,$value) = split(/\=/,$line,2);
 4336: 	    if (($key) && ($value)) {
 4337: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4338: 	    }
 4339: 	}
 4340:     }
 4341:     return %personnel;
 4342: }
 4343: 
 4344: # ----------------------------------------------------------- Interval timing 
 4345: 
 4346: {
 4347: # Caches needed for speedup of navmaps
 4348: # We don't want to cache this for very long at all (5 seconds at most)
 4349: # 
 4350: # The user for whom we cache
 4351: my $cachedkey='';
 4352: # The cached times for this user
 4353: my %cachedtimes=();
 4354: # When this was last done
 4355: my $cachedtime=();
 4356: 
 4357: sub load_all_first_access {
 4358:     my ($uname,$udom)=@_;
 4359:     if (($cachedkey eq $uname.':'.$udom) &&
 4360:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4361:         return;
 4362:     }
 4363:     $cachedtime=time;
 4364:     $cachedkey=$uname.':'.$udom;
 4365:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4366: }
 4367: 
 4368: sub get_first_access {
 4369:     my ($type,$argsymb,$argmap)=@_;
 4370:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4371:     if ($argsymb) { $symb=$argsymb; }
 4372:     my ($map,$id,$res)=&decode_symb($symb);
 4373:     if ($argmap) { $map = $argmap; }
 4374:     if ($type eq 'course') {
 4375: 	$res='course';
 4376:     } elsif ($type eq 'map') {
 4377: 	$res=&symbread($map);
 4378:     } else {
 4379: 	$res=$symb;
 4380:     }
 4381:     &load_all_first_access($uname,$udom);
 4382:     return $cachedtimes{"$courseid\0$res"};
 4383: }
 4384: 
 4385: sub set_first_access {
 4386:     my ($type,$interval)=@_;
 4387:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4388:     my ($map,$id,$res)=&decode_symb($symb);
 4389:     if ($type eq 'course') {
 4390: 	$res='course';
 4391:     } elsif ($type eq 'map') {
 4392: 	$res=&symbread($map);
 4393:     } else {
 4394: 	$res=$symb;
 4395:     }
 4396:     $cachedkey='';
 4397:     my $firstaccess=&get_first_access($type,$symb,$map);
 4398:     if (!$firstaccess) {
 4399:         my $start = time;
 4400: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4401:                           $udom,$uname);
 4402:         if ($putres eq 'ok') {
 4403:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4404:                  $udom,$uname); 
 4405:             &appenv(
 4406:                      {
 4407:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4408:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4409:                      }
 4410:                   );
 4411:         }
 4412:         return $putres;
 4413:     }
 4414:     return 'already_set';
 4415: }
 4416: }
 4417: # --------------------------------------------- Set Expire Date for Spreadsheet
 4418: 
 4419: sub expirespread {
 4420:     my ($uname,$udom,$stype,$usymb)=@_;
 4421:     my $cid=$env{'request.course.id'}; 
 4422:     if ($cid) {
 4423:        my $now=time;
 4424:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4425:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4426:                             $env{'course.'.$cid.'.num'}.
 4427: 	        	    ':nohist_expirationdates:'.
 4428:                             &escape($key).'='.$now,
 4429:                             $env{'course.'.$cid.'.home'})
 4430:     }
 4431:     return 'ok';
 4432: }
 4433: 
 4434: # ----------------------------------------------------- Devalidate Spreadsheets
 4435: 
 4436: sub devalidate {
 4437:     my ($symb,$uname,$udom)=@_;
 4438:     my $cid=$env{'request.course.id'}; 
 4439:     if ($cid) {
 4440:         # delete the stored spreadsheets for
 4441:         # - the student level sheet of this user in course's homespace
 4442:         # - the assessment level sheet for this resource 
 4443:         #   for this user in user's homespace
 4444: 	# - current conditional state info
 4445: 	my $key=$uname.':'.$udom.':';
 4446:         my $status=
 4447: 	    &del('nohist_calculatedsheets',
 4448: 		 [$key.'studentcalc:'],
 4449: 		 $env{'course.'.$cid.'.domain'},
 4450: 		 $env{'course.'.$cid.'.num'})
 4451: 		.' '.
 4452: 	    &del('nohist_calculatedsheets_'.$cid,
 4453: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4454:         unless ($status eq 'ok ok') {
 4455:            &logthis('Could not devalidate spreadsheet '.
 4456:                     $uname.' at '.$udom.' for '.
 4457: 		    $symb.': '.$status);
 4458:         }
 4459: 	&delenv('user.state.'.$cid);
 4460:     }
 4461: }
 4462: 
 4463: sub get_scalar {
 4464:     my ($string,$end) = @_;
 4465:     my $value;
 4466:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4467: 	$value = $1;
 4468:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4469: 	$value = $1;
 4470:     }
 4471:     return &unescape($value);
 4472: }
 4473: 
 4474: sub array2str {
 4475:   my (@array) = @_;
 4476:   my $result=&arrayref2str(\@array);
 4477:   $result=~s/^__ARRAY_REF__//;
 4478:   $result=~s/__END_ARRAY_REF__$//;
 4479:   return $result;
 4480: }
 4481: 
 4482: sub arrayref2str {
 4483:   my ($arrayref) = @_;
 4484:   my $result='__ARRAY_REF__';
 4485:   foreach my $elem (@$arrayref) {
 4486:     if(ref($elem) eq 'ARRAY') {
 4487:       $result.=&arrayref2str($elem).'&';
 4488:     } elsif(ref($elem) eq 'HASH') {
 4489:       $result.=&hashref2str($elem).'&';
 4490:     } elsif(ref($elem)) {
 4491:       #print("Got a ref of ".(ref($elem))." skipping.");
 4492:     } else {
 4493:       $result.=&escape($elem).'&';
 4494:     }
 4495:   }
 4496:   $result=~s/\&$//;
 4497:   $result .= '__END_ARRAY_REF__';
 4498:   return $result;
 4499: }
 4500: 
 4501: sub hash2str {
 4502:   my (%hash) = @_;
 4503:   my $result=&hashref2str(\%hash);
 4504:   $result=~s/^__HASH_REF__//;
 4505:   $result=~s/__END_HASH_REF__$//;
 4506:   return $result;
 4507: }
 4508: 
 4509: sub hashref2str {
 4510:   my ($hashref)=@_;
 4511:   my $result='__HASH_REF__';
 4512:   foreach my $key (sort(keys(%$hashref))) {
 4513:     if (ref($key) eq 'ARRAY') {
 4514:       $result.=&arrayref2str($key).'=';
 4515:     } elsif (ref($key) eq 'HASH') {
 4516:       $result.=&hashref2str($key).'=';
 4517:     } elsif (ref($key)) {
 4518:       $result.='=';
 4519:       #print("Got a ref of ".(ref($key))." skipping.");
 4520:     } else {
 4521: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4522:     }
 4523: 
 4524:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4525:       $result.=&arrayref2str($hashref->{$key}).'&';
 4526:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4527:       $result.=&hashref2str($hashref->{$key}).'&';
 4528:     } elsif(ref($hashref->{$key})) {
 4529:        $result.='&';
 4530:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4531:     } else {
 4532:       $result.=&escape($hashref->{$key}).'&';
 4533:     }
 4534:   }
 4535:   $result=~s/\&$//;
 4536:   $result .= '__END_HASH_REF__';
 4537:   return $result;
 4538: }
 4539: 
 4540: sub str2hash {
 4541:     my ($string)=@_;
 4542:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4543:     return %$hash;
 4544: }
 4545: 
 4546: sub str2hashref {
 4547:   my ($string) = @_;
 4548: 
 4549:   my %hash;
 4550: 
 4551:   if($string !~ /^__HASH_REF__/) {
 4552:       if (! ($string eq '' || !defined($string))) {
 4553: 	  $hash{'error'}='Not hash reference';
 4554:       }
 4555:       return (\%hash, $string);
 4556:   }
 4557: 
 4558:   $string =~ s/^__HASH_REF__//;
 4559: 
 4560:   while($string !~ /^__END_HASH_REF__/) {
 4561:       #key
 4562:       my $key='';
 4563:       if($string =~ /^__HASH_REF__/) {
 4564:           ($key, $string)=&str2hashref($string);
 4565:           if(defined($key->{'error'})) {
 4566:               $hash{'error'}='Bad data';
 4567:               return (\%hash, $string);
 4568:           }
 4569:       } elsif($string =~ /^__ARRAY_REF__/) {
 4570:           ($key, $string)=&str2arrayref($string);
 4571:           if($key->[0] eq 'Array reference error') {
 4572:               $hash{'error'}='Bad data';
 4573:               return (\%hash, $string);
 4574:           }
 4575:       } else {
 4576:           $string =~ s/^(.*?)=//;
 4577: 	  $key=&unescape($1);
 4578:       }
 4579:       $string =~ s/^=//;
 4580: 
 4581:       #value
 4582:       my $value='';
 4583:       if($string =~ /^__HASH_REF__/) {
 4584:           ($value, $string)=&str2hashref($string);
 4585:           if(defined($value->{'error'})) {
 4586:               $hash{'error'}='Bad data';
 4587:               return (\%hash, $string);
 4588:           }
 4589:       } elsif($string =~ /^__ARRAY_REF__/) {
 4590:           ($value, $string)=&str2arrayref($string);
 4591:           if($value->[0] eq 'Array reference error') {
 4592:               $hash{'error'}='Bad data';
 4593:               return (\%hash, $string);
 4594:           }
 4595:       } else {
 4596: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4597:       }
 4598:       $string =~ s/^&//;
 4599: 
 4600:       $hash{$key}=$value;
 4601:   }
 4602: 
 4603:   $string =~ s/^__END_HASH_REF__//;
 4604: 
 4605:   return (\%hash, $string);
 4606: }
 4607: 
 4608: sub str2array {
 4609:     my ($string)=@_;
 4610:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4611:     return @$array;
 4612: }
 4613: 
 4614: sub str2arrayref {
 4615:   my ($string) = @_;
 4616:   my @array;
 4617: 
 4618:   if($string !~ /^__ARRAY_REF__/) {
 4619:       if (! ($string eq '' || !defined($string))) {
 4620: 	  $array[0]='Array reference error';
 4621:       }
 4622:       return (\@array, $string);
 4623:   }
 4624: 
 4625:   $string =~ s/^__ARRAY_REF__//;
 4626: 
 4627:   while($string !~ /^__END_ARRAY_REF__/) {
 4628:       my $value='';
 4629:       if($string =~ /^__HASH_REF__/) {
 4630:           ($value, $string)=&str2hashref($string);
 4631:           if(defined($value->{'error'})) {
 4632:               $array[0] ='Array reference error';
 4633:               return (\@array, $string);
 4634:           }
 4635:       } elsif($string =~ /^__ARRAY_REF__/) {
 4636:           ($value, $string)=&str2arrayref($string);
 4637:           if($value->[0] eq 'Array reference error') {
 4638:               $array[0] ='Array reference error';
 4639:               return (\@array, $string);
 4640:           }
 4641:       } else {
 4642: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4643:       }
 4644:       $string =~ s/^&//;
 4645: 
 4646:       push(@array, $value);
 4647:   }
 4648: 
 4649:   $string =~ s/^__END_ARRAY_REF__//;
 4650: 
 4651:   return (\@array, $string);
 4652: }
 4653: 
 4654: # -------------------------------------------------------------------Temp Store
 4655: 
 4656: sub tmpreset {
 4657:   my ($symb,$namespace,$domain,$stuname) = @_;
 4658:   if (!$symb) {
 4659:     $symb=&symbread();
 4660:     if (!$symb) { $symb= $env{'request.url'}; }
 4661:   }
 4662:   $symb=escape($symb);
 4663: 
 4664:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4665:   $namespace=~s/\//\_/g;
 4666:   $namespace=~s/\W//g;
 4667: 
 4668:   if (!$domain) { $domain=$env{'user.domain'}; }
 4669:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4670:   if ($domain eq 'public' && $stuname eq 'public') {
 4671:       $stuname=$ENV{'REMOTE_ADDR'};
 4672:   }
 4673:   my $path=LONCAPA::tempdir();
 4674:   my %hash;
 4675:   if (tie(%hash,'GDBM_File',
 4676: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4677: 	  &GDBM_WRCREAT(),0640)) {
 4678:     foreach my $key (keys(%hash)) {
 4679:       if ($key=~ /:$symb/) {
 4680: 	delete($hash{$key});
 4681:       }
 4682:     }
 4683:   }
 4684: }
 4685: 
 4686: sub tmpstore {
 4687:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4688: 
 4689:   if (!$symb) {
 4690:     $symb=&symbread();
 4691:     if (!$symb) { $symb= $env{'request.url'}; }
 4692:   }
 4693:   $symb=escape($symb);
 4694: 
 4695:   if (!$namespace) {
 4696:     # I don't think we would ever want to store this for a course.
 4697:     # it seems this will only be used if we don't have a course.
 4698:     #$namespace=$env{'request.course.id'};
 4699:     #if (!$namespace) {
 4700:       $namespace=$env{'request.state'};
 4701:     #}
 4702:   }
 4703:   $namespace=~s/\//\_/g;
 4704:   $namespace=~s/\W//g;
 4705:   if (!$domain) { $domain=$env{'user.domain'}; }
 4706:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4707:   if ($domain eq 'public' && $stuname eq 'public') {
 4708:       $stuname=$ENV{'REMOTE_ADDR'};
 4709:   }
 4710:   my $now=time;
 4711:   my %hash;
 4712:   my $path=LONCAPA::tempdir();
 4713:   if (tie(%hash,'GDBM_File',
 4714: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4715: 	  &GDBM_WRCREAT(),0640)) {
 4716:     $hash{"version:$symb"}++;
 4717:     my $version=$hash{"version:$symb"};
 4718:     my $allkeys=''; 
 4719:     foreach my $key (keys(%$storehash)) {
 4720:       $allkeys.=$key.':';
 4721:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4722:     }
 4723:     $hash{"$version:$symb:timestamp"}=$now;
 4724:     $allkeys.='timestamp';
 4725:     $hash{"$version:keys:$symb"}=$allkeys;
 4726:     if (untie(%hash)) {
 4727:       return 'ok';
 4728:     } else {
 4729:       return "error:$!";
 4730:     }
 4731:   } else {
 4732:     return "error:$!";
 4733:   }
 4734: }
 4735: 
 4736: # -----------------------------------------------------------------Temp Restore
 4737: 
 4738: sub tmprestore {
 4739:   my ($symb,$namespace,$domain,$stuname) = @_;
 4740: 
 4741:   if (!$symb) {
 4742:     $symb=&symbread();
 4743:     if (!$symb) { $symb= $env{'request.url'}; }
 4744:   }
 4745:   $symb=escape($symb);
 4746: 
 4747:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4748: 
 4749:   if (!$domain) { $domain=$env{'user.domain'}; }
 4750:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4751:   if ($domain eq 'public' && $stuname eq 'public') {
 4752:       $stuname=$ENV{'REMOTE_ADDR'};
 4753:   }
 4754:   my %returnhash;
 4755:   $namespace=~s/\//\_/g;
 4756:   $namespace=~s/\W//g;
 4757:   my %hash;
 4758:   my $path=LONCAPA::tempdir();
 4759:   if (tie(%hash,'GDBM_File',
 4760: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4761: 	  &GDBM_READER(),0640)) {
 4762:     my $version=$hash{"version:$symb"};
 4763:     $returnhash{'version'}=$version;
 4764:     my $scope;
 4765:     for ($scope=1;$scope<=$version;$scope++) {
 4766:       my $vkeys=$hash{"$scope:keys:$symb"};
 4767:       my @keys=split(/:/,$vkeys);
 4768:       my $key;
 4769:       $returnhash{"$scope:keys"}=$vkeys;
 4770:       foreach $key (@keys) {
 4771: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4772: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4773:       }
 4774:     }
 4775:     if (!(untie(%hash))) {
 4776:       return "error:$!";
 4777:     }
 4778:   } else {
 4779:     return "error:$!";
 4780:   }
 4781:   return %returnhash;
 4782: }
 4783: 
 4784: # ----------------------------------------------------------------------- Store
 4785: 
 4786: sub store {
 4787:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4788:     my $home='';
 4789: 
 4790:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4791: 
 4792:     $symb=&symbclean($symb);
 4793:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4794: 
 4795:     if (!$domain) { $domain=$env{'user.domain'}; }
 4796:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4797: 
 4798:     &devalidate($symb,$stuname,$domain);
 4799: 
 4800:     $symb=escape($symb);
 4801:     if (!$namespace) { 
 4802:        unless ($namespace=$env{'request.course.id'}) { 
 4803:           return ''; 
 4804:        } 
 4805:     }
 4806:     if (!$home) { $home=$env{'user.home'}; }
 4807: 
 4808:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4809:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4810: 
 4811:     my $namevalue='';
 4812:     foreach my $key (keys(%$storehash)) {
 4813:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4814:     }
 4815:     $namevalue=~s/\&$//;
 4816:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4817:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4818: }
 4819: 
 4820: # -------------------------------------------------------------- Critical Store
 4821: 
 4822: sub cstore {
 4823:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4824:     my $home='';
 4825: 
 4826:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4827: 
 4828:     $symb=&symbclean($symb);
 4829:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4830: 
 4831:     if (!$domain) { $domain=$env{'user.domain'}; }
 4832:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4833: 
 4834:     &devalidate($symb,$stuname,$domain);
 4835: 
 4836:     $symb=escape($symb);
 4837:     if (!$namespace) { 
 4838:        unless ($namespace=$env{'request.course.id'}) { 
 4839:           return ''; 
 4840:        } 
 4841:     }
 4842:     if (!$home) { $home=$env{'user.home'}; }
 4843: 
 4844:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4845:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4846: 
 4847:     my $namevalue='';
 4848:     foreach my $key (keys(%$storehash)) {
 4849:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4850:     }
 4851:     $namevalue=~s/\&$//;
 4852:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4853:     return critical
 4854:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4855: }
 4856: 
 4857: # --------------------------------------------------------------------- Restore
 4858: 
 4859: sub restore {
 4860:     my ($symb,$namespace,$domain,$stuname) = @_;
 4861:     my $home='';
 4862: 
 4863:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4864: 
 4865:     if (!$symb) {
 4866:         return if ($namespace eq 'courserequests');
 4867:         unless ($symb=escape(&symbread())) { return ''; }
 4868:     } else {
 4869:         unless ($namespace eq 'courserequests') {
 4870:             $symb=&escape(&symbclean($symb));
 4871:         }
 4872:     }
 4873:     if (!$namespace) { 
 4874:        unless ($namespace=$env{'request.course.id'}) { 
 4875:           return ''; 
 4876:        } 
 4877:     }
 4878:     if (!$domain) { $domain=$env{'user.domain'}; }
 4879:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4880:     if (!$home) { $home=$env{'user.home'}; }
 4881:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4882: 
 4883:     my %returnhash=();
 4884:     foreach my $line (split(/\&/,$answer)) {
 4885: 	my ($name,$value)=split(/\=/,$line);
 4886:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4887:     }
 4888:     my $version;
 4889:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4890:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4891:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4892:        }
 4893:     }
 4894:     return %returnhash;
 4895: }
 4896: 
 4897: # ---------------------------------------------------------- Course Description
 4898: #
 4899: #  
 4900: 
 4901: sub coursedescription {
 4902:     my ($courseid,$args)=@_;
 4903:     $courseid=~s/^\///;
 4904:     $courseid=~s/\_/\//g;
 4905:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4906:     my $chome=&homeserver($cnum,$cdomain);
 4907:     my $normalid=$cdomain.'_'.$cnum;
 4908:     # need to always cache even if we get errors otherwise we keep 
 4909:     # trying and trying and trying to get the course description.
 4910:     my %envhash=();
 4911:     my %returnhash=();
 4912:     
 4913:     my $expiretime=600;
 4914:     if ($env{'request.course.id'} eq $normalid) {
 4915: 	$expiretime=120;
 4916:     }
 4917: 
 4918:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4919:     if (!$args->{'freshen_cache'}
 4920: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4921: 	foreach my $key (keys(%env)) {
 4922: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4923: 	    my ($setting) = $1;
 4924: 	    $returnhash{$setting} = $env{$key};
 4925: 	}
 4926: 	return %returnhash;
 4927:     }
 4928: 
 4929:     # get the data again
 4930: 
 4931:     if (!$args->{'one_time'}) {
 4932: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4933:     }
 4934: 
 4935:     if ($chome ne 'no_host') {
 4936:        %returnhash=&dump('environment',$cdomain,$cnum);
 4937:        if (!exists($returnhash{'con_lost'})) {
 4938: 	   my $username = $env{'user.name'}; # Defult username
 4939: 	   if(defined $args->{'user'}) {
 4940: 	       $username = $args->{'user'};
 4941: 	   }
 4942:            $returnhash{'home'}= $chome;
 4943: 	   $returnhash{'domain'} = $cdomain;
 4944: 	   $returnhash{'num'} = $cnum;
 4945:            if (!defined($returnhash{'type'})) {
 4946:                $returnhash{'type'} = 'Course';
 4947:            }
 4948:            while (my ($name,$value) = each %returnhash) {
 4949:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4950:            }
 4951:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4952:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4953: 	       $username.'_'.$cdomain.'_'.$cnum;
 4954:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4955:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4956:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4957:        }
 4958:     }
 4959:     if (!$args->{'one_time'}) {
 4960: 	&appenv(\%envhash);
 4961:     }
 4962:     return %returnhash;
 4963: }
 4964: 
 4965: sub update_released_required {
 4966:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4967:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4968:         $cid = $env{'request.course.id'};
 4969:         $cdom = $env{'course.'.$cid.'.domain'};
 4970:         $cnum = $env{'course.'.$cid.'.num'};
 4971:         $chome = $env{'course.'.$cid.'.home'};
 4972:     }
 4973:     if ($needsrelease) {
 4974:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4975:         my $needsupdate;
 4976:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4977:             $needsupdate = 1;
 4978:         } else {
 4979:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4980:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4981:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4982:                 $needsupdate = 1;
 4983:             }
 4984:         }
 4985:         if ($needsupdate) {
 4986:             my %needshash = (
 4987:                              'internal.releaserequired' => $needsrelease,
 4988:                             );
 4989:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4990:             if ($putresult eq 'ok') {
 4991:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4992:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4993:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4994:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4995:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4996:                 }
 4997:             }
 4998:         }
 4999:     }
 5000:     return;
 5001: }
 5002: 
 5003: # -------------------------------------------------See if a user is privileged
 5004: 
 5005: sub privileged {
 5006:     my ($username,$domain,$possdomains,$possroles)=@_;
 5007:     my $now = time;
 5008:     my $roles;
 5009:     if (ref($possroles) eq 'ARRAY') {
 5010:         $roles = $possroles; 
 5011:     } else {
 5012:         $roles = ['dc','su'];
 5013:     }
 5014:     if (ref($possdomains) eq 'ARRAY') {
 5015:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5016:         foreach my $dom (@{$possdomains}) {
 5017:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5018:                 (ref($privileged{$dom}) eq 'HASH')) {
 5019:                 foreach my $role (@{$roles}) {
 5020:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5021:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5022:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5023:                             return 1 unless (($end && $end < $now) ||
 5024:                                              ($start && $start > $now));
 5025:                         }
 5026:                     }
 5027:                 }
 5028:             }
 5029:         }
 5030:     } else {
 5031:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5032:         my $now = time;
 5033: 
 5034:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5035:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5036:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5037:                 return 1 unless ($tend && $tend < $now) 
 5038:                         or ($tstart && $tstart > $now);
 5039:             }
 5040:         }
 5041:     }
 5042:     return 0;
 5043: }
 5044: 
 5045: sub privileged_by_domain {
 5046:     my ($domains,$roles) = @_;
 5047:     my %privileged = ();
 5048:     my $cachetime = 60*60*24;
 5049:     my $now = time;
 5050:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5051:         return %privileged;
 5052:     }
 5053:     foreach my $dom (@{$domains}) {
 5054:         next if (ref($privileged{$dom}) eq 'HASH');
 5055:         my $needroles;
 5056:         foreach my $role (@{$roles}) {
 5057:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5058:             if (defined($cached)) {
 5059:                 if (ref($result) eq 'HASH') {
 5060:                     $privileged{$dom}{$role} = $result;
 5061:                 }
 5062:             } else {
 5063:                 $needroles = 1;
 5064:             }
 5065:         }
 5066:         if ($needroles) {
 5067:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5068:             $privileged{$dom} = {};
 5069:             foreach my $server (keys(%dompersonnel)) {
 5070:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5071:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5072:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5073:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5074:                         next if ($end && $end < $now);
 5075:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5076:                             $dompersonnel{$server}{$item};
 5077:                     }
 5078:                 }
 5079:             }
 5080:             if (ref($privileged{$dom}) eq 'HASH') {
 5081:                 foreach my $role (@{$roles}) {
 5082:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5083:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5084:                     } else {
 5085:                         my %hash = ();
 5086:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5087:                     }
 5088:                 }
 5089:             }
 5090:         }
 5091:     }
 5092:     return %privileged;
 5093: }
 5094: 
 5095: # -------------------------------------------------------- Get user privileges
 5096: 
 5097: sub rolesinit {
 5098:     my ($domain, $username) = @_;
 5099:     my %userroles = ('user.login.time' => time);
 5100:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5101: 
 5102:     # firstaccess and timerinterval are related to timed maps/resources. 
 5103:     # also, blocking can be triggered by an activating timer
 5104:     # it's saved in the user's %env.
 5105:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5106:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5107:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5108:         %timerintchk, %timerintenv);
 5109: 
 5110:     foreach my $key (keys(%firstaccess)) {
 5111:         my ($cid, $rest) = split(/\0/, $key);
 5112:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5113:     }
 5114: 
 5115:     foreach my $key (keys(%timerinterval)) {
 5116:         my ($cid,$rest) = split(/\0/,$key);
 5117:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5118:     }
 5119: 
 5120:     my %allroles=();
 5121:     my %allgroups=();
 5122: 
 5123:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5124:         my $role = $rolesdump{$area};
 5125:         $area =~ s/\_\w\w$//;
 5126: 
 5127:         my ($trole, $tend, $tstart, $group_privs);
 5128: 
 5129:         if ($role =~ /^cr/) {
 5130:         # Custom role, defined by a user 
 5131:         # e.g., user.role.cr/msu/smith/mynewrole
 5132:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5133:                 $trole = $1;
 5134:                 ($tend, $tstart) = split('_', $2);
 5135:             } else {
 5136:                 $trole = $role;
 5137:             }
 5138:         } elsif ($role =~ m|^gr/|) {
 5139:         # Role of member in a group, defined within a course/community
 5140:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5141:             ($trole, $tend, $tstart) = split(/_/, $role);
 5142:             next if $tstart eq '-1';
 5143:             ($trole, $group_privs) = split(/\//, $trole);
 5144:             $group_privs = &unescape($group_privs);
 5145:         } else {
 5146:         # Just a normal role, defined in roles.tab
 5147:             ($trole, $tend, $tstart) = split(/_/,$role);
 5148:         }
 5149: 
 5150:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5151:                  $username);
 5152:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5153: 
 5154:         # role expired or not available yet?
 5155:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5156:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5157: 
 5158:         next if $area eq '' or $trole eq '';
 5159: 
 5160:         my $spec = "$trole.$area";
 5161:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5162: 
 5163:         if ($trole =~ /^cr\//) {
 5164:         # Custom role, defined by a user
 5165:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5166:         } elsif ($trole eq 'gr') {
 5167:         # Role of a member in a group, defined within a course/community
 5168:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5169:             next;
 5170:         } else {
 5171:         # Normal role, defined in roles.tab
 5172:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5173:         }
 5174: 
 5175:         my $cid = $tdomain.'_'.$trest;
 5176:         unless ($firstaccchk{$cid}) {
 5177:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5178:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5179:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5180:                         $coursetimerstarts{$cid}{$item}; 
 5181:                 }
 5182:             }
 5183:             $firstaccchk{$cid} = 1;
 5184:         }
 5185:         unless ($timerintchk{$cid}) {
 5186:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5187:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5188:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5189:                        $coursetimerintervals{$cid}{$item};
 5190:                 }
 5191:             }
 5192:             $timerintchk{$cid} = 1;
 5193:         }
 5194:     }
 5195: 
 5196:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5197:         \%allroles, \%allgroups);
 5198:     $env{'user.adv'} = $userroles{'user.adv'};
 5199: 
 5200:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5201: }
 5202: 
 5203: sub set_arearole {
 5204:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5205:     unless ($nolog) {
 5206: # log the associated role with the area
 5207:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5208:     }
 5209:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5210: }
 5211: 
 5212: sub custom_roleprivs {
 5213:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5214:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5215:     my $homsvr=homeserver($rauthor,$rdomain);
 5216:     if (&hostname($homsvr) ne '') {
 5217:         my ($rdummy,$roledef)=
 5218:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5219:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5220:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5221:             if (defined($syspriv)) {
 5222:                 if ($trest =~ /^$match_community$/) {
 5223:                     $syspriv =~ s/bre\&S//; 
 5224:                 }
 5225:                 $$allroles{'cm./'}.=':'.$syspriv;
 5226:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5227:             }
 5228:             if ($tdomain ne '') {
 5229:                 if (defined($dompriv)) {
 5230:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5231:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5232:                 }
 5233:                 if (($trest ne '') && (defined($coursepriv))) {
 5234:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5235:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5236:                 }
 5237:             }
 5238:         }
 5239:     }
 5240: }
 5241: 
 5242: sub group_roleprivs {
 5243:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5244:     my $access = 1;
 5245:     my $now = time;
 5246:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5247:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5248:     if ($access) {
 5249:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5250:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5251:     }
 5252: }
 5253: 
 5254: sub standard_roleprivs {
 5255:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5256:     if (defined($pr{$trole.':s'})) {
 5257:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5258:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5259:     }
 5260:     if ($tdomain ne '') {
 5261:         if (defined($pr{$trole.':d'})) {
 5262:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5263:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5264:         }
 5265:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5266:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5267:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5268:         }
 5269:     }
 5270: }
 5271: 
 5272: sub set_userprivs {
 5273:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5274:     my $author=0;
 5275:     my $adv=0;
 5276:     my %grouproles = ();
 5277:     if (keys(%{$allgroups}) > 0) {
 5278:         my @groupkeys; 
 5279:         foreach my $role (keys(%{$allroles})) {
 5280:             push(@groupkeys,$role);
 5281:         }
 5282:         if (ref($groups_roles) eq 'HASH') {
 5283:             foreach my $key (keys(%{$groups_roles})) {
 5284:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5285:                     push(@groupkeys,$key);
 5286:                 }
 5287:             }
 5288:         }
 5289:         if (@groupkeys > 0) {
 5290:             foreach my $role (@groupkeys) {
 5291:                 my ($trole,$area,$sec,$extendedarea);
 5292:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5293:                     $trole = $1;
 5294:                     $area = $2;
 5295:                     $sec = $3;
 5296:                     $extendedarea = $area.$sec;
 5297:                     if (exists($$allgroups{$area})) {
 5298:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5299:                             my $spec = $trole.'.'.$extendedarea;
 5300:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5301:                                                 $$allgroups{$area}{$group};
 5302:                         }
 5303:                     }
 5304:                 }
 5305:             }
 5306:         }
 5307:     }
 5308:     foreach my $group (keys(%grouproles)) {
 5309:         $$allroles{$group} = $grouproles{$group};
 5310:     }
 5311:     foreach my $role (keys(%{$allroles})) {
 5312:         my %thesepriv;
 5313:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5314:         foreach my $item (split(/:/,$$allroles{$role})) {
 5315:             if ($item ne '') {
 5316:                 my ($privilege,$restrictions)=split(/&/,$item);
 5317:                 if ($restrictions eq '') {
 5318:                     $thesepriv{$privilege}='F';
 5319:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5320:                     $thesepriv{$privilege}.=$restrictions;
 5321:                 }
 5322:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5323:             }
 5324:         }
 5325:         my $thesestr='';
 5326:         foreach my $priv (sort(keys(%thesepriv))) {
 5327: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5328: 	}
 5329:         $userroles->{'user.priv.'.$role} = $thesestr;
 5330:     }
 5331:     return ($author,$adv);
 5332: }
 5333: 
 5334: sub role_status {
 5335:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5336:     my @pwhere = ();
 5337:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5338:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5339:         unless (!defined($$role) || $$role eq '') {
 5340:             $$where=join('.',@pwhere);
 5341:             $$trolecode=$$role.'.'.$$where;
 5342:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5343:             $$tstatus='is';
 5344:             if ($$tstart && $$tstart>$update) {
 5345:                 $$tstatus='future';
 5346:                 if ($$tstart<$now) {
 5347:                     if ($$tstart && $$tstart>$refresh) {
 5348:                         if (($$where ne '') && ($$role ne '')) {
 5349:                             my (%allroles,%allgroups,$group_privs,
 5350:                                 %groups_roles,@rolecodes);
 5351:                             my %userroles = (
 5352:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5353:                             );
 5354:                             @rolecodes = ('cm'); 
 5355:                             my $spec=$$role.'.'.$$where;
 5356:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5357:                             if ($$role =~ /^cr\//) {
 5358:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5359:                                 push(@rolecodes,'cr');
 5360:                             } elsif ($$role eq 'gr') {
 5361:                                 push(@rolecodes,$$role);
 5362:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5363:                                                     $env{'user.name'});
 5364:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5365:                                 (undef,my $group_privs) = split(/\//,$trole);
 5366:                                 $group_privs = &unescape($group_privs);
 5367:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5368:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5369:                                 &get_groups_roles($tdomain,$trest,
 5370:                                                   \%course_roles,\@rolecodes,
 5371:                                                   \%groups_roles);
 5372:                             } else {
 5373:                                 push(@rolecodes,$$role);
 5374:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5375:                             }
 5376:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5377:                             &appenv(\%userroles,\@rolecodes);
 5378:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5379:                         }
 5380:                     }
 5381:                     $$tstatus = 'is';
 5382:                 }
 5383:             }
 5384:             if ($$tend) {
 5385:                 if ($$tend<$update) {
 5386:                     $$tstatus='expired';
 5387:                 } elsif ($$tend<$now) {
 5388:                     $$tstatus='will_not';
 5389:                 }
 5390:             }
 5391:         }
 5392:     }
 5393: }
 5394: 
 5395: sub get_groups_roles {
 5396:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5397:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5398:                   (ref($rolecodes) eq 'ARRAY') && 
 5399:                   (ref($groups_roles) eq 'HASH')); 
 5400:     if (keys(%{$cdom_courseroles}) > 0) {
 5401:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5402:         if ($cdom ne '' && $cnum ne '') {
 5403:             foreach my $key (keys(%{$cdom_courseroles})) {
 5404:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5405:                     my $crsrole = $1;
 5406:                     my $crssec = $2;
 5407:                     if ($crsrole =~ /^cr/) {
 5408:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5409:                             push(@{$rolecodes},'cr');
 5410:                         }
 5411:                     } else {
 5412:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5413:                             push(@{$rolecodes},$crsrole);
 5414:                         }
 5415:                     }
 5416:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5417:                     if ($crssec ne '') {
 5418:                         $rolekey .= "/$crssec";
 5419:                     }
 5420:                     $rolekey .= './';
 5421:                     $groups_roles->{$rolekey} = $rolecodes;
 5422:                 }
 5423:             }
 5424:         }
 5425:     }
 5426:     return;
 5427: }
 5428: 
 5429: sub delete_env_groupprivs {
 5430:     my ($where,$courseroles,$possroles) = @_;
 5431:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5432:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5433:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5434:         %{$courseroles->{$udom}} =
 5435:             &get_my_roles('','','userroles',['active'],
 5436:                           $possroles,[$udom],1);
 5437:     }
 5438:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5439:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5440:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5441:             my $area = '/'.$cdom.'/'.$cnum;
 5442:             my $privkey = "user.priv.$crsrole.$area";
 5443:             if ($crssec ne '') {
 5444:                 $privkey .= '/'.$crssec;
 5445:             }
 5446:             $privkey .= ".$area/$group";
 5447:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5448:         }
 5449:     }
 5450:     return;
 5451: }
 5452: 
 5453: sub check_adhoc_privs {
 5454:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5455:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5456:     my $setprivs;
 5457:     if ($env{$cckey}) {
 5458:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5459:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5460:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5461:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5462:             $setprivs = 1;
 5463:         }
 5464:     } else {
 5465:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5466:         $setprivs = 1;
 5467:     }
 5468:     return $setprivs;
 5469: }
 5470: 
 5471: sub set_adhoc_privileges {
 5472: # role can be cc or ca
 5473:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5474:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5475:     my $spec = $role.'.'.$area;
 5476:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5477:                                   $env{'user.name'},1);
 5478:     my %ccrole = ();
 5479:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5480:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5481:     &appenv(\%userroles,[$role,'cm']);
 5482:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5483:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5484:         &appenv( {'request.role'        => $spec,
 5485:                   'request.role.domain' => $dcdom,
 5486:                   'request.course.sec'  => ''
 5487:                  }
 5488:                );
 5489:         my $tadv=0;
 5490:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5491:         &appenv({'request.role.adv'    => $tadv});
 5492:     }
 5493: }
 5494: 
 5495: # --------------------------------------------------------------- get interface
 5496: 
 5497: sub get {
 5498:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5499:    my $items='';
 5500:    foreach my $item (@$storearr) {
 5501:        $items.=&escape($item).'&';
 5502:    }
 5503:    $items=~s/\&$//;
 5504:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5505:    if (!$uname) { $uname=$env{'user.name'}; }
 5506:    my $uhome=&homeserver($uname,$udomain);
 5507: 
 5508:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5509:    my @pairs=split(/\&/,$rep);
 5510:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5511:      return @pairs;
 5512:    }
 5513:    my %returnhash=();
 5514:    my $i=0;
 5515:    foreach my $item (@$storearr) {
 5516:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5517:       $i++;
 5518:    }
 5519:    return %returnhash;
 5520: }
 5521: 
 5522: # --------------------------------------------------------------- del interface
 5523: 
 5524: sub del {
 5525:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5526:    my $items='';
 5527:    foreach my $item (@$storearr) {
 5528:        $items.=&escape($item).'&';
 5529:    }
 5530: 
 5531:    $items=~s/\&$//;
 5532:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5533:    if (!$uname) { $uname=$env{'user.name'}; }
 5534:    my $uhome=&homeserver($uname,$udomain);
 5535:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5536: }
 5537: 
 5538: # -------------------------------------------------------------- dump interface
 5539: 
 5540: sub unserialize {
 5541:     my ($rep, $escapedkeys) = @_;
 5542: 
 5543:     return {} if $rep =~ /^error/;
 5544: 
 5545:     my %returnhash=();
 5546: 	foreach my $item (split /\&/, $rep) {
 5547: 	    my ($key, $value) = split(/=/, $item, 2);
 5548: 	    $key = unescape($key) unless $escapedkeys;
 5549: 	    next if $key =~ /^error: 2 /;
 5550: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5551: 	}
 5552:     #return %returnhash;
 5553:     return \%returnhash;
 5554: }        
 5555: 
 5556: # see Lond::dump_with_regexp
 5557: # if $escapedkeys hash keys won't get unescaped.
 5558: sub dump {
 5559:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5560:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5561:     if (!$uname) { $uname=$env{'user.name'}; }
 5562:     my $uhome=&homeserver($uname,$udomain);
 5563: 
 5564:     my $reply;
 5565:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5566:         # user is hosted on this machine
 5567:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5568:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5569:         return %{unserialize($reply, $escapedkeys)};
 5570:     }
 5571:     if ($regexp) {
 5572: 	$regexp=&escape($regexp);
 5573:     } else {
 5574: 	$regexp='.';
 5575:     }
 5576:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5577:     my @pairs=split(/\&/,$rep);
 5578:     my %returnhash=();
 5579:     if (!($rep =~ /^error/ )) {
 5580: 	foreach my $item (@pairs) {
 5581: 	    my ($key,$value)=split(/=/,$item,2);
 5582:         $key = unescape($key) unless $escapedkeys;
 5583:         #$key = &unescape($key);
 5584: 	    next if ($key =~ /^error: 2 /);
 5585: 	    $returnhash{$key}=&thaw_unescape($value);
 5586: 	}
 5587:     }
 5588:     return %returnhash;
 5589: }
 5590: 
 5591: 
 5592: # --------------------------------------------------------- dumpstore interface
 5593: 
 5594: sub dumpstore {
 5595:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5596:    # same as dump but keys must be escaped. They may contain colon separated
 5597:    # lists of values that may themself contain colons (e.g. symbs).
 5598:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5599: }
 5600: 
 5601: # -------------------------------------------------------------- keys interface
 5602: 
 5603: sub getkeys {
 5604:    my ($namespace,$udomain,$uname)=@_;
 5605:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5606:    if (!$uname) { $uname=$env{'user.name'}; }
 5607:    my $uhome=&homeserver($uname,$udomain);
 5608:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5609:    my @keyarray=();
 5610:    foreach my $key (split(/\&/,$rep)) {
 5611:       next if ($key =~ /^error: 2 /);
 5612:       push(@keyarray,&unescape($key));
 5613:    }
 5614:    return @keyarray;
 5615: }
 5616: 
 5617: # --------------------------------------------------------------- currentdump
 5618: sub currentdump {
 5619:    my ($courseid,$sdom,$sname)=@_;
 5620:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5621:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5622:    $sname    = $env{'user.name'}         if (! defined($sname));
 5623:    my $uhome = &homeserver($sname,$sdom);
 5624:    my $rep;
 5625: 
 5626:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5627:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5628:                    $courseid)));
 5629:    } else {
 5630:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5631:    }
 5632: 
 5633:    return if ($rep =~ /^(error:|no_such_host)/);
 5634:    #
 5635:    my %returnhash=();
 5636:    #
 5637:    if ($rep eq "unknown_cmd") { 
 5638:        # an old lond will not know currentdump
 5639:        # Do a dump and make it look like a currentdump
 5640:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5641:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5642:        my %hash = @tmp;
 5643:        @tmp=();
 5644:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5645:    } else {
 5646:        my @pairs=split(/\&/,$rep);
 5647:        foreach my $pair (@pairs) {
 5648:            my ($key,$value)=split(/=/,$pair,2);
 5649:            my ($symb,$param) = split(/:/,$key);
 5650:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5651:                                                         &thaw_unescape($value);
 5652:        }
 5653:    }
 5654:    return %returnhash;
 5655: }
 5656: 
 5657: sub convert_dump_to_currentdump{
 5658:     my %hash = %{shift()};
 5659:     my %returnhash;
 5660:     # Code ripped from lond, essentially.  The only difference
 5661:     # here is the unescaping done by lonnet::dump().  Conceivably
 5662:     # we might run in to problems with parameter names =~ /^v\./
 5663:     while (my ($key,$value) = each(%hash)) {
 5664:         my ($v,$symb,$param) = split(/:/,$key);
 5665: 	$symb  = &unescape($symb);
 5666: 	$param = &unescape($param);
 5667:         next if ($v eq 'version' || $symb eq 'keys');
 5668:         next if (exists($returnhash{$symb}) &&
 5669:                  exists($returnhash{$symb}->{$param}) &&
 5670:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5671:         $returnhash{$symb}->{$param}=$value;
 5672:         $returnhash{$symb}->{'v.'.$param}=$v;
 5673:     }
 5674:     #
 5675:     # Remove all of the keys in the hashes which keep track of
 5676:     # the version of the parameter.
 5677:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5678:         # use a foreach because we are going to delete from the hash.
 5679:         foreach my $key (keys(%$param_hash)) {
 5680:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5681:         }
 5682:     }
 5683:     return \%returnhash;
 5684: }
 5685: 
 5686: # ------------------------------------------------------ critical inc interface
 5687: 
 5688: sub cinc {
 5689:     return &inc(@_,'critical');
 5690: }
 5691: 
 5692: # --------------------------------------------------------------- inc interface
 5693: 
 5694: sub inc {
 5695:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5696:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5697:     if (!$uname) { $uname=$env{'user.name'}; }
 5698:     my $uhome=&homeserver($uname,$udomain);
 5699:     my $items='';
 5700:     if (! ref($store)) {
 5701:         # got a single value, so use that instead
 5702:         $items = &escape($store).'=&';
 5703:     } elsif (ref($store) eq 'SCALAR') {
 5704:         $items = &escape($$store).'=&';        
 5705:     } elsif (ref($store) eq 'ARRAY') {
 5706:         $items = join('=&',map {&escape($_);} @{$store});
 5707:     } elsif (ref($store) eq 'HASH') {
 5708:         while (my($key,$value) = each(%{$store})) {
 5709:             $items.= &escape($key).'='.&escape($value).'&';
 5710:         }
 5711:     }
 5712:     $items=~s/\&$//;
 5713:     if ($critical) {
 5714: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5715:     } else {
 5716: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5717:     }
 5718: }
 5719: 
 5720: # --------------------------------------------------------------- put interface
 5721: 
 5722: sub put {
 5723:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5724:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5725:    if (!$uname) { $uname=$env{'user.name'}; }
 5726:    my $uhome=&homeserver($uname,$udomain);
 5727:    my $items='';
 5728:    foreach my $item (keys(%$storehash)) {
 5729:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5730:    }
 5731:    $items=~s/\&$//;
 5732:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5733: }
 5734: 
 5735: # ------------------------------------------------------------ newput interface
 5736: 
 5737: sub newput {
 5738:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5740:    if (!$uname) { $uname=$env{'user.name'}; }
 5741:    my $uhome=&homeserver($uname,$udomain);
 5742:    my $items='';
 5743:    foreach my $key (keys(%$storehash)) {
 5744:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5745:    }
 5746:    $items=~s/\&$//;
 5747:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5748: }
 5749: 
 5750: # ---------------------------------------------------------  putstore interface
 5751: 
 5752: sub putstore {
 5753:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5754:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5755:    if (!$uname) { $uname=$env{'user.name'}; }
 5756:    my $uhome=&homeserver($uname,$udomain);
 5757:    my $items='';
 5758:    foreach my $key (keys(%$storehash)) {
 5759:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5760:    }
 5761:    $items=~s/\&$//;
 5762:    my $esc_symb=&escape($symb);
 5763:    my $esc_v=&escape($version);
 5764:    my $reply =
 5765:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5766: 	      $uhome);
 5767:    if ($reply eq 'unknown_cmd') {
 5768:        # gfall back to way things use to be done
 5769:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5770: 			    $uname);
 5771:    }
 5772:    return $reply;
 5773: }
 5774: 
 5775: sub old_putstore {
 5776:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5777:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5778:     if (!$uname) { $uname=$env{'user.name'}; }
 5779:     my $uhome=&homeserver($uname,$udomain);
 5780:     my %newstorehash;
 5781:     foreach my $item (keys(%$storehash)) {
 5782: 	my $key = $version.':'.&escape($symb).':'.$item;
 5783: 	$newstorehash{$key} = $storehash->{$item};
 5784:     }
 5785:     my $items='';
 5786:     my %allitems = ();
 5787:     foreach my $item (keys(%newstorehash)) {
 5788: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5789: 	    my $key = $1.':keys:'.$2;
 5790: 	    $allitems{$key} .= $3.':';
 5791: 	}
 5792: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5793:     }
 5794:     foreach my $item (keys(%allitems)) {
 5795: 	$allitems{$item} =~ s/\:$//;
 5796: 	$items.= $item.'='.$allitems{$item}.'&';
 5797:     }
 5798:     $items=~s/\&$//;
 5799:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5800: }
 5801: 
 5802: # ------------------------------------------------------ critical put interface
 5803: 
 5804: sub cput {
 5805:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5806:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5807:    if (!$uname) { $uname=$env{'user.name'}; }
 5808:    my $uhome=&homeserver($uname,$udomain);
 5809:    my $items='';
 5810:    foreach my $item (keys(%$storehash)) {
 5811:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5812:    }
 5813:    $items=~s/\&$//;
 5814:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5815: }
 5816: 
 5817: # -------------------------------------------------------------- eget interface
 5818: 
 5819: sub eget {
 5820:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5821:    my $items='';
 5822:    foreach my $item (@$storearr) {
 5823:        $items.=&escape($item).'&';
 5824:    }
 5825:    $items=~s/\&$//;
 5826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5827:    if (!$uname) { $uname=$env{'user.name'}; }
 5828:    my $uhome=&homeserver($uname,$udomain);
 5829:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5830:    my @pairs=split(/\&/,$rep);
 5831:    my %returnhash=();
 5832:    my $i=0;
 5833:    foreach my $item (@$storearr) {
 5834:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5835:       $i++;
 5836:    }
 5837:    return %returnhash;
 5838: }
 5839: 
 5840: # ------------------------------------------------------------ tmpput interface
 5841: sub tmpput {
 5842:     my ($storehash,$server,$context)=@_;
 5843:     my $items='';
 5844:     foreach my $item (keys(%$storehash)) {
 5845: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5846:     }
 5847:     $items=~s/\&$//;
 5848:     if (defined($context)) {
 5849:         $items .= ':'.&escape($context);
 5850:     }
 5851:     return &reply("tmpput:$items",$server);
 5852: }
 5853: 
 5854: # ------------------------------------------------------------ tmpget interface
 5855: sub tmpget {
 5856:     my ($token,$server)=@_;
 5857:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5858:     my $rep=&reply("tmpget:$token",$server);
 5859:     my %returnhash;
 5860:     foreach my $item (split(/\&/,$rep)) {
 5861: 	my ($key,$value)=split(/=/,$item);
 5862:         next if ($key =~ /^error: 2 /);
 5863: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5864:     }
 5865:     return %returnhash;
 5866: }
 5867: 
 5868: # ------------------------------------------------------------ tmpdel interface
 5869: sub tmpdel {
 5870:     my ($token,$server)=@_;
 5871:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5872:     return &reply("tmpdel:$token",$server);
 5873: }
 5874: 
 5875: # ------------------------------------------------------------ get_timebased_id 
 5876: 
 5877: sub get_timebased_id {
 5878:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5879:         $maxtries) = @_;
 5880:     my ($newid,$error,$dellock);
 5881:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5882:         return ('','ok','invalid call to get suffix');
 5883:     }
 5884: 
 5885: # set defaults for any optional args for which values were not supplied
 5886:     if ($who eq '') {
 5887:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5888:     }
 5889:     if (!$locktries) {
 5890:         $locktries = 3;
 5891:     }
 5892:     if (!$maxtries) {
 5893:         $maxtries = 10;
 5894:     }
 5895:     
 5896:     if (($cdom eq '') || ($cnum eq '')) {
 5897:         if ($env{'request.course.id'}) {
 5898:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5899:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5900:         }
 5901:         if (($cdom eq '') || ($cnum eq '')) {
 5902:             return ('','ok','call to get suffix not in course context');
 5903:         }
 5904:     }
 5905: 
 5906: # construct locking item
 5907:     my $lockhash = {
 5908:                       $prefix."\0".'locked_'.$keyid => $who,
 5909:                    };
 5910:     my $tries = 0;
 5911: 
 5912: # attempt to get lock on nohist_$namespace file
 5913:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5914:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5915:         $tries ++;
 5916:         sleep 1;
 5917:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5918:     }
 5919: 
 5920: # attempt to get unique identifier, based on current timestamp
 5921:     if ($gotlock eq 'ok') {
 5922:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5923:         my $id = time;
 5924:         $newid = $id;
 5925:         my $idtries = 0;
 5926:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5927:             if ($idtype eq 'concat') {
 5928:                 $newid = $id.$idtries;
 5929:             } else {
 5930:                 $newid ++;
 5931:             }
 5932:             $idtries ++;
 5933:         }
 5934:         if (!exists($inuse{$prefix."\0".$newid})) {
 5935:             my %new_item =  (
 5936:                               $prefix."\0".$newid => $who,
 5937:                             );
 5938:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5939:                                                  $cdom,$cnum);
 5940:             if ($putresult ne 'ok') {
 5941:                 undef($newid);
 5942:                 $error = 'error saving new item: '.$putresult;
 5943:             }
 5944:         } else {
 5945:              $error = ('error: no unique suffix available for the new item ');
 5946:         }
 5947: #  remove lock
 5948:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5949:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5950:     } else {
 5951:         $error = "error: could not obtain lockfile\n";
 5952:         $dellock = 'ok';
 5953:     }
 5954:     return ($newid,$dellock,$error);
 5955: }
 5956: 
 5957: # -------------------------------------------------- portfolio access checking
 5958: 
 5959: sub portfolio_access {
 5960:     my ($requrl) = @_;
 5961:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5962:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5963:     if ($result) {
 5964:         my %setters;
 5965:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5966:             my ($startblock,$endblock) =
 5967:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5968:             if ($startblock && $endblock) {
 5969:                 return 'B';
 5970:             }
 5971:         } else {
 5972:             my ($startblock,$endblock) =
 5973:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5974:             if ($startblock && $endblock) {
 5975:                 return 'B';
 5976:             }
 5977:         }
 5978:     }
 5979:     if ($result eq 'ok') {
 5980:        return 'F';
 5981:     } elsif ($result =~ /^[^:]+:guest_/) {
 5982:        return 'A';
 5983:     }
 5984:     return '';
 5985: }
 5986: 
 5987: sub get_portfolio_access {
 5988:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5989: 
 5990:     if (!ref($access_hash)) {
 5991: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5992: 	my %access_controls = &get_access_controls($current_perms,$group,
 5993: 						   $file_name);
 5994: 	$access_hash = $access_controls{$file_name};
 5995:     }
 5996: 
 5997:     my ($public,$guest,@domains,@users,@courses,@groups);
 5998:     my $now = time;
 5999:     if (ref($access_hash) eq 'HASH') {
 6000:         foreach my $key (keys(%{$access_hash})) {
 6001:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6002:             if ($start > $now) {
 6003:                 next;
 6004:             }
 6005:             if ($end && $end<$now) {
 6006:                 next;
 6007:             }
 6008:             if ($scope eq 'public') {
 6009:                 $public = $key;
 6010:                 last;
 6011:             } elsif ($scope eq 'guest') {
 6012:                 $guest = $key;
 6013:             } elsif ($scope eq 'domains') {
 6014:                 push(@domains,$key);
 6015:             } elsif ($scope eq 'users') {
 6016:                 push(@users,$key);
 6017:             } elsif ($scope eq 'course') {
 6018:                 push(@courses,$key);
 6019:             } elsif ($scope eq 'group') {
 6020:                 push(@groups,$key);
 6021:             }
 6022:         }
 6023:         if ($public) {
 6024:             return 'ok';
 6025:         }
 6026:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6027:             if ($guest) {
 6028:                 return $guest;
 6029:             }
 6030:         } else {
 6031:             if (@domains > 0) {
 6032:                 foreach my $domkey (@domains) {
 6033:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6034:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6035:                             return 'ok';
 6036:                         }
 6037:                     }
 6038:                 }
 6039:             }
 6040:             if (@users > 0) {
 6041:                 foreach my $userkey (@users) {
 6042:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6043:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6044:                             if (ref($item) eq 'HASH') {
 6045:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6046:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6047:                                     return 'ok';
 6048:                                 }
 6049:                             }
 6050:                         }
 6051:                     } 
 6052:                 }
 6053:             }
 6054:             my %roleshash;
 6055:             my @courses_and_groups = @courses;
 6056:             push(@courses_and_groups,@groups); 
 6057:             if (@courses_and_groups > 0) {
 6058:                 my (%allgroups,%allroles); 
 6059:                 my ($start,$end,$role,$sec,$group);
 6060:                 foreach my $envkey (%env) {
 6061:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6062:                         my $cid = $2.'_'.$3; 
 6063:                         if ($1 eq 'gr') {
 6064:                             $group = $4;
 6065:                             $allgroups{$cid}{$group} = $env{$envkey};
 6066:                         } else {
 6067:                             if ($4 eq '') {
 6068:                                 $sec = 'none';
 6069:                             } else {
 6070:                                 $sec = $4;
 6071:                             }
 6072:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6073:                         }
 6074:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6075:                         my $cid = $2.'_'.$3;
 6076:                         if ($4 eq '') {
 6077:                             $sec = 'none';
 6078:                         } else {
 6079:                             $sec = $4;
 6080:                         }
 6081:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6082:                     }
 6083:                 }
 6084:                 if (keys(%allroles) == 0) {
 6085:                     return;
 6086:                 }
 6087:                 foreach my $key (@courses_and_groups) {
 6088:                     my %content = %{$$access_hash{$key}};
 6089:                     my $cnum = $content{'number'};
 6090:                     my $cdom = $content{'domain'};
 6091:                     my $cid = $cdom.'_'.$cnum;
 6092:                     if (!exists($allroles{$cid})) {
 6093:                         next;
 6094:                     }    
 6095:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6096:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6097:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6098:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6099:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6100:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6101:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6102:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6103:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6104:                                         if (grep/^all$/,@sections) {
 6105:                                             return 'ok';
 6106:                                         } else {
 6107:                                             if (grep/^$sec$/,@sections) {
 6108:                                                 return 'ok';
 6109:                                             }
 6110:                                         }
 6111:                                     }
 6112:                                 }
 6113:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6114:                                     if (grep/^none$/,@groups) {
 6115:                                         return 'ok';
 6116:                                     }
 6117:                                 } else {
 6118:                                     if (grep/^all$/,@groups) {
 6119:                                         return 'ok';
 6120:                                     } 
 6121:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6122:                                         if (grep/^$group$/,@groups) {
 6123:                                             return 'ok';
 6124:                                         }
 6125:                                     }
 6126:                                 } 
 6127:                             }
 6128:                         }
 6129:                     }
 6130:                 }
 6131:             }
 6132:             if ($guest) {
 6133:                 return $guest;
 6134:             }
 6135:         }
 6136:     }
 6137:     return;
 6138: }
 6139: 
 6140: sub course_group_datechecker {
 6141:     my ($dates,$now,$status) = @_;
 6142:     my ($start,$end) = split(/\./,$dates);
 6143:     if (!$start && !$end) {
 6144:         return 'ok';
 6145:     }
 6146:     if (grep/^active$/,@{$status}) {
 6147:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6148:             return 'ok';
 6149:         }
 6150:     }
 6151:     if (grep/^previous$/,@{$status}) {
 6152:         if ($end > $now ) {
 6153:             return 'ok';
 6154:         }
 6155:     }
 6156:     if (grep/^future$/,@{$status}) {
 6157:         if ($start > $now) {
 6158:             return 'ok';
 6159:         }
 6160:     }
 6161:     return; 
 6162: }
 6163: 
 6164: sub parse_portfolio_url {
 6165:     my ($url) = @_;
 6166: 
 6167:     my ($type,$udom,$unum,$group,$file_name);
 6168:     
 6169:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6170: 	$type = 1;
 6171:         $udom = $1;
 6172:         $unum = $2;
 6173:         $file_name = $3;
 6174:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6175: 	$type = 2;
 6176:         $udom = $1;
 6177:         $unum = $2;
 6178:         $group = $3;
 6179:         $file_name = $3.'/'.$4;
 6180:     }
 6181:     if (wantarray) {
 6182: 	return ($type,$udom,$unum,$file_name,$group);
 6183:     }
 6184:     return $type;
 6185: }
 6186: 
 6187: sub is_portfolio_url {
 6188:     my ($url) = @_;
 6189:     return scalar(&parse_portfolio_url($url));
 6190: }
 6191: 
 6192: sub is_portfolio_file {
 6193:     my ($file) = @_;
 6194:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6195:         return 1;
 6196:     }
 6197:     return;
 6198: }
 6199: 
 6200: sub usertools_access {
 6201:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6202:     my ($access,%tools);
 6203:     if ($context eq '') {
 6204:         $context = 'tools';
 6205:     }
 6206:     if ($context eq 'requestcourses') {
 6207:         %tools = (
 6208:                       official   => 1,
 6209:                       unofficial => 1,
 6210:                       community  => 1,
 6211:                  );
 6212:     } elsif ($context eq 'requestauthor') {
 6213:         %tools = (
 6214:                       requestauthor => 1,
 6215:                  );
 6216:     } else {
 6217:         %tools = (
 6218:                       aboutme   => 1,
 6219:                       blog      => 1,
 6220:                       webdav    => 1,
 6221:                       portfolio => 1,
 6222:                  );
 6223:     }
 6224:     return if (!defined($tools{$tool}));
 6225: 
 6226:     if (($udom eq '') || ($uname eq '')) {
 6227:         $udom = $env{'user.domain'};
 6228:         $uname = $env{'user.name'};
 6229:     }
 6230: 
 6231:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6232:         if ($action ne 'reload') {
 6233:             if ($context eq 'requestcourses') {
 6234:                 return $env{'environment.canrequest.'.$tool};
 6235:             } elsif ($context eq 'requestauthor') {
 6236:                 return $env{'environment.canrequest.author'};
 6237:             } else {
 6238:                 return $env{'environment.availabletools.'.$tool};
 6239:             }
 6240:         }
 6241:     }
 6242: 
 6243:     my ($toolstatus,$inststatus,$envkey);
 6244:     if ($context eq 'requestauthor') {
 6245:         $envkey = $context; 
 6246:     } else {
 6247:         $envkey = $context.'.'.$tool;
 6248:     }
 6249: 
 6250:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6251:          ($action ne 'reload')) {
 6252:         $toolstatus = $env{'environment.'.$envkey};
 6253:         $inststatus = $env{'environment.inststatus'};
 6254:     } else {
 6255:         if (ref($userenvref) eq 'HASH') {
 6256:             $toolstatus = $userenvref->{$envkey};
 6257:             $inststatus = $userenvref->{'inststatus'};
 6258:         } else {
 6259:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6260:             $toolstatus = $userenv{$envkey};
 6261:             $inststatus = $userenv{'inststatus'};
 6262:         }
 6263:     }
 6264: 
 6265:     if ($toolstatus ne '') {
 6266:         if ($toolstatus) {
 6267:             $access = 1;
 6268:         } else {
 6269:             $access = 0;
 6270:         }
 6271:         return $access;
 6272:     }
 6273: 
 6274:     my ($is_adv,%domdef);
 6275:     if (ref($is_advref) eq 'HASH') {
 6276:         $is_adv = $is_advref->{'is_adv'};
 6277:     } else {
 6278:         $is_adv = &is_advanced_user($udom,$uname);
 6279:     }
 6280:     if (ref($domdefref) eq 'HASH') {
 6281:         %domdef = %{$domdefref};
 6282:     } else {
 6283:         %domdef = &get_domain_defaults($udom);
 6284:     }
 6285:     if (ref($domdef{$tool}) eq 'HASH') {
 6286:         if ($is_adv) {
 6287:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6288:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6289:                     $access = 1;
 6290:                 } else {
 6291:                     $access = 0;
 6292:                 }
 6293:                 return $access;
 6294:             }
 6295:         }
 6296:         if ($inststatus ne '') {
 6297:             my ($hasaccess,$hasnoaccess);
 6298:             foreach my $affiliation (split(/:/,$inststatus)) {
 6299:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6300:                     if ($domdef{$tool}{$affiliation}) {
 6301:                         $hasaccess = 1;
 6302:                     } else {
 6303:                         $hasnoaccess = 1;
 6304:                     }
 6305:                 }
 6306:             }
 6307:             if ($hasaccess || $hasnoaccess) {
 6308:                 if ($hasaccess) {
 6309:                     $access = 1;
 6310:                 } elsif ($hasnoaccess) {
 6311:                     $access = 0; 
 6312:                 }
 6313:                 return $access;
 6314:             }
 6315:         } else {
 6316:             if ($domdef{$tool}{'default'} ne '') {
 6317:                 if ($domdef{$tool}{'default'}) {
 6318:                     $access = 1;
 6319:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6320:                     $access = 0;
 6321:                 }
 6322:                 return $access;
 6323:             }
 6324:         }
 6325:     } else {
 6326:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6327:             $access = 1;
 6328:         } else {
 6329:             $access = 0;
 6330:         }
 6331:         return $access;
 6332:     }
 6333: }
 6334: 
 6335: sub is_course_owner {
 6336:     my ($cdom,$cnum,$udom,$uname) = @_;
 6337:     if (($udom eq '') || ($uname eq '')) {
 6338:         $udom = $env{'user.domain'};
 6339:         $uname = $env{'user.name'};
 6340:     }
 6341:     unless (($udom eq '') || ($uname eq '')) {
 6342:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6343:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6344:                 return 1;
 6345:             } else {
 6346:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6347:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6348:                     return 1;
 6349:                 }
 6350:             }
 6351:         }
 6352:     }
 6353:     return;
 6354: }
 6355: 
 6356: sub is_advanced_user {
 6357:     my ($udom,$uname) = @_;
 6358:     if ($udom ne '' && $uname ne '') {
 6359:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6360:             if (wantarray) {
 6361:                 return ($env{'user.adv'},$env{'user.author'});
 6362:             } else {
 6363:                 return $env{'user.adv'};
 6364:             }
 6365:         }
 6366:     }
 6367:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6368:     my %allroles;
 6369:     my ($is_adv,$is_author);
 6370:     foreach my $role (keys(%roleshash)) {
 6371:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6372:         my $area = '/'.$tdomain.'/'.$trest;
 6373:         if ($sec ne '') {
 6374:             $area .= '/'.$sec;
 6375:         }
 6376:         if (($area ne '') && ($trole ne '')) {
 6377:             my $spec=$trole.'.'.$area;
 6378:             if ($trole =~ /^cr\//) {
 6379:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6380:             } elsif ($trole ne 'gr') {
 6381:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6382:             }
 6383:             if ($trole eq 'au') {
 6384:                 $is_author = 1;
 6385:             }
 6386:         }
 6387:     }
 6388:     foreach my $role (keys(%allroles)) {
 6389:         last if ($is_adv);
 6390:         foreach my $item (split(/:/,$allroles{$role})) {
 6391:             if ($item ne '') {
 6392:                 my ($privilege,$restrictions)=split(/&/,$item);
 6393:                 if ($privilege eq 'adv') {
 6394:                     $is_adv = 1;
 6395:                     last;
 6396:                 }
 6397:             }
 6398:         }
 6399:     }
 6400:     if (wantarray) {
 6401:         return ($is_adv,$is_author);
 6402:     }
 6403:     return $is_adv;
 6404: }
 6405: 
 6406: sub check_can_request {
 6407:     my ($dom,$can_request,$request_domains) = @_;
 6408:     my $canreq = 0;
 6409:     my ($types,$typename) = &Apache::loncommon::course_types();
 6410:     my @options = ('approval','validate','autolimit');
 6411:     my $optregex = join('|',@options);
 6412:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6413:         foreach my $type (@{$types}) {
 6414:             if (&usertools_access($env{'user.name'},
 6415:                                   $env{'user.domain'},
 6416:                                   $type,undef,'requestcourses')) {
 6417:                 $canreq ++;
 6418:                 if (ref($request_domains) eq 'HASH') {
 6419:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6420:                 }
 6421:                 if ($dom eq $env{'user.domain'}) {
 6422:                     $can_request->{$type} = 1;
 6423:                 }
 6424:             }
 6425:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6426:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6427:                 if (@curr > 0) {
 6428:                     foreach my $item (@curr) {
 6429:                         if (ref($request_domains) eq 'HASH') {
 6430:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6431:                             if ($otherdom ne '') {
 6432:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6433:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6434:                                         push(@{$request_domains->{$type}},$otherdom);
 6435:                                     }
 6436:                                 } else {
 6437:                                     push(@{$request_domains->{$type}},$otherdom);
 6438:                                 }
 6439:                             }
 6440:                         }
 6441:                     }
 6442:                     unless($dom eq $env{'user.domain'}) {
 6443:                         $canreq ++;
 6444:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6445:                             $can_request->{$type} = 1;
 6446:                         }
 6447:                     }
 6448:                 }
 6449:             }
 6450:         }
 6451:     }
 6452:     return $canreq;
 6453: }
 6454: 
 6455: # ---------------------------------------------- Custom access rule evaluation
 6456: 
 6457: sub customaccess {
 6458:     my ($priv,$uri)=@_;
 6459:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6460:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6461:     $udom = &LONCAPA::clean_domain($udom);
 6462:     $ucrs = &LONCAPA::clean_username($ucrs);
 6463:     my $access=0;
 6464:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6465: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6466: 	if ($type eq 'user') {
 6467: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6468: 		my ($tdom,$tuname)=split(m{/},$scope);
 6469: 		if ($tdom) {
 6470: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6471: 		}
 6472: 		if ($tuname) {
 6473: 		    if ($tuname ne $env{'user.name'}) { next; }
 6474: 		}
 6475: 		$access=($effect eq 'allow');
 6476: 		last;
 6477: 	    }
 6478: 	} else {
 6479: 	    if ($role) {
 6480: 		if ($role ne $urole) { next; }
 6481: 	    }
 6482: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6483: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6484: 		if ($tdom) {
 6485: 		    if ($tdom ne $udom) { next; }
 6486: 		}
 6487: 		if ($tcrs) {
 6488: 		    if ($tcrs ne $ucrs) { next; }
 6489: 		}
 6490: 		if ($tsec) {
 6491: 		    if ($tsec ne $usec) { next; }
 6492: 		}
 6493: 		$access=($effect eq 'allow');
 6494: 		last;
 6495: 	    }
 6496: 	    if ($realm eq '' && $role eq '') {
 6497: 		$access=($effect eq 'allow');
 6498: 	    }
 6499: 	}
 6500:     }
 6501:     return $access;
 6502: }
 6503: 
 6504: # ------------------------------------------------- Check for a user privilege
 6505: 
 6506: sub allowed {
 6507:     my ($priv,$uri,$symb,$role)=@_;
 6508:     my $ver_orguri=$uri;
 6509:     $uri=&deversion($uri);
 6510:     my $orguri=$uri;
 6511:     $uri=&declutter($uri);
 6512: 
 6513:     if ($priv eq 'evb') {
 6514: # Evade communication block restrictions for specified role in a course
 6515:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6516:             return $1;
 6517:         } else {
 6518:             return;
 6519:         }
 6520:     }
 6521: 
 6522:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6523: # Free bre access to adm and meta resources
 6524:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6525: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6526: 	&& ($priv eq 'bre')) {
 6527: 	return 'F';
 6528:     }
 6529: 
 6530: # Free bre access to user's own portfolio contents
 6531:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6532:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6533: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6534:         my %setters;
 6535:         my ($startblock,$endblock) = 
 6536:             &Apache::loncommon::blockcheck(\%setters,'port');
 6537:         if ($startblock && $endblock) {
 6538:             return 'B';
 6539:         } else {
 6540:             return 'F';
 6541:         }
 6542:     }
 6543: 
 6544: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6545:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6546:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6547:         if (exists($env{'request.course.id'})) {
 6548:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6549:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6550:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6551:                 my $courseprivid=$env{'request.course.id'};
 6552:                 $courseprivid=~s/\_/\//;
 6553:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6554:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6555:                     return $1; 
 6556:                 } else {
 6557:                     if ($env{'request.course.sec'}) {
 6558:                         $courseprivid.='/'.$env{'request.course.sec'};
 6559:                     }
 6560:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6561:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6562:                         return $2;
 6563:                     }
 6564:                 }
 6565:             }
 6566:         }
 6567:     }
 6568: 
 6569: # Free bre to public access
 6570: 
 6571:     if ($priv eq 'bre') {
 6572:         my $copyright=&metadata($uri,'copyright');
 6573: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6574:            return 'F'; 
 6575:         }
 6576:         if ($copyright eq 'priv') {
 6577:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6578: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6579: 		return '';
 6580:             }
 6581:         }
 6582:         if ($copyright eq 'domain') {
 6583:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6584: 	    unless (($env{'user.domain'} eq $1) ||
 6585:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6586: 		return '';
 6587:             }
 6588:         }
 6589:         if ($env{'request.role'}=~ /li\.\//) {
 6590:             # Library role, so allow browsing of resources in this domain.
 6591:             return 'F';
 6592:         }
 6593:         if ($copyright eq 'custom') {
 6594: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6595:         }
 6596:     }
 6597:     # Domain coordinator is trying to create a course
 6598:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6599:         # uri is the requested domain in this case.
 6600:         # comparison to 'request.role.domain' shows if the user has selected
 6601:         # a role of dc for the domain in question.
 6602:         return 'F' if ($uri eq $env{'request.role.domain'});
 6603:     }
 6604: 
 6605:     my $thisallowed='';
 6606:     my $statecond=0;
 6607:     my $courseprivid='';
 6608: 
 6609:     my $ownaccess;
 6610:     # Community Coordinator or Assistant Co-author browsing resource space.
 6611:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6612:         if ($uri eq '') {
 6613:             $ownaccess = 1;
 6614:         } else {
 6615:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6616:                 my $udom = $env{'user.domain'};
 6617:                 my $uname = $env{'user.name'};
 6618:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6619:                     $ownaccess = 1;
 6620:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6621:                     unless ($uri =~ m{\.\./}) {
 6622:                         $ownaccess = 1;
 6623:                     }
 6624:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6625:                     my $now = time;
 6626:                     if ($uri =~ m{^([^/]+)/?$}) {
 6627:                         my $adom = $1;
 6628:                         foreach my $key (keys(%env)) {
 6629:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6630:                                 my ($start,$end) = split('.',$env{$key});
 6631:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6632:                                     $ownaccess = 1;
 6633:                                     last;
 6634:                                 }
 6635:                             }
 6636:                         }
 6637:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6638:                         my $adom = $1;
 6639:                         my $aname = $2;
 6640:                         foreach my $role ('ca','aa') { 
 6641:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6642:                                 my ($start,$end) =
 6643:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6644:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6645:                                     $ownaccess = 1;
 6646:                                     last;
 6647:                                 }
 6648:                             }
 6649:                         }
 6650:                     }
 6651:                 }
 6652:             }
 6653:         }
 6654:     }
 6655: 
 6656: # Course
 6657: 
 6658:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6659:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6660:             $thisallowed.=$1;
 6661:         }
 6662:     }
 6663: 
 6664: # Domain
 6665: 
 6666:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6667:        =~/\Q$priv\E\&([^\:]*)/) {
 6668:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6669:             $thisallowed.=$1;
 6670:         }
 6671:     }
 6672: 
 6673: # User who is not author or co-author might still be able to edit
 6674: # resource of an author in the domain (e.g., if Domain Coordinator).
 6675:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6676:         (&allowed('mdc',$env{'request.course.id'}))) {
 6677:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6678:             $thisallowed.=$1;
 6679:         }
 6680:     }
 6681: 
 6682: # Course: uri itself is a course
 6683:     my $courseuri=$uri;
 6684:     $courseuri=~s/\_(\d)/\/$1/;
 6685:     $courseuri=~s/^([^\/])/\/$1/;
 6686: 
 6687:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6688:        =~/\Q$priv\E\&([^\:]*)/) {
 6689:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6690:             $thisallowed.=$1;
 6691:         }
 6692:     }
 6693: 
 6694: # URI is an uploaded document for this course, default permissions don't matter
 6695: # not allowing 'edit' access (editupload) to uploaded course docs
 6696:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6697: 	$thisallowed='';
 6698:         my ($match)=&is_on_map($uri);
 6699:         if ($match) {
 6700:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6701:                   =~/\Q$priv\E\&([^\:]*)/) {
 6702:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6703:                 if (@blockers > 0) {
 6704:                     $thisallowed = 'B';
 6705:                 } else {
 6706:                     $thisallowed.=$1;
 6707:                 }
 6708:             }
 6709:         } else {
 6710:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6711:             if ($refuri) {
 6712:                 if ($refuri =~ m|^/adm/|) {
 6713:                     $thisallowed='F';
 6714:                 } else {
 6715:                     $refuri=&declutter($refuri);
 6716:                     my ($match) = &is_on_map($refuri);
 6717:                     if ($match) {
 6718:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6719:                         if (@blockers > 0) {
 6720:                             $thisallowed = 'B';
 6721:                         } else {
 6722:                             $thisallowed='F';
 6723:                         }
 6724:                     }
 6725:                 }
 6726:             }
 6727:         }
 6728:     }
 6729: 
 6730:     if ($priv eq 'bre'
 6731: 	&& $thisallowed ne 'F' 
 6732: 	&& $thisallowed ne '2'
 6733: 	&& &is_portfolio_url($uri)) {
 6734: 	$thisallowed = &portfolio_access($uri);
 6735:     }
 6736:     
 6737: # Full access at system, domain or course-wide level? Exit.
 6738:     if ($thisallowed=~/F/) {
 6739: 	return 'F';
 6740:     }
 6741: 
 6742: # If this is generating or modifying users, exit with special codes
 6743: 
 6744:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6745: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6746: 	    my ($audom,$auname)=split('/',$uri);
 6747: # no author name given, so this just checks on the general right to make a co-author in this domain
 6748: 	    unless ($auname) { return $thisallowed; }
 6749: # an author name is given, so we are about to actually make a co-author for a certain account
 6750: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6751: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6752: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6753: 	}
 6754: 	return $thisallowed;
 6755:     }
 6756: #
 6757: # Gathered so far: system, domain and course wide privileges
 6758: #
 6759: # Course: See if uri or referer is an individual resource that is part of 
 6760: # the course
 6761: 
 6762:     if ($env{'request.course.id'}) {
 6763: 
 6764:        $courseprivid=$env{'request.course.id'};
 6765:        if ($env{'request.course.sec'}) {
 6766:           $courseprivid.='/'.$env{'request.course.sec'};
 6767:        }
 6768:        $courseprivid=~s/\_/\//;
 6769:        my $checkreferer=1;
 6770:        my ($match,$cond)=&is_on_map($uri);
 6771:        if ($match) {
 6772:            $statecond=$cond;
 6773:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6774:                =~/\Q$priv\E\&([^\:]*)/) {
 6775:                my $value = $1;
 6776:                if ($priv eq 'bre') {
 6777:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6778:                    if (@blockers > 0) {
 6779:                        $thisallowed = 'B';
 6780:                    } else {
 6781:                        $thisallowed.=$value;
 6782:                    }
 6783:                } else {
 6784:                    $thisallowed.=$value;
 6785:                }
 6786:                $checkreferer=0;
 6787:            }
 6788:        }
 6789:        
 6790:        if ($checkreferer) {
 6791: 	  my $refuri=$env{'httpref.'.$orguri};
 6792:             unless ($refuri) {
 6793:                 foreach my $key (keys(%env)) {
 6794: 		    if ($key=~/^httpref\..*\*/) {
 6795: 			my $pattern=$key;
 6796:                         $pattern=~s/^httpref\.\/res\///;
 6797:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6798:                         $pattern=~s/\//\\\//g;
 6799:                         if ($orguri=~/$pattern/) {
 6800: 			    $refuri=$env{$key};
 6801:                         }
 6802:                     }
 6803:                 }
 6804:             }
 6805: 
 6806:          if ($refuri) { 
 6807: 	  $refuri=&declutter($refuri);
 6808:           my ($match,$cond)=&is_on_map($refuri);
 6809:             if ($match) {
 6810:               my $refstatecond=$cond;
 6811:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6812:                   =~/\Q$priv\E\&([^\:]*)/) {
 6813:                   my $value = $1;
 6814:                   if ($priv eq 'bre') {
 6815:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6816:                       if (@blockers > 0) {
 6817:                           $thisallowed = 'B';
 6818:                       } else {
 6819:                           $thisallowed.=$value;
 6820:                       }
 6821:                   } else {
 6822:                       $thisallowed.=$value;
 6823:                   }
 6824:                   $uri=$refuri;
 6825:                   $statecond=$refstatecond;
 6826:               }
 6827:           }
 6828:         }
 6829:        }
 6830:    }
 6831: 
 6832: #
 6833: # Gathered now: all privileges that could apply, and condition number
 6834: # 
 6835: #
 6836: # Full or no access?
 6837: #
 6838: 
 6839:     if ($thisallowed=~/F/) {
 6840: 	return 'F';
 6841:     }
 6842: 
 6843:     unless ($thisallowed) {
 6844:         return '';
 6845:     }
 6846: 
 6847: # Restrictions exist, deal with them
 6848: #
 6849: #   C:according to course preferences
 6850: #   R:according to resource settings
 6851: #   L:unless locked
 6852: #   X:according to user session state
 6853: #
 6854: 
 6855: # Possibly locked functionality, check all courses
 6856: # Locks might take effect only after 10 minutes cache expiration for other
 6857: # courses, and 2 minutes for current course
 6858: 
 6859:     my $envkey;
 6860:     if ($thisallowed=~/L/) {
 6861:         foreach $envkey (keys(%env)) {
 6862:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6863:                my $courseid=$2;
 6864:                my $roleid=$1.'.'.$2;
 6865:                $courseid=~s/^\///;
 6866:                my $expiretime=600;
 6867:                if ($env{'request.role'} eq $roleid) {
 6868: 		  $expiretime=120;
 6869:                }
 6870: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6871:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6872:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6873: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6874:                }
 6875:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6876:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6877: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6878:                        &log($env{'user.domain'},$env{'user.name'},
 6879:                             $env{'user.home'},
 6880:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6881:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6882:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6883: 		       return '';
 6884:                    }
 6885:                }
 6886:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6887:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6888: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6889:                        &log($env{'user.domain'},$env{'user.name'},
 6890:                             $env{'user.home'},
 6891:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6892:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6893:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6894: 		       return '';
 6895:                    }
 6896:                }
 6897: 	   }
 6898:        }
 6899:     }
 6900:    
 6901: #
 6902: # Rest of the restrictions depend on selected course
 6903: #
 6904: 
 6905:     unless ($env{'request.course.id'}) {
 6906: 	if ($thisallowed eq 'A') {
 6907: 	    return 'A';
 6908:         } elsif ($thisallowed eq 'B') {
 6909:             return 'B';
 6910: 	} else {
 6911: 	    return '1';
 6912: 	}
 6913:     }
 6914: 
 6915: #
 6916: # Now user is definitely in a course
 6917: #
 6918: 
 6919: 
 6920: # Course preferences
 6921: 
 6922:    if ($thisallowed=~/C/) {
 6923:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6924:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6925:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6926: 	   =~/\Q$rolecode\E/) {
 6927: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6929: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6930: 			$env{'request.course.id'});
 6931: 	   }
 6932:            return '';
 6933:        }
 6934: 
 6935:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6936: 	   =~/\Q$unamedom\E/) {
 6937: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6938: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6939: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6940: 			$env{'request.course.id'});
 6941: 	   }
 6942:            return '';
 6943:        }
 6944:    }
 6945: 
 6946: # Resource preferences
 6947: 
 6948:    if ($thisallowed=~/R/) {
 6949:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6950:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6951: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6952: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6953: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6954: 	   }
 6955: 	   return '';
 6956:        }
 6957:    }
 6958: 
 6959: # Restricted by state or randomout?
 6960: 
 6961:    if ($thisallowed=~/X/) {
 6962:       if ($env{'acc.randomout'}) {
 6963: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6964:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6965:             return ''; 
 6966:          }
 6967:       }
 6968:       if (&condval($statecond)) {
 6969: 	 return '2';
 6970:       } else {
 6971:          return '';
 6972:       }
 6973:    }
 6974: 
 6975:     if ($thisallowed eq 'A') {
 6976: 	return 'A';
 6977:     } elsif ($thisallowed eq 'B') {
 6978:         return 'B';
 6979:     }
 6980:    return 'F';
 6981: }
 6982: 
 6983: # ------------------------------------------- Check construction space access
 6984: 
 6985: sub constructaccess {
 6986:     my ($url,$setpriv)=@_;
 6987: 
 6988: # We do not allow editing of previous versions of files
 6989:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6990: 
 6991: # Get username and domain from URL
 6992:     my ($ownername,$ownerdomain,$ownerhome);
 6993: 
 6994:     ($ownerdomain,$ownername) =
 6995:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6996: 
 6997: # The URL does not really point to any authorspace, forget it
 6998:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6999: 
 7000: # Now we need to see if the user has access to the authorspace of
 7001: # $ownername at $ownerdomain
 7002: 
 7003:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7004: # Real author for this?
 7005:        $ownerhome = $env{'user.home'};
 7006:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7007:           return ($ownername,$ownerdomain,$ownerhome);
 7008:        }
 7009:     } else {
 7010: # Co-author for this?
 7011:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7012:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7013:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7014:             return ($ownername,$ownerdomain,$ownerhome);
 7015:         }
 7016:     }
 7017: 
 7018: # We don't have any access right now. If we are not possibly going to do anything about this,
 7019: # we might as well leave
 7020:    unless ($setpriv) { return ''; }
 7021: 
 7022: # Backdoor access?
 7023:     my $allowed=&allowed('eco',$ownerdomain);
 7024: # Nope
 7025:     unless ($allowed) { return ''; }
 7026: # Looks like we may have access, but could be locked by the owner of the construction space
 7027:     if ($allowed eq 'U') {
 7028:         my %blocked=&get('environment',['domcoord.author'],
 7029:                          $ownerdomain,$ownername);
 7030: # Is blocked by owner
 7031:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7032:     }
 7033:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7034: # Grant temporary access
 7035:         my $then=$env{'user.login.time'};
 7036:         my $update=$env{'user.update.time'};
 7037:         if (!$update) { $update = $then; }
 7038:         my $refresh=$env{'user.refresh.time'};
 7039:         if (!$refresh) { $refresh = $update; }
 7040:         my $now = time;
 7041:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7042:                            $now,'ca','constructaccess');
 7043:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7044:         return($ownername,$ownerdomain,$ownerhome);
 7045:     }
 7046: # No business here
 7047:     return '';
 7048: }
 7049: 
 7050: sub get_comm_blocks {
 7051:     my ($cdom,$cnum) = @_;
 7052:     if ($cdom eq '' || $cnum eq '') {
 7053:         return unless ($env{'request.course.id'});
 7054:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7055:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7056:     }
 7057:     my %commblocks;
 7058:     my $hashid=$cdom.'_'.$cnum;
 7059:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7060:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7061:         %commblocks = %{$blocksref};
 7062:     } else {
 7063:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7064:         my $cachetime = 600;
 7065:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7066:     }
 7067:     return %commblocks;
 7068: }
 7069: 
 7070: sub has_comm_blocking {
 7071:     my ($priv,$symb,$uri,$blocks) = @_;
 7072:     return unless ($env{'request.course.id'});
 7073:     return unless ($priv eq 'bre');
 7074:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7075:     my %commblocks;
 7076:     if (ref($blocks) eq 'HASH') {
 7077:         %commblocks = %{$blocks};
 7078:     } else {
 7079:         %commblocks = &get_comm_blocks();
 7080:     }
 7081:     return unless (keys(%commblocks) > 0);
 7082:     if (!$symb) { $symb=&symbread($uri,1); }
 7083:     my ($map,$resid,undef)=&decode_symb($symb);
 7084:     my %tocheck = (
 7085:                     maps      => $map,
 7086:                     resources => $symb,
 7087:                   );
 7088:     my @blockers;
 7089:     my $now = time;
 7090:     my $navmap = Apache::lonnavmaps::navmap->new();
 7091:     foreach my $block (keys(%commblocks)) {
 7092:         if ($block =~ /^(\d+)____(\d+)$/) {
 7093:             my ($start,$end) = ($1,$2);
 7094:             if ($start <= $now && $end >= $now) {
 7095:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7096:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7097:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7098:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7099:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7100:                                     push(@blockers,$block);
 7101:                                 }
 7102:                             }
 7103:                         }
 7104:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7105:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7106:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7107:                                     push(@blockers,$block);
 7108:                                 }
 7109:                             }
 7110:                         }
 7111:                     }
 7112:                 }
 7113:             }
 7114:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7115:             my $item = $1;
 7116:             my @to_test;
 7117:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7118:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7119:                     my $check_interval;
 7120:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7121:                         my @interval;
 7122:                         my $type = 'map';
 7123:                         if ($item eq 'course') {
 7124:                             $type = 'course';
 7125:                             @interval=&EXT("resource.0.interval");
 7126:                         } else {
 7127:                             if ($item =~ /___\d+___/) {
 7128:                                 $type = 'resource';
 7129:                                 @interval=&EXT("resource.0.interval",$item);
 7130:                                 if (ref($navmap)) {                        
 7131:                                     my $res = $navmap->getBySymb($item); 
 7132:                                     push(@to_test,$res);
 7133:                                 }
 7134:                             } else {
 7135:                                 my $mapsymb = &symbread($item,1);
 7136:                                 if ($mapsymb) {
 7137:                                     if (ref($navmap)) {
 7138:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7139:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7140:                                         foreach my $res (@to_test) {
 7141:                                             my $symb = $res->symb();
 7142:                                             next if ($symb eq $mapsymb);
 7143:                                             if ($symb ne '') {
 7144:                                                 @interval=&EXT("resource.0.interval",$symb);
 7145:                                                 last;
 7146:                                             }
 7147:                                         }
 7148:                                     }
 7149:                                 }
 7150:                             }
 7151:                         }
 7152:                         if ($interval[0] =~ /\d+/) {
 7153:                             my $first_access;
 7154:                             if ($type eq 'resource') {
 7155:                                 $first_access=&get_first_access($interval[1],$item);
 7156:                             } elsif ($type eq 'map') {
 7157:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7158:                             } else {
 7159:                                 $first_access=&get_first_access($interval[1]);
 7160:                             }
 7161:                             if ($first_access) {
 7162:                                 my $timesup = $first_access+$interval[0];
 7163:                                 if ($timesup > $now) {
 7164:                                     foreach my $res (@to_test) {
 7165:                                         if ($res->is_problem()) {
 7166:                                             if ($res->completable()) {
 7167:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7168:                                                     push(@blockers,$block);
 7169:                                                 }
 7170:                                                 last;
 7171:                                             }
 7172:                                         }
 7173:                                     }
 7174:                                 }
 7175:                             }
 7176:                         }
 7177:                     }
 7178:                 }
 7179:             }
 7180:         }
 7181:     }
 7182:     return @blockers;
 7183: }
 7184: 
 7185: sub check_docs_block {
 7186:     my ($docsblock,$tocheck) =@_;
 7187:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7188:         return;
 7189:     }
 7190:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7191:         if ($tocheck->{'maps'}) {
 7192:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7193:                 return 1;
 7194:             }
 7195:         }
 7196:     }
 7197:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7198:         if ($tocheck->{'resources'}) {
 7199:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7200:                 return 1;
 7201:             }
 7202:         }
 7203:     }
 7204:     return;
 7205: }
 7206: 
 7207: #
 7208: #   Removes the versino from a URI and
 7209: #   splits it in to its filename and path to the filename.
 7210: #   Seems like File::Basename could have done this more clearly.
 7211: #   Parameters:
 7212: #      $uri   - input URI
 7213: #   Returns:
 7214: #     Two element list consisting of 
 7215: #     $pathname  - the URI up to and excluding the trailing /
 7216: #     $filename  - The part of the URI following the last /
 7217: #  NOTE:
 7218: #    Another realization of this is simply:
 7219: #    use File::Basename;
 7220: #    ...
 7221: #    $uri = shift;
 7222: #    $filename = basename($uri);
 7223: #    $path     = dirname($uri);
 7224: #    return ($filename, $path);
 7225: #
 7226: #     The implementation below is probably faster however.
 7227: #
 7228: sub split_uri_for_cond {
 7229:     my $uri=&deversion(&declutter(shift));
 7230:     my @uriparts=split(/\//,$uri);
 7231:     my $filename=pop(@uriparts);
 7232:     my $pathname=join('/',@uriparts);
 7233:     return ($pathname,$filename);
 7234: }
 7235: # --------------------------------------------------- Is a resource on the map?
 7236: 
 7237: sub is_on_map {
 7238:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7239:     #Trying to find the conditional for the file
 7240:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7241: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7242:     if ($match) {
 7243: 	return (1,$1);
 7244:     } else {
 7245: 	return (0,0);
 7246:     }
 7247: }
 7248: 
 7249: # --------------------------------------------------------- Get symb from alias
 7250: 
 7251: sub get_symb_from_alias {
 7252:     my $symb=shift;
 7253:     my ($map,$resid,$url)=&decode_symb($symb);
 7254: # Already is a symb
 7255:     if ($url) { return $symb; }
 7256: # Must be an alias
 7257:     my $aliassymb='';
 7258:     my %bighash;
 7259:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7260:                             &GDBM_READER(),0640)) {
 7261:         my $rid=$bighash{'mapalias_'.$symb};
 7262: 	if ($rid) {
 7263: 	    my ($mapid,$resid)=split(/\./,$rid);
 7264: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7265: 				    $resid,$bighash{'src_'.$rid});
 7266: 	}
 7267:         untie %bighash;
 7268:     }
 7269:     return $aliassymb;
 7270: }
 7271: 
 7272: # ----------------------------------------------------------------- Define Role
 7273: 
 7274: sub definerole {
 7275:   if (allowed('mcr','/')) {
 7276:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7277:     foreach my $role (split(':',$sysrole)) {
 7278: 	my ($crole,$cqual)=split(/\&/,$role);
 7279:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7280:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7281: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7282:                return "refused:s:$crole&$cqual"; 
 7283:             }
 7284:         }
 7285:     }
 7286:     foreach my $role (split(':',$domrole)) {
 7287: 	my ($crole,$cqual)=split(/\&/,$role);
 7288:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7289:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7290: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7291:                return "refused:d:$crole&$cqual"; 
 7292:             }
 7293:         }
 7294:     }
 7295:     foreach my $role (split(':',$courole)) {
 7296: 	my ($crole,$cqual)=split(/\&/,$role);
 7297:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7298:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7299: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7300:                return "refused:c:$crole&$cqual"; 
 7301:             }
 7302:         }
 7303:     }
 7304:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7305:                 "$env{'user.domain'}:$env{'user.name'}:".
 7306: 	        "rolesdef_$rolename=".
 7307:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7308:     return reply($command,$env{'user.home'});
 7309:   } else {
 7310:     return 'refused';
 7311:   }
 7312: }
 7313: 
 7314: # ---------------- Make a metadata query against the network of library servers
 7315: 
 7316: sub metadata_query {
 7317:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7318:     my %rhash;
 7319:     my %libserv = &all_library();
 7320:     my @server_list = (defined($server_array) ? @$server_array
 7321:                                               : keys(%libserv) );
 7322:     for my $server (@server_list) {
 7323:         my $domains = ''; 
 7324:         if (ref($domains_hash) eq 'HASH') {
 7325:             $domains = $domains_hash->{$server}; 
 7326:         }
 7327: 	unless ($custom or $customshow) {
 7328: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7329: 	    $rhash{$server}=$reply;
 7330: 	}
 7331: 	else {
 7332: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7333: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7334: 			     $server);
 7335: 	    $rhash{$server}=$reply;
 7336: 	}
 7337:     }
 7338:     return \%rhash;
 7339: }
 7340: 
 7341: # ----------------------------------------- Send log queries and wait for reply
 7342: 
 7343: sub log_query {
 7344:     my ($uname,$udom,$query,%filters)=@_;
 7345:     my $uhome=&homeserver($uname,$udom);
 7346:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7347:     my $uhost=&hostname($uhome);
 7348:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7349:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7350:                        $uhome);
 7351:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7352:     return get_query_reply($queryid);
 7353: }
 7354: 
 7355: # -------------------------- Update MySQL table for portfolio file
 7356: 
 7357: sub update_portfolio_table {
 7358:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7359:     if ($group ne '') {
 7360:         $file_name =~s /^\Q$group\E//;
 7361:     }
 7362:     my $homeserver = &homeserver($uname,$udom);
 7363:     my $queryid=
 7364:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7365:                ':'.&escape($file_name).':'.$action,$homeserver);
 7366:     my $reply = &get_query_reply($queryid);
 7367:     return $reply;
 7368: }
 7369: 
 7370: # -------------------------- Update MySQL allusers table
 7371: 
 7372: sub update_allusers_table {
 7373:     my ($uname,$udom,$names) = @_;
 7374:     my $homeserver = &homeserver($uname,$udom);
 7375:     my $queryid=
 7376:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7377:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7378:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7379:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7380:                'generation='.&escape($names->{'generation'}).'%%'.
 7381:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7382:                'id='.&escape($names->{'id'}),$homeserver);
 7383:     return;
 7384: }
 7385: 
 7386: # ------- Request retrieval of institutional classlists for course(s)
 7387: 
 7388: sub fetch_enrollment_query {
 7389:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7390:     my $homeserver;
 7391:     my $maxtries = 1;
 7392:     if ($context eq 'automated') {
 7393:         $homeserver = $perlvar{'lonHostID'};
 7394:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7395:     } else {
 7396:         $homeserver = &homeserver($cnum,$dom);
 7397:     }
 7398:     my $host=&hostname($homeserver);
 7399:     my $cmd = '';
 7400:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7401:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7402:     }
 7403:     $cmd =~ s/%%$//;
 7404:     $cmd = &escape($cmd);
 7405:     my $query = 'fetchenrollment';
 7406:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7407:     unless ($queryid=~/^\Q$host\E\_/) { 
 7408:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7409:         return 'error: '.$queryid;
 7410:     }
 7411:     my $reply = &get_query_reply($queryid);
 7412:     my $tries = 1;
 7413:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7414:         $reply = &get_query_reply($queryid);
 7415:         $tries ++;
 7416:     }
 7417:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7418:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7419:     } else {
 7420:         my @responses = split(/:/,$reply);
 7421:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7422:             foreach my $line (@responses) {
 7423:                 my ($key,$value) = split(/=/,$line,2);
 7424:                 $$replyref{$key} = $value;
 7425:             }
 7426:         } else {
 7427:             my $pathname = LONCAPA::tempdir();
 7428:             foreach my $line (@responses) {
 7429:                 my ($key,$value) = split(/=/,$line);
 7430:                 $$replyref{$key} = $value;
 7431:                 if ($value > 0) {
 7432:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7433:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7434:                         my $destname = $pathname.'/'.$filename;
 7435:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7436:                         if ($xml_classlist =~ /^error/) {
 7437:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7438:                         } else {
 7439:                             if ( open(FILE,">$destname") ) {
 7440:                                 print FILE &unescape($xml_classlist);
 7441:                                 close(FILE);
 7442:                             } else {
 7443:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7444:                             }
 7445:                         }
 7446:                     }
 7447:                 }
 7448:             }
 7449:         }
 7450:         return 'ok';
 7451:     }
 7452:     return 'error';
 7453: }
 7454: 
 7455: sub get_query_reply {
 7456:     my $queryid=shift;
 7457:     my $replyfile=LONCAPA::tempdir().$queryid;
 7458:     my $reply='';
 7459:     for (1..100) {
 7460: 	sleep 2;
 7461:         if (-e $replyfile.'.end') {
 7462: 	    if (open(my $fh,$replyfile)) {
 7463: 		$reply = join('',<$fh>);
 7464: 		close($fh);
 7465: 	   } else { return 'error: reply_file_error'; }
 7466:            return &unescape($reply);
 7467: 	}
 7468:     }
 7469:     return 'timeout:'.$queryid;
 7470: }
 7471: 
 7472: sub courselog_query {
 7473: #
 7474: # possible filters:
 7475: # url: url or symb
 7476: # username
 7477: # domain
 7478: # action: view, submit, grade
 7479: # start: timestamp
 7480: # end: timestamp
 7481: #
 7482:     my (%filters)=@_;
 7483:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7484:     if ($filters{'url'}) {
 7485: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7486:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7487:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7488:     }
 7489:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7490:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7491:     return &log_query($cname,$cdom,'courselog',%filters);
 7492: }
 7493: 
 7494: sub userlog_query {
 7495: #
 7496: # possible filters:
 7497: # action: log check role
 7498: # start: timestamp
 7499: # end: timestamp
 7500: #
 7501:     my ($uname,$udom,%filters)=@_;
 7502:     return &log_query($uname,$udom,'userlog',%filters);
 7503: }
 7504: 
 7505: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7506: 
 7507: sub auto_run {
 7508:     my ($cnum,$cdom) = @_;
 7509:     my $response = 0;
 7510:     my $settings;
 7511:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7512:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7513:         $settings = $domconfig{'autoenroll'};
 7514:         if ($settings->{'run'} eq '1') {
 7515:             $response = 1;
 7516:         }
 7517:     } else {
 7518:         my $homeserver;
 7519:         if (&is_course($cdom,$cnum)) {
 7520:             $homeserver = &homeserver($cnum,$cdom);
 7521:         } else {
 7522:             $homeserver = &domain($cdom,'primary');
 7523:         }
 7524:         if ($homeserver ne 'no_host') {
 7525:             $response = &reply('autorun:'.$cdom,$homeserver);
 7526:         }
 7527:     }
 7528:     return $response;
 7529: }
 7530: 
 7531: sub auto_get_sections {
 7532:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7533:     my $homeserver;
 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:     my @secs;
 7543:     if (defined($homeserver)) {
 7544:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7545:         unless ($response eq 'refused') {
 7546:             @secs = split(/:/,$response);
 7547:         }
 7548:     }
 7549:     return @secs;
 7550: }
 7551: 
 7552: sub auto_new_course {
 7553:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7554:     my $homeserver = &homeserver($cnum,$cdom);
 7555:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7556:     return $response;
 7557: }
 7558: 
 7559: sub auto_validate_courseID {
 7560:     my ($cnum,$cdom,$inst_course_id) = @_;
 7561:     my $homeserver = &homeserver($cnum,$cdom);
 7562:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7563:     return $response;
 7564: }
 7565: 
 7566: sub auto_validate_instcode {
 7567:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7568:     my ($homeserver,$response);
 7569:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7570:         $homeserver = &homeserver($cnum,$cdom);
 7571:     }
 7572:     if (!defined($homeserver)) {
 7573:         if ($cdom =~ /^$match_domain$/) {
 7574:             $homeserver = &domain($cdom,'primary');
 7575:         }
 7576:     }
 7577:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7578:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7579:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7580:     return ($outcome,$description,$defaultcredits);
 7581: }
 7582: 
 7583: sub auto_create_password {
 7584:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7585:     my ($homeserver,$response);
 7586:     my $create_passwd = 0;
 7587:     my $authchk = '';
 7588:     if ($udom =~ /^$match_domain$/) {
 7589:         $homeserver = &domain($udom,'primary');
 7590:     }
 7591:     if ($homeserver eq '') {
 7592:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7593:             $homeserver = &homeserver($cnum,$cdom);
 7594:         }
 7595:     }
 7596:     if ($homeserver eq '') {
 7597:         $authchk = 'nodomain';
 7598:     } else {
 7599:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7600:         if ($response eq 'refused') {
 7601:             $authchk = 'refused';
 7602:         } else {
 7603:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7604:         }
 7605:     }
 7606:     return ($authparam,$create_passwd,$authchk);
 7607: }
 7608: 
 7609: sub auto_photo_permission {
 7610:     my ($cnum,$cdom,$students) = @_;
 7611:     my $homeserver = &homeserver($cnum,$cdom);
 7612:     my ($outcome,$perm_reqd,$conditions) = 
 7613: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7614:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7615: 	return (undef,undef);
 7616:     }
 7617:     return ($outcome,$perm_reqd,$conditions);
 7618: }
 7619: 
 7620: sub auto_checkphotos {
 7621:     my ($uname,$udom,$pid) = @_;
 7622:     my $homeserver = &homeserver($uname,$udom);
 7623:     my ($result,$resulttype);
 7624:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7625: 				   &escape($uname).':'.&escape($pid),
 7626: 				   $homeserver));
 7627:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7628: 	return (undef,undef);
 7629:     }
 7630:     if ($outcome) {
 7631:         ($result,$resulttype) = split(/:/,$outcome);
 7632:     } 
 7633:     return ($result,$resulttype);
 7634: }
 7635: 
 7636: sub auto_photochoice {
 7637:     my ($cnum,$cdom) = @_;
 7638:     my $homeserver = &homeserver($cnum,$cdom);
 7639:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7640: 						       &escape($cdom),
 7641: 						       $homeserver)));
 7642:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7643: 	return (undef,undef);
 7644:     }
 7645:     return ($update,$comment);
 7646: }
 7647: 
 7648: sub auto_photoupdate {
 7649:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7650:     my $homeserver = &homeserver($cnum,$dom);
 7651:     my $host=&hostname($homeserver);
 7652:     my $cmd = '';
 7653:     my $maxtries = 1;
 7654:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7655:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7656:     }
 7657:     $cmd =~ s/%%$//;
 7658:     $cmd = &escape($cmd);
 7659:     my $query = 'institutionalphotos';
 7660:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7661:     unless ($queryid=~/^\Q$host\E\_/) {
 7662:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7663:         return 'error: '.$queryid;
 7664:     }
 7665:     my $reply = &get_query_reply($queryid);
 7666:     my $tries = 1;
 7667:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7668:         $reply = &get_query_reply($queryid);
 7669:         $tries ++;
 7670:     }
 7671:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7672:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7673:     } else {
 7674:         my @responses = split(/:/,$reply);
 7675:         my $outcome = shift(@responses); 
 7676:         foreach my $item (@responses) {
 7677:             my ($key,$value) = split(/=/,$item);
 7678:             $$photo{$key} = $value;
 7679:         }
 7680:         return $outcome;
 7681:     }
 7682:     return 'error';
 7683: }
 7684: 
 7685: sub auto_instcode_format {
 7686:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7687: 	$cat_order) = @_;
 7688:     my $courses = '';
 7689:     my @homeservers;
 7690:     if ($caller eq 'global') {
 7691: 	my %servers = &get_servers($codedom,'library');
 7692: 	foreach my $tryserver (keys(%servers)) {
 7693: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7694: 		push(@homeservers,$tryserver);
 7695: 	    }
 7696:         }
 7697:     } elsif ($caller eq 'requests') {
 7698:         if ($codedom =~ /^$match_domain$/) {
 7699:             my $chome = &domain($codedom,'primary');
 7700:             unless ($chome eq 'no_host') {
 7701:                 push(@homeservers,$chome);
 7702:             }
 7703:         }
 7704:     } else {
 7705:         push(@homeservers,&homeserver($caller,$codedom));
 7706:     }
 7707:     foreach my $code (keys(%{$instcodes})) {
 7708:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7709:     }
 7710:     chop($courses);
 7711:     my $ok_response = 0;
 7712:     my $response;
 7713:     while (@homeservers > 0 && $ok_response == 0) {
 7714:         my $server = shift(@homeservers); 
 7715:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7716:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7717:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7718: 		split(/:/,$response);
 7719:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7720:             push(@{$codetitles},&str2array($codetitles_str));
 7721:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7722:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7723:             $ok_response = 1;
 7724:         }
 7725:     }
 7726:     if ($ok_response) {
 7727:         return 'ok';
 7728:     } else {
 7729:         return $response;
 7730:     }
 7731: }
 7732: 
 7733: sub auto_instcode_defaults {
 7734:     my ($domain,$returnhash,$code_order) = @_;
 7735:     my @homeservers;
 7736: 
 7737:     my %servers = &get_servers($domain,'library');
 7738:     foreach my $tryserver (keys(%servers)) {
 7739: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7740: 	    push(@homeservers,$tryserver);
 7741: 	}
 7742:     }
 7743: 
 7744:     my $response;
 7745:     foreach my $server (@homeservers) {
 7746:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7747:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7748: 	
 7749: 	foreach my $pair (split(/\&/,$response)) {
 7750: 	    my ($name,$value)=split(/\=/,$pair);
 7751: 	    if ($name eq 'code_order') {
 7752: 		@{$code_order} = split(/\&/,&unescape($value));
 7753: 	    } else {
 7754: 		$returnhash->{&unescape($name)}=&unescape($value);
 7755: 	    }
 7756: 	}
 7757: 	return 'ok';
 7758:     }
 7759: 
 7760:     return $response;
 7761: }
 7762: 
 7763: sub auto_possible_instcodes {
 7764:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7765:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7766:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7767:         return;
 7768:     }
 7769:     my (@homeservers,$uhome);
 7770:     if (defined(&domain($domain,'primary'))) {
 7771:         $uhome=&domain($domain,'primary');
 7772:         push(@homeservers,&domain($domain,'primary'));
 7773:     } else {
 7774:         my %servers = &get_servers($domain,'library');
 7775:         foreach my $tryserver (keys(%servers)) {
 7776:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7777:                 push(@homeservers,$tryserver);
 7778:             }
 7779:         }
 7780:     }
 7781:     my $response;
 7782:     foreach my $server (@homeservers) {
 7783:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7784:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7785:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7786:             split(':',$response);
 7787:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7788:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7789:         foreach my $item (split('&',$cat_title)) {   
 7790:             my ($name,$value)=split('=',$item);
 7791:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7792:         }
 7793:         foreach my $item (split('&',$cat_order)) {
 7794:             my ($name,$value)=split('=',$item);
 7795:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7796:         }
 7797:         return 'ok';
 7798:     }
 7799:     return $response;
 7800: }
 7801: 
 7802: sub auto_courserequest_checks {
 7803:     my ($dom) = @_;
 7804:     my ($homeserver,%validations);
 7805:     if ($dom =~ /^$match_domain$/) {
 7806:         $homeserver = &domain($dom,'primary');
 7807:     }
 7808:     unless ($homeserver eq 'no_host') {
 7809:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7810:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7811:             my @items = split(/&/,$response);
 7812:             foreach my $item (@items) {
 7813:                 my ($key,$value) = split('=',$item);
 7814:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7815:             }
 7816:         }
 7817:     }
 7818:     return %validations; 
 7819: }
 7820: 
 7821: sub auto_courserequest_validation {
 7822:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7823:     my ($homeserver,$response);
 7824:     if ($dom =~ /^$match_domain$/) {
 7825:         $homeserver = &domain($dom,'primary');
 7826:     }
 7827:     unless ($homeserver eq 'no_host') {  
 7828:           
 7829:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7830:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7831:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7832:                                     $homeserver));
 7833:     }
 7834:     return $response;
 7835: }
 7836: 
 7837: sub auto_validate_class_sec {
 7838:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7839:     my $homeserver = &homeserver($cnum,$cdom);
 7840:     my $ownerlist;
 7841:     if (ref($owners) eq 'ARRAY') {
 7842:         $ownerlist = join(',',@{$owners});
 7843:     } else {
 7844:         $ownerlist = $owners;
 7845:     }
 7846:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7847:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7848:     return $response;
 7849: }
 7850: 
 7851: # ------------------------------------------------------- Course Group routines
 7852: 
 7853: sub get_coursegroups {
 7854:     my ($cdom,$cnum,$group,$namespace) = @_;
 7855:     return(&dump($namespace,$cdom,$cnum,$group));
 7856: }
 7857: 
 7858: sub modify_coursegroup {
 7859:     my ($cdom,$cnum,$groupsettings) = @_;
 7860:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7861: }
 7862: 
 7863: sub toggle_coursegroup_status {
 7864:     my ($cdom,$cnum,$group,$action) = @_;
 7865:     my ($from_namespace,$to_namespace);
 7866:     if ($action eq 'delete') {
 7867:         $from_namespace = 'coursegroups';
 7868:         $to_namespace = 'deleted_groups';
 7869:     } else {
 7870:         $from_namespace = 'deleted_groups';
 7871:         $to_namespace = 'coursegroups';
 7872:     }
 7873:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7874:     if (my $tmp = &error(%curr_group)) {
 7875:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7876:         return ('read error',$tmp);
 7877:     } else {
 7878:         my %savedsettings = %curr_group; 
 7879:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7880:         my $deloutcome;
 7881:         if ($result eq 'ok') {
 7882:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7883:         } else {
 7884:             return ('write error',$result);
 7885:         }
 7886:         if ($deloutcome eq 'ok') {
 7887:             return 'ok';
 7888:         } else {
 7889:             return ('delete error',$deloutcome);
 7890:         }
 7891:     }
 7892: }
 7893: 
 7894: sub modify_group_roles {
 7895:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7896:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7897:     my $role = 'gr/'.&escape($userprivs);
 7898:     my ($uname,$udom) = split(/:/,$user);
 7899:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7900:     if ($result eq 'ok') {
 7901:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7902:     }
 7903:     return $result;
 7904: }
 7905: 
 7906: sub modify_coursegroup_membership {
 7907:     my ($cdom,$cnum,$membership) = @_;
 7908:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7909:     return $result;
 7910: }
 7911: 
 7912: sub get_active_groups {
 7913:     my ($udom,$uname,$cdom,$cnum) = @_;
 7914:     my $now = time;
 7915:     my %groups = ();
 7916:     foreach my $key (keys(%env)) {
 7917:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7918:             my ($start,$end) = split(/\./,$env{$key});
 7919:             if (($end!=0) && ($end<$now)) { next; }
 7920:             if (($start!=0) && ($start>$now)) { next; }
 7921:             if ($1 eq $cdom && $2 eq $cnum) {
 7922:                 $groups{$3} = $env{$key} ;
 7923:             }
 7924:         }
 7925:     }
 7926:     return %groups;
 7927: }
 7928: 
 7929: sub get_group_membership {
 7930:     my ($cdom,$cnum,$group) = @_;
 7931:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7932: }
 7933: 
 7934: sub get_users_groups {
 7935:     my ($udom,$uname,$courseid) = @_;
 7936:     my @usersgroups;
 7937:     my $cachetime=1800;
 7938: 
 7939:     my $hashid="$udom:$uname:$courseid";
 7940:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7941:     if (defined($cached)) {
 7942:         @usersgroups = split(/:/,$grouplist);
 7943:     } else {  
 7944:         $grouplist = '';
 7945:         my $courseurl = &courseid_to_courseurl($courseid);
 7946:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7947:         my $access_end = $env{'course.'.$courseid.
 7948:                               '.default_enrollment_end_date'};
 7949:         my $now = time;
 7950:         foreach my $key (keys(%roleshash)) {
 7951:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7952:                 my $group = $1;
 7953:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7954:                     my $start = $2;
 7955:                     my $end = $1;
 7956:                     if ($start == -1) { next; } # deleted from group
 7957:                     if (($start!=0) && ($start>$now)) { next; }
 7958:                     if (($end!=0) && ($end<$now)) {
 7959:                         if ($access_end && $access_end < $now) {
 7960:                             if ($access_end - $end < 86400) {
 7961:                                 push(@usersgroups,$group);
 7962:                             }
 7963:                         }
 7964:                         next;
 7965:                     }
 7966:                     push(@usersgroups,$group);
 7967:                 }
 7968:             }
 7969:         }
 7970:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7971:         $grouplist = join(':',@usersgroups);
 7972:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7973:     }
 7974:     return @usersgroups;
 7975: }
 7976: 
 7977: sub devalidate_getgroups_cache {
 7978:     my ($udom,$uname,$cdom,$cnum)=@_;
 7979:     my $courseid = $cdom.'_'.$cnum;
 7980: 
 7981:     my $hashid="$udom:$uname:$courseid";
 7982:     &devalidate_cache_new('getgroups',$hashid);
 7983: }
 7984: 
 7985: # ------------------------------------------------------------------ Plain Text
 7986: 
 7987: sub plaintext {
 7988:     my ($short,$type,$cid,$forcedefault) = @_;
 7989:     if ($short =~ m{^cr/}) {
 7990: 	return (split('/',$short))[-1];
 7991:     }
 7992:     if (!defined($cid)) {
 7993:         $cid = $env{'request.course.id'};
 7994:     }
 7995:     my %rolenames = (
 7996:                       Course    => 'std',
 7997:                       Community => 'alt1',
 7998:                     );
 7999:     if ($cid ne '') {
 8000:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8001:             unless ($forcedefault) {
 8002:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8003:                 &Apache::lonlocal::mt_escape(\$roletext);
 8004:                 return &Apache::lonlocal::mt($roletext);
 8005:             }
 8006:         }
 8007:     }
 8008:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8009:         (defined($rolenames{$type})) && 
 8010:         (defined($prp{$short}{$rolenames{$type}}))) {
 8011:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8012:     } elsif ($cid ne '') {
 8013:         my $crstype = $env{'course.'.$cid.'.type'};
 8014:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8015:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8016:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8017:         }
 8018:     }
 8019:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8020: }
 8021: 
 8022: # ----------------------------------------------------------------- Assign Role
 8023: 
 8024: sub assignrole {
 8025:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8026:         $context)=@_;
 8027:     my $mrole;
 8028:     if ($role =~ /^cr\//) {
 8029:         my $cwosec=$url;
 8030:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8031: 	unless (&allowed('ccr',$cwosec)) {
 8032:            my $refused = 1;
 8033:            if ($context eq 'requestcourses') {
 8034:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8035:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8036:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8037:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8038:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8039:                            if ($crsenv{'internal.courseowner'} eq
 8040:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8041:                                $refused = '';
 8042:                            }
 8043:                        }
 8044:                    }
 8045:                }
 8046:            }
 8047:            if ($refused) {
 8048:                &logthis('Refused custom assignrole: '.
 8049:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8050:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8051:                return 'refused';
 8052:            }
 8053:         }
 8054:         $mrole='cr';
 8055:     } elsif ($role =~ /^gr\//) {
 8056:         my $cwogrp=$url;
 8057:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8058:         unless (&allowed('mdg',$cwogrp)) {
 8059:             &logthis('Refused group assignrole: '.
 8060:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8061:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8062:             return 'refused';
 8063:         }
 8064:         $mrole='gr';
 8065:     } else {
 8066:         my $cwosec=$url;
 8067:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8068:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8069:             my $refused;
 8070:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8071:                 if (!(&allowed('c'.$role,$url))) {
 8072:                     $refused = 1;
 8073:                 }
 8074:             } else {
 8075:                 $refused = 1;
 8076:             }
 8077:             if ($refused) {
 8078:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8079:                 if (!$selfenroll && $context eq 'course') {
 8080:                     my %crsenv;
 8081:                     if ($role eq 'cc' || $role eq 'co') {
 8082:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8083:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8084:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8085:                                 if ($crsenv{'internal.courseowner'} eq 
 8086:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8087:                                     $refused = '';
 8088:                                 }
 8089:                             }
 8090:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8091:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8092:                                 if ($crsenv{'internal.courseowner'} eq 
 8093:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8094:                                     $refused = '';
 8095:                                 }
 8096:                             }
 8097:                         }
 8098:                     }
 8099:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8100:                     $refused = '';
 8101:                 } elsif ($context eq 'requestcourses') {
 8102:                     my @possroles = ('st','ta','ep','in','cc','co');
 8103:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8104:                         my $wrongcc;
 8105:                         if ($cnum =~ /^$match_community$/) {
 8106:                             $wrongcc = 1 if ($role eq 'cc');
 8107:                         } else {
 8108:                             $wrongcc = 1 if ($role eq 'co');
 8109:                         }
 8110:                         unless ($wrongcc) {
 8111:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8112:                             if ($crsenv{'internal.courseowner'} eq 
 8113:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8114:                                 $refused = '';
 8115:                             }
 8116:                         }
 8117:                     }
 8118:                 } elsif ($context eq 'requestauthor') {
 8119:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8120:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8121:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8122:                             $refused = '';
 8123:                         } else {
 8124:                             my %domdefaults = &get_domain_defaults($udom);
 8125:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8126:                                 my $checkbystatus;
 8127:                                 if ($env{'user.adv'}) { 
 8128:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8129:                                     if ($disposition eq 'automatic') {
 8130:                                         $refused = '';
 8131:                                     } elsif ($disposition eq '') {
 8132:                                         $checkbystatus = 1;
 8133:                                     } 
 8134:                                 } else {
 8135:                                     $checkbystatus = 1;
 8136:                                 }
 8137:                                 if ($checkbystatus) {
 8138:                                     if ($env{'environment.inststatus'}) {
 8139:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8140:                                         foreach my $type (@inststatuses) {
 8141:                                             if (($type ne '') &&
 8142:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8143:                                                 $refused = '';
 8144:                                             }
 8145:                                         }
 8146:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8147:                                         $refused = '';
 8148:                                     }
 8149:                                 }
 8150:                             }
 8151:                         }
 8152:                     }
 8153:                 }
 8154:                 if ($refused) {
 8155:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8156:                              ' '.$role.' '.$end.' '.$start.' by '.
 8157: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8158:                     return 'refused';
 8159:                 }
 8160:             }
 8161:         } elsif ($role eq 'au') {
 8162:             if ($url ne '/'.$udom.'/') {
 8163:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8164:                          ' to assign author role for '.$uname.':'.$udom.
 8165:                          ' in domain: '.$url.' refused (wrong domain).');
 8166:                 return 'refused';
 8167:             }
 8168:         }
 8169:         $mrole=$role;
 8170:     }
 8171:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8172:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8173:     if ($end) { $command.='_'.$end; }
 8174:     if ($start) {
 8175: 	if ($end) { 
 8176:            $command.='_'.$start; 
 8177:         } else {
 8178:            $command.='_0_'.$start;
 8179:         }
 8180:     }
 8181:     my $origstart = $start;
 8182:     my $origend = $end;
 8183:     my $delflag;
 8184: # actually delete
 8185:     if ($deleteflag) {
 8186: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8187: # modify command to delete the role
 8188:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8189:                 "$udom:$uname:$url".'_'."$mrole";
 8190: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8191: # set start and finish to negative values for userrolelog
 8192:            $start=-1;
 8193:            $end=-1;
 8194:            $delflag = 1;
 8195:         }
 8196:     }
 8197: # send command
 8198:     my $answer=&reply($command,&homeserver($uname,$udom));
 8199: # log new user role if status is ok
 8200:     if ($answer eq 'ok') {
 8201: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8202:         if (($role eq 'cc') || ($role eq 'in') ||
 8203:             ($role eq 'ep') || ($role eq 'ad') ||
 8204:             ($role eq 'ta') || ($role eq 'st') ||
 8205:             ($role=~/^cr/) || ($role eq 'gr') ||
 8206:             ($role eq 'co')) {
 8207: # for course roles, perform group memberships changes triggered by role change.
 8208:             unless ($role =~ /^gr/) {
 8209:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8210:                                                  $origstart,$selfenroll,$context);
 8211:             }
 8212:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8213:                            $selfenroll,$context);
 8214:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8215:                  ($role eq 'au') || ($role eq 'dc')) {
 8216:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8217:                            $context);
 8218:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8219:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8220:                              $context); 
 8221:         }
 8222:         if ($role eq 'cc') {
 8223:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8224:         }
 8225:     }
 8226:     return $answer;
 8227: }
 8228: 
 8229: sub autoupdate_coowners {
 8230:     my ($url,$end,$start,$uname,$udom) = @_;
 8231:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8232:     if (($cdom ne '') && ($cnum ne '')) {
 8233:         my $now = time;
 8234:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8235:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8236:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8237:             my $instcode = $coursehash{'internal.coursecode'};
 8238:             if ($instcode ne '') {
 8239:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8240:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8241:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8242:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8243:                         if ($result eq 'valid') {
 8244:                             if ($coursehash{'internal.co-owners'}) {
 8245:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8246:                                     push(@newcoowners,$coowner);
 8247:                                 }
 8248:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8249:                                     push(@newcoowners,$uname.':'.$udom);
 8250:                                 }
 8251:                                 @newcoowners = sort(@newcoowners);
 8252:                             } else {
 8253:                                 push(@newcoowners,$uname.':'.$udom);
 8254:                             }
 8255:                         } else {
 8256:                             if ($coursehash{'internal.co-owners'}) {
 8257:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8258:                                     unless ($coowner eq $uname.':'.$udom) {
 8259:                                         push(@newcoowners,$coowner);
 8260:                                     }
 8261:                                 }
 8262:                                 unless (@newcoowners > 0) {
 8263:                                     $delcoowners = 1;
 8264:                                     $coowners = '';
 8265:                                 }
 8266:                             }
 8267:                         }
 8268:                         if (@newcoowners || $delcoowners) {
 8269:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8270:                                             $delcoowners,@newcoowners);
 8271:                         }
 8272:                     }
 8273:                 }
 8274:             }
 8275:         }
 8276:     }
 8277: }
 8278: 
 8279: sub store_coowners {
 8280:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8281:     my $cid = $cdom.'_'.$cnum;
 8282:     my ($coowners,$delresult,$putresult);
 8283:     if (@newcoowners) {
 8284:         $coowners = join(',',@newcoowners);
 8285:         my %coownershash = (
 8286:                             'internal.co-owners' => $coowners,
 8287:                            );
 8288:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8289:         if ($putresult eq 'ok') {
 8290:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8291:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8292:             }
 8293:         }
 8294:     }
 8295:     if ($delcoowners) {
 8296:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8297:         if ($delresult eq 'ok') {
 8298:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8299:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8300:             }
 8301:         }
 8302:     }
 8303:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8304:         my %crsinfo =
 8305:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8306:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8307:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8308:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8309:         }
 8310:     }
 8311: }
 8312: 
 8313: # -------------------------------------------------- Modify user authentication
 8314: # Overrides without validation
 8315: 
 8316: sub modifyuserauth {
 8317:     my ($udom,$uname,$umode,$upass)=@_;
 8318:     my $uhome=&homeserver($uname,$udom);
 8319:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8320:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8321:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8322:              ' in domain '.$env{'request.role.domain'});  
 8323:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8324: 		     &escape($upass),$uhome);
 8325:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8326:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8327:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8328:     &log($udom,,$uname,$uhome,
 8329:         'Authentication changed by '.$env{'user.domain'}.', '.
 8330:                                      $env{'user.name'}.', '.$umode.
 8331:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8332:     unless ($reply eq 'ok') {
 8333:         &logthis('Authentication mode error: '.$reply);
 8334: 	return 'error: '.$reply;
 8335:     }   
 8336:     return 'ok';
 8337: }
 8338: 
 8339: # --------------------------------------------------------------- Modify a user
 8340: 
 8341: sub modifyuser {
 8342:     my ($udom,    $uname, $uid,
 8343:         $umode,   $upass, $first,
 8344:         $middle,  $last,  $gene,
 8345:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8346:     $udom= &LONCAPA::clean_domain($udom);
 8347:     $uname=&LONCAPA::clean_username($uname);
 8348:     my $showcandelete = 'none';
 8349:     if (ref($candelete) eq 'ARRAY') {
 8350:         if (@{$candelete} > 0) {
 8351:             $showcandelete = join(', ',@{$candelete});
 8352:         }
 8353:     }
 8354:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8355:              $umode.', '.$first.', '.$middle.', '.
 8356: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8357:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8358:                                      ' desiredhome not specified'). 
 8359:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8360:              ' in domain '.$env{'request.role.domain'});
 8361:     my $uhome=&homeserver($uname,$udom,'true');
 8362:     my $newuser;
 8363:     if ($uhome eq 'no_host') {
 8364:         $newuser = 1;
 8365:     }
 8366: # ----------------------------------------------------------------- Create User
 8367:     if (($uhome eq 'no_host') && 
 8368: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8369:         my $unhome='';
 8370:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8371:             $unhome = $desiredhome;
 8372: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8373: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8374:         } else { # load balancing routine for determining $unhome
 8375:             my $loadm=10000000;
 8376: 	    my %servers = &get_servers($udom,'library');
 8377: 	    foreach my $tryserver (keys(%servers)) {
 8378: 		my $answer=reply('load',$tryserver);
 8379: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8380: 		    $loadm=$answer;
 8381: 		    $unhome=$tryserver;
 8382: 		}
 8383: 	    }
 8384:         }
 8385:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8386: 	    return 'error: unable to find a home server for '.$uname.
 8387:                    ' in domain '.$udom;
 8388:         }
 8389:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8390:                          &escape($upass),$unhome);
 8391: 	unless ($reply eq 'ok') {
 8392:             return 'error: '.$reply;
 8393:         }   
 8394:         $uhome=&homeserver($uname,$udom,'true');
 8395:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8396: 	    return 'error: unable verify users home machine.';
 8397:         }
 8398:     }   # End of creation of new user
 8399: # ---------------------------------------------------------------------- Add ID
 8400:     if ($uid) {
 8401:        $uid=~tr/A-Z/a-z/;
 8402:        my %uidhash=&idrget($udom,$uname);
 8403:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8404:          && (!$forceid)) {
 8405: 	  unless ($uid eq $uidhash{$uname}) {
 8406: 	      return 'error: user id "'.$uid.'" does not match '.
 8407:                   'current user id "'.$uidhash{$uname}.'".';
 8408:           }
 8409:        } else {
 8410: 	  &idput($udom,($uname => $uid));
 8411:        }
 8412:     }
 8413: # -------------------------------------------------------------- Add names, etc
 8414:     my @tmp=&get('environment',
 8415: 		   ['firstname','middlename','lastname','generation','id',
 8416:                     'permanentemail','inststatus'],
 8417: 		   $udom,$uname);
 8418:     my (%names,%oldnames);
 8419:     if ($tmp[0] =~ m/^error:.*/) { 
 8420:         %names=(); 
 8421:     } else {
 8422:         %names = @tmp;
 8423:         %oldnames = %names;
 8424:     }
 8425: #
 8426: # If name, email and/or uid are blank (e.g., because an uploaded file
 8427: # of users did not contain them), do not overwrite existing values
 8428: # unless field is in $candelete array ref.  
 8429: #
 8430: 
 8431:     my @fields = ('firstname','middlename','lastname','generation',
 8432:                   'permanentemail','id');
 8433:     my %newvalues;
 8434:     if (ref($candelete) eq 'ARRAY') {
 8435:         foreach my $field (@fields) {
 8436:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8437:                 if ($field eq 'firstname') {
 8438:                     $names{$field} = $first;
 8439:                 } elsif ($field eq 'middlename') {
 8440:                     $names{$field} = $middle;
 8441:                 } elsif ($field eq 'lastname') {
 8442:                     $names{$field} = $last;
 8443:                 } elsif ($field eq 'generation') { 
 8444:                     $names{$field} = $gene;
 8445:                 } elsif ($field eq 'permanentemail') {
 8446:                     $names{$field} = $email;
 8447:                 } elsif ($field eq 'id') {
 8448:                     $names{$field}  = $uid;
 8449:                 }
 8450:             }
 8451:         }
 8452:     }
 8453:     if ($first)  { $names{'firstname'}  = $first; }
 8454:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8455:     if ($last)   { $names{'lastname'}   = $last; }
 8456:     if (defined($gene))   { $names{'generation'} = $gene; }
 8457:     if ($email) {
 8458:        $email=~s/[^\w\@\.\-\,]//gs;
 8459:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8460:     }
 8461:     if ($uid) { $names{'id'}  = $uid; }
 8462:     if (defined($inststatus)) {
 8463:         $names{'inststatus'} = '';
 8464:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8465:         if (ref($usertypes) eq 'HASH') {
 8466:             my @okstatuses; 
 8467:             foreach my $item (split(/:/,$inststatus)) {
 8468:                 if (defined($usertypes->{$item})) {
 8469:                     push(@okstatuses,$item);  
 8470:                 }
 8471:             }
 8472:             if (@okstatuses) {
 8473:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8474:             }
 8475:         }
 8476:     }
 8477:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8478:                  $umode.', '.$first.', '.$middle.', '.
 8479:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8480:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8481:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8482:     } else {
 8483:         $logmsg .= ' during self creation';
 8484:     }
 8485:     my $changed;
 8486:     if ($newuser) {
 8487:         $changed = 1;
 8488:     } else {
 8489:         foreach my $field (@fields) {
 8490:             if ($names{$field} ne $oldnames{$field}) {
 8491:                 $changed = 1;
 8492:                 last;
 8493:             }
 8494:         }
 8495:     }
 8496:     unless ($changed) {
 8497:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8498:         &logthis($logmsg);
 8499:         return 'ok';
 8500:     }
 8501:     my $reply = &put('environment', \%names, $udom,$uname);
 8502:     if ($reply ne 'ok') { 
 8503:         return 'error: '.$reply;
 8504:     }
 8505:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8506:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8507:     }
 8508:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8509:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8510:     $logmsg = 'Success modifying user '.$logmsg;
 8511:     &logthis($logmsg);
 8512:     return 'ok';
 8513: }
 8514: 
 8515: # -------------------------------------------------------------- Modify student
 8516: 
 8517: sub modifystudent {
 8518:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8519:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8520:         $selfenroll,$context,$inststatus,$credits)=@_;
 8521:     if (!$cid) {
 8522: 	unless ($cid=$env{'request.course.id'}) {
 8523: 	    return 'not_in_class';
 8524: 	}
 8525:     }
 8526: # --------------------------------------------------------------- Make the user
 8527:     my $reply=&modifyuser
 8528: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8529:          $desiredhome,$email,$inststatus);
 8530:     unless ($reply eq 'ok') { return $reply; }
 8531:     # This will cause &modify_student_enrollment to get the uid from the
 8532:     # student's environment
 8533:     $uid = undef if (!$forceid);
 8534:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8535:                                         $gene,$usec,$end,$start,$type,$locktype,
 8536:                                         $cid,$selfenroll,$context,$credits);
 8537:     return $reply;
 8538: }
 8539: 
 8540: sub modify_student_enrollment {
 8541:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8542:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8543:     my ($cdom,$cnum,$chome);
 8544:     if (!$cid) {
 8545: 	unless ($cid=$env{'request.course.id'}) {
 8546: 	    return 'not_in_class';
 8547: 	}
 8548: 	$cdom=$env{'course.'.$cid.'.domain'};
 8549: 	$cnum=$env{'course.'.$cid.'.num'};
 8550:     } else {
 8551: 	($cdom,$cnum)=split(/_/,$cid);
 8552:     }
 8553:     $chome=$env{'course.'.$cid.'.home'};
 8554:     if (!$chome) {
 8555: 	$chome=&homeserver($cnum,$cdom);
 8556:     }
 8557:     if (!$chome) { return 'unknown_course'; }
 8558:     # Make sure the user exists
 8559:     my $uhome=&homeserver($uname,$udom);
 8560:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8561: 	return 'error: no such user';
 8562:     }
 8563:     # Get student data if we were not given enough information
 8564:     if (!defined($first)  || $first  eq '' || 
 8565:         !defined($last)   || $last   eq '' || 
 8566:         !defined($uid)    || $uid    eq '' || 
 8567:         !defined($middle) || $middle eq '' || 
 8568:         !defined($gene)   || $gene   eq '') {
 8569:         # They did not supply us with enough data to enroll the student, so
 8570:         # we need to pick up more information.
 8571:         my %tmp = &get('environment',
 8572:                        ['firstname','middlename','lastname', 'generation','id']
 8573:                        ,$udom,$uname);
 8574: 
 8575:         #foreach my $key (keys(%tmp)) {
 8576:         #    &logthis("key $key = ".$tmp{$key});
 8577:         #}
 8578:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8579:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8580:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8581:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8582:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8583:     }
 8584:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8585:     my $user = "$uname:$udom";
 8586:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8587:     my $reply=cput('classlist',
 8588: 		   {$user => 
 8589: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8590: 		   $cdom,$cnum);
 8591:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8592:         &devalidate_getsection_cache($udom,$uname,$cid);
 8593:     } else { 
 8594: 	return 'error: '.$reply;
 8595:     }
 8596:     # Add student role to user
 8597:     my $uurl='/'.$cid;
 8598:     $uurl=~s/\_/\//g;
 8599:     if ($usec) {
 8600: 	$uurl.='/'.$usec;
 8601:     }
 8602:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8603:                              $selfenroll,$context);
 8604:     if ($result ne 'ok') {
 8605:         if ($old_entry{$user} ne '') {
 8606:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8607:         } else {
 8608:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8609:         }
 8610:     }
 8611:     return $result; 
 8612: }
 8613: 
 8614: sub format_name {
 8615:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8616:     my $name;
 8617:     if ($first ne 'lastname') {
 8618: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8619:     } else {
 8620: 	if ($lastname=~/\S/) {
 8621: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8622: 	    $name=~s/\s+,/,/;
 8623: 	} else {
 8624: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8625: 	}
 8626:     }
 8627:     $name=~s/^\s+//;
 8628:     $name=~s/\s+$//;
 8629:     $name=~s/\s+/ /g;
 8630:     return $name;
 8631: }
 8632: 
 8633: # ------------------------------------------------- Write to course preferences
 8634: 
 8635: sub writecoursepref {
 8636:     my ($courseid,%prefs)=@_;
 8637:     $courseid=~s/^\///;
 8638:     $courseid=~s/\_/\//g;
 8639:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8640:     my $chome=homeserver($cnum,$cdomain);
 8641:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8642: 	return 'error: no such course';
 8643:     }
 8644:     my $cstring='';
 8645:     foreach my $pref (keys(%prefs)) {
 8646: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8647:     }
 8648:     $cstring=~s/\&$//;
 8649:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8650: }
 8651: 
 8652: # ---------------------------------------------------------- Make/modify course
 8653: 
 8654: sub createcourse {
 8655:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8656:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8657:     $url=&declutter($url);
 8658:     my $cid='';
 8659:     if ($context eq 'requestcourses') {
 8660:         my $can_create = 0;
 8661:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8662:         if ($udom eq $ownerdom) {
 8663:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8664:                                   $context)) {
 8665:                 $can_create = 1;
 8666:             }
 8667:         } else {
 8668:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8669:                                            $category);
 8670:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8671:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8672:                 if (@curr > 0) {
 8673:                     my @options = qw(approval validate autolimit);
 8674:                     my $optregex = join('|',@options);
 8675:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8676:                         $can_create = 1;
 8677:                     }
 8678:                 }
 8679:             }
 8680:         }
 8681:         if ($can_create) {
 8682:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8683:                 unless (&allowed('ccc',$udom)) {
 8684:                     return 'refused'; 
 8685:                 }
 8686:             }
 8687:         } else {
 8688:             return 'refused';
 8689:         }
 8690:     } elsif (!&allowed('ccc',$udom)) {
 8691:         return 'refused';
 8692:     }
 8693: # --------------------------------------------------------------- Get Unique ID
 8694:     my $uname;
 8695:     if ($cnum =~ /^$match_courseid$/) {
 8696:         my $chome=&homeserver($cnum,$udom,'true');
 8697:         if (($chome eq '') || ($chome eq 'no_host')) {
 8698:             $uname = $cnum;
 8699:         } else {
 8700:             $uname = &generate_coursenum($udom,$crstype);
 8701:         }
 8702:     } else {
 8703:         $uname = &generate_coursenum($udom,$crstype);
 8704:     }
 8705:     return $uname if ($uname =~ /^error/);
 8706: # -------------------------------------------------- Check supplied server name
 8707:     if (!defined($course_server)) {
 8708:         if (defined(&domain($udom,'primary'))) {
 8709:             $course_server = &domain($udom,'primary');
 8710:         } else {
 8711:             $course_server = $env{'user.home'}; 
 8712:         }
 8713:     }
 8714:     my %host_servers =
 8715:         &Apache::lonnet::get_servers($udom,'library');
 8716:     unless ($host_servers{$course_server}) {
 8717:         return 'error: invalid home server for course: '.$course_server;
 8718:     }
 8719: # ------------------------------------------------------------- Make the course
 8720:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8721:                       $course_server);
 8722:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8723:     my $uhome=&homeserver($uname,$udom,'true');
 8724:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8725: 	return 'error: no such course';
 8726:     }
 8727: # ----------------------------------------------------------------- Course made
 8728: # log existence
 8729:     my $now = time;
 8730:     my $newcourse = {
 8731:                     $udom.'_'.$uname => {
 8732:                                      description => $description,
 8733:                                      inst_code   => $inst_code,
 8734:                                      owner       => $course_owner,
 8735:                                      type        => $crstype,
 8736:                                      creator     => $env{'user.name'}.':'.
 8737:                                                     $env{'user.domain'},
 8738:                                      created     => $now,
 8739:                                      context     => $context,
 8740:                                                 },
 8741:                     };
 8742:     &courseidput($udom,$newcourse,$uhome,'notime');
 8743: # set toplevel url
 8744:     my $topurl=$url;
 8745:     unless ($nonstandard) {
 8746: # ------------------------------------------ For standard courses, make top url
 8747:         my $mapurl=&clutter($url);
 8748:         if ($mapurl eq '/res/') { $mapurl=''; }
 8749:         $env{'form.initmap'}=(<<ENDINITMAP);
 8750: <map>
 8751: <resource id="1" type="start"></resource>
 8752: <resource id="2" src="$mapurl"></resource>
 8753: <resource id="3" type="finish"></resource>
 8754: <link index="1" from="1" to="2"></link>
 8755: <link index="2" from="2" to="3"></link>
 8756: </map>
 8757: ENDINITMAP
 8758:         $topurl=&declutter(
 8759:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8760:                           );
 8761:     }
 8762: # ----------------------------------------------------------- Write preferences
 8763:     &writecoursepref($udom.'_'.$uname,
 8764:                      ('description'              => $description,
 8765:                       'url'                      => $topurl,
 8766:                       'internal.creator'         => $env{'user.name'}.':'.
 8767:                                                     $env{'user.domain'},
 8768:                       'internal.created'         => $now,
 8769:                       'internal.creationcontext' => $context)
 8770:                     );
 8771:     return '/'.$udom.'/'.$uname;
 8772: }
 8773: 
 8774: # ------------------------------------------------------------------- Create ID
 8775: sub generate_coursenum {
 8776:     my ($udom,$crstype) = @_;
 8777:     my $domdesc = &domain($udom);
 8778:     return 'error: invalid domain' if ($domdesc eq '');
 8779:     my $first;
 8780:     if ($crstype eq 'Community') {
 8781:         $first = '0';
 8782:     } else {
 8783:         $first = int(1+rand(9)); 
 8784:     } 
 8785:     my $uname=$first.
 8786:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8787:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8788:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8789: # ----------------------------------------------- Make sure that does not exist
 8790:     my $uhome=&homeserver($uname,$udom,'true');
 8791:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8792:         if ($crstype eq 'Community') {
 8793:             $first = '0';
 8794:         } else {
 8795:             $first = int(1+rand(9));
 8796:         }
 8797:         $uname=$first.
 8798:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8799:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8800:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8801:         $uhome=&homeserver($uname,$udom,'true');
 8802:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8803:             return 'error: unable to generate unique course-ID';
 8804:         }
 8805:     }
 8806:     return $uname;
 8807: }
 8808: 
 8809: sub is_course {
 8810:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8811:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8812: 
 8813:     return unless $cdom and $cnum;
 8814: 
 8815:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8816:         '.');
 8817: 
 8818:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8819:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8820: }
 8821: 
 8822: sub store_userdata {
 8823:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8824:     my $result;
 8825:     if ($datakey ne '') {
 8826:         if (ref($storehash) eq 'HASH') {
 8827:             if ($udom eq '' || $uname eq '') {
 8828:                 $udom = $env{'user.domain'};
 8829:                 $uname = $env{'user.name'};
 8830:             }
 8831:             my $uhome=&homeserver($uname,$udom);
 8832:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8833:                 $result = 'error: no_host';
 8834:             } else {
 8835:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8836:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8837: 
 8838:                 my $namevalue='';
 8839:                 foreach my $key (keys(%{$storehash})) {
 8840:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8841:                 }
 8842:                 $namevalue=~s/\&$//;
 8843:                 unless ($namespace eq 'courserequests') {
 8844:                     $datakey = &escape($datakey);
 8845:                 }
 8846:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8847:                                   $namevalue,$uhome);
 8848:             }
 8849:         } else {
 8850:             $result = 'error: data to store was not a hash reference'; 
 8851:         }
 8852:     } else {
 8853:         $result= 'error: invalid requestkey'; 
 8854:     }
 8855:     return $result;
 8856: }
 8857: 
 8858: # ---------------------------------------------------------- Assign Custom Role
 8859: 
 8860: sub assigncustomrole {
 8861:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8862:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8863:                        $end,$start,$deleteflag,$selfenroll,$context);
 8864: }
 8865: 
 8866: # ----------------------------------------------------------------- Revoke Role
 8867: 
 8868: sub revokerole {
 8869:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8870:     my $now=time;
 8871:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8872: }
 8873: 
 8874: # ---------------------------------------------------------- Revoke Custom Role
 8875: 
 8876: sub revokecustomrole {
 8877:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8878:     my $now=time;
 8879:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8880:            $deleteflag,$selfenroll,$context);
 8881: }
 8882: 
 8883: # ------------------------------------------------------------ Disk usage
 8884: sub diskusage {
 8885:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8886:     $directorypath =~ s/\/$//;
 8887:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8888:                        .&escape($getpropath).':'.&escape($uname).':'
 8889:                        .&escape($udom),homeserver($uname,$udom));
 8890:     if ($listing eq 'unknown_cmd') {
 8891:         if ($getpropath) {
 8892:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8893:         }
 8894:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8895:     }
 8896:     return $listing;
 8897: }
 8898: 
 8899: sub is_locked {
 8900:     my ($file_name, $domain, $user, $which) = @_;
 8901:     my @check;
 8902:     my $is_locked;
 8903:     push (@check,$file_name);
 8904:     my %locked = &get('file_permissions',\@check,
 8905: 		      $env{'user.domain'},$env{'user.name'});
 8906:     my ($tmp)=keys(%locked);
 8907:     if ($tmp=~/^error:/) { undef(%locked); }
 8908:     
 8909:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8910:         $is_locked = 'false';
 8911:         foreach my $entry (@{$locked{$file_name}}) {
 8912:            if (ref($entry) eq 'ARRAY') {
 8913:                $is_locked = 'true';
 8914:                if (ref($which) eq 'ARRAY') {
 8915:                    push(@{$which},$entry);
 8916:                } else {
 8917:                    last;
 8918:                }
 8919:            }
 8920:        }
 8921:     } else {
 8922:         $is_locked = 'false';
 8923:     }
 8924:     return $is_locked;
 8925: }
 8926: 
 8927: sub declutter_portfile {
 8928:     my ($file) = @_;
 8929:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8930:     return $file;
 8931: }
 8932: 
 8933: # ------------------------------------------------------------- Mark as Read Only
 8934: 
 8935: sub mark_as_readonly {
 8936:     my ($domain,$user,$files,$what) = @_;
 8937:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8938:     my ($tmp)=keys(%current_permissions);
 8939:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8940:     foreach my $file (@{$files}) {
 8941: 	$file = &declutter_portfile($file);
 8942:         push(@{$current_permissions{$file}},$what);
 8943:     }
 8944:     &put('file_permissions',\%current_permissions,$domain,$user);
 8945:     return;
 8946: }
 8947: 
 8948: # ------------------------------------------------------------Save Selected Files
 8949: 
 8950: sub save_selected_files {
 8951:     my ($user, $path, @files) = @_;
 8952:     my $filename = $user."savedfiles";
 8953:     my @other_files = &files_not_in_path($user, $path);
 8954:     open (OUT, '>'.$tmpdir.$filename);
 8955:     foreach my $file (@files) {
 8956:         print (OUT $env{'form.currentpath'}.$file."\n");
 8957:     }
 8958:     foreach my $file (@other_files) {
 8959:         print (OUT $file."\n");
 8960:     }
 8961:     close (OUT);
 8962:     return 'ok';
 8963: }
 8964: 
 8965: sub clear_selected_files {
 8966:     my ($user) = @_;
 8967:     my $filename = $user."savedfiles";
 8968:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8969:     print (OUT undef);
 8970:     close (OUT);
 8971:     return ("ok");    
 8972: }
 8973: 
 8974: sub files_in_path {
 8975:     my ($user, $path) = @_;
 8976:     my $filename = $user."savedfiles";
 8977:     my %return_files;
 8978:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8979:     while (my $line_in = <IN>) {
 8980:         chomp ($line_in);
 8981:         my @paths_and_file = split (m!/!, $line_in);
 8982:         my $file_part = pop (@paths_and_file);
 8983:         my $path_part = join ('/', @paths_and_file);
 8984:         $path_part.='/';
 8985:         my $path_and_file = $path_part.$file_part;
 8986:         if ($path_part eq $path) {
 8987:             $return_files{$file_part}= 'selected';
 8988:         }
 8989:     }
 8990:     close (IN);
 8991:     return (\%return_files);
 8992: }
 8993: 
 8994: # called in portfolio select mode, to show files selected NOT in current directory
 8995: sub files_not_in_path {
 8996:     my ($user, $path) = @_;
 8997:     my $filename = $user."savedfiles";
 8998:     my @return_files;
 8999:     my $path_part;
 9000:     open(IN, '<'.LONCAPA::.$filename);
 9001:     while (my $line = <IN>) {
 9002:         #ok, I know it's clunky, but I want it to work
 9003:         my @paths_and_file = split(m|/|, $line);
 9004:         my $file_part = pop(@paths_and_file);
 9005:         chomp($file_part);
 9006:         my $path_part = join('/', @paths_and_file);
 9007:         $path_part .= '/';
 9008:         my $path_and_file = $path_part.$file_part;
 9009:         if ($path_part ne $path) {
 9010:             push(@return_files, ($path_and_file));
 9011:         }
 9012:     }
 9013:     close(OUT);
 9014:     return (@return_files);
 9015: }
 9016: 
 9017: #----------------------------------------------Get portfolio file permissions
 9018: 
 9019: sub get_portfile_permissions {
 9020:     my ($domain,$user) = @_;
 9021:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9022:     my ($tmp)=keys(%current_permissions);
 9023:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9024:     return \%current_permissions;
 9025: }
 9026: 
 9027: #---------------------------------------------Get portfolio file access controls
 9028: 
 9029: sub get_access_controls {
 9030:     my ($current_permissions,$group,$file) = @_;
 9031:     my %access;
 9032:     my $real_file = $file;
 9033:     $file =~ s/\.meta$//;
 9034:     if (defined($file)) {
 9035:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9036:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9037:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9038:             }
 9039:         }
 9040:     } else {
 9041:         foreach my $key (keys(%{$current_permissions})) {
 9042:             if ($key =~ /\0accesscontrol$/) {
 9043:                 if (defined($group)) {
 9044:                     if ($key !~ m-^\Q$group\E/-) {
 9045:                         next;
 9046:                     }
 9047:                 }
 9048:                 my ($fullpath) = split(/\0/,$key);
 9049:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9050:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9051:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9052:                     }
 9053:                 }
 9054:             }
 9055:         }
 9056:     }
 9057:     return %access;
 9058: }
 9059: 
 9060: sub modify_access_controls {
 9061:     my ($file_name,$changes,$domain,$user)=@_;
 9062:     my ($outcome,$deloutcome);
 9063:     my %store_permissions;
 9064:     my %new_values;
 9065:     my %new_control;
 9066:     my %translation;
 9067:     my @deletions = ();
 9068:     my $now = time;
 9069:     if (exists($$changes{'activate'})) {
 9070:         if (ref($$changes{'activate'}) eq 'HASH') {
 9071:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9072:             my $numnew = scalar(@newitems);
 9073:             for (my $i=0; $i<$numnew; $i++) {
 9074:                 my $newkey = $newitems[$i];
 9075:                 my $newid = &Apache::loncommon::get_cgi_id();
 9076:                 if ($newkey =~ /^\d+:/) { 
 9077:                     $newkey =~ s/^(\d+)/$newid/;
 9078:                     $translation{$1} = $newid;
 9079:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9080:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9081:                     $translation{$1} = $newid;
 9082:                 }
 9083:                 $new_values{$file_name."\0".$newkey} = 
 9084:                                           $$changes{'activate'}{$newitems[$i]};
 9085:                 $new_control{$newkey} = $now;
 9086:             }
 9087:         }
 9088:     }
 9089:     my %todelete;
 9090:     my %changed_items;
 9091:     foreach my $action ('delete','update') {
 9092:         if (exists($$changes{$action})) {
 9093:             if (ref($$changes{$action}) eq 'HASH') {
 9094:                 foreach my $key (keys(%{$$changes{$action}})) {
 9095:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9096:                     if ($action eq 'delete') { 
 9097:                         $todelete{$itemnum} = 1;
 9098:                     } else {
 9099:                         $changed_items{$itemnum} = $key;
 9100:                     }
 9101:                 }
 9102:             }
 9103:         }
 9104:     }
 9105:     # get lock on access controls for file.
 9106:     my $lockhash = {
 9107:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9108:                                                        ':'.$env{'user.domain'},
 9109:                    }; 
 9110:     my $tries = 0;
 9111:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9112:    
 9113:     while (($gotlock ne 'ok') && $tries <3) {
 9114:         $tries ++;
 9115:         sleep 1;
 9116:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9117:     }
 9118:     if ($gotlock eq 'ok') {
 9119:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9120:         my ($tmp)=keys(%curr_permissions);
 9121:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9122:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9123:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9124:             if (ref($curr_controls) eq 'HASH') {
 9125:                 foreach my $control_item (keys(%{$curr_controls})) {
 9126:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9127:                     if (defined($todelete{$itemnum})) {
 9128:                         push(@deletions,$file_name."\0".$control_item);
 9129:                     } else {
 9130:                         if (defined($changed_items{$itemnum})) {
 9131:                             $new_control{$changed_items{$itemnum}} = $now;
 9132:                             push(@deletions,$file_name."\0".$control_item);
 9133:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9134:                         } else {
 9135:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9136:                         }
 9137:                     }
 9138:                 }
 9139:             }
 9140:         }
 9141:         my ($group);
 9142:         if (&is_course($domain,$user)) {
 9143:             ($group,my $file) = split(/\//,$file_name,2);
 9144:         }
 9145:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9146:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9147:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9148:         #  remove lock
 9149:         my @del_lock = ($file_name."\0".'locked_access_records');
 9150:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9151:         my $sqlresult =
 9152:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9153:                                     $group);
 9154:     } else {
 9155:         $outcome = "error: could not obtain lockfile\n";  
 9156:     }
 9157:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9158: }
 9159: 
 9160: sub make_public_indefinitely {
 9161:     my ($requrl) = @_;
 9162:     my $now = time;
 9163:     my $action = 'activate';
 9164:     my $aclnum = 0;
 9165:     if (&is_portfolio_url($requrl)) {
 9166:         my (undef,$udom,$unum,$file_name,$group) =
 9167:             &parse_portfolio_url($requrl);
 9168:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9169:         my %access_controls = &get_access_controls($current_perms,
 9170:                                                    $group,$file_name);
 9171:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9172:             my ($num,$scope,$end,$start) = 
 9173:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9174:             if ($scope eq 'public') {
 9175:                 if ($start <= $now && $end == 0) {
 9176:                     $action = 'none';
 9177:                 } else {
 9178:                     $action = 'update';
 9179:                     $aclnum = $num;
 9180:                 }
 9181:                 last;
 9182:             }
 9183:         }
 9184:         if ($action eq 'none') {
 9185:              return 'ok';
 9186:         } else {
 9187:             my %changes;
 9188:             my $newend = 0;
 9189:             my $newstart = $now;
 9190:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9191:             $changes{$action}{$newkey} = {
 9192:                 type => 'public',
 9193:                 time => {
 9194:                     start => $newstart,
 9195:                     end   => $newend,
 9196:                 },
 9197:             };
 9198:             my ($outcome,$deloutcome,$new_values,$translation) =
 9199:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9200:             return $outcome;
 9201:         }
 9202:     } else {
 9203:         return 'invalid';
 9204:     }
 9205: }
 9206: 
 9207: #------------------------------------------------------Get Marked as Read Only
 9208: 
 9209: sub get_marked_as_readonly {
 9210:     my ($domain,$user,$what,$group) = @_;
 9211:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9212:     my @readonly_files;
 9213:     my $cmp1=$what;
 9214:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9215:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9216:         if (defined($group)) {
 9217:             if ($file_name !~ m-^\Q$group\E/-) {
 9218:                 next;
 9219:             }
 9220:         }
 9221:         if (ref($value) eq "ARRAY"){
 9222:             foreach my $stored_what (@{$value}) {
 9223:                 my $cmp2=$stored_what;
 9224:                 if (ref($stored_what) eq 'ARRAY') {
 9225:                     $cmp2=join('',@{$stored_what});
 9226:                 }
 9227:                 if ($cmp1 eq $cmp2) {
 9228:                     push(@readonly_files, $file_name);
 9229:                     last;
 9230:                 } elsif (!defined($what)) {
 9231:                     push(@readonly_files, $file_name);
 9232:                     last;
 9233:                 }
 9234:             }
 9235:         }
 9236:     }
 9237:     return @readonly_files;
 9238: }
 9239: #-----------------------------------------------------------Get Marked as Read Only Hash
 9240: 
 9241: sub get_marked_as_readonly_hash {
 9242:     my ($current_permissions,$group,$what) = @_;
 9243:     my %readonly_files;
 9244:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9245:         if (defined($group)) {
 9246:             if ($file_name !~ m-^\Q$group\E/-) {
 9247:                 next;
 9248:             }
 9249:         }
 9250:         if (ref($value) eq "ARRAY"){
 9251:             foreach my $stored_what (@{$value}) {
 9252:                 if (ref($stored_what) eq 'ARRAY') {
 9253:                     foreach my $lock_descriptor(@{$stored_what}) {
 9254:                         if ($lock_descriptor eq 'graded') {
 9255:                             $readonly_files{$file_name} = 'graded';
 9256:                         } elsif ($lock_descriptor eq 'handback') {
 9257:                             $readonly_files{$file_name} = 'handback';
 9258:                         } else {
 9259:                             if (!exists($readonly_files{$file_name})) {
 9260:                                 $readonly_files{$file_name} = 'locked';
 9261:                             }
 9262:                         }
 9263:                     }
 9264:                 } 
 9265:             }
 9266:         } 
 9267:     }
 9268:     return %readonly_files;
 9269: }
 9270: # ------------------------------------------------------------ Unmark as Read Only
 9271: 
 9272: sub unmark_as_readonly {
 9273:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9274:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9275:     my ($domain,$user,$what,$file_name,$group) = @_;
 9276:     $file_name = &declutter_portfile($file_name);
 9277:     my $symb_crs = $what;
 9278:     if (ref($what)) { $symb_crs=join('',@$what); }
 9279:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9280:     my ($tmp)=keys(%current_permissions);
 9281:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9282:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9283:     foreach my $file (@readonly_files) {
 9284: 	my $clean_file = &declutter_portfile($file);
 9285: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9286: 	my $current_locks = $current_permissions{$file};
 9287:         my @new_locks;
 9288:         my @del_keys;
 9289:         if (ref($current_locks) eq "ARRAY"){
 9290:             foreach my $locker (@{$current_locks}) {
 9291:                 my $compare=$locker;
 9292:                 if (ref($locker) eq 'ARRAY') {
 9293:                     $compare=join('',@{$locker});
 9294:                     if ($compare ne $symb_crs) {
 9295:                         push(@new_locks, $locker);
 9296:                     }
 9297:                 }
 9298:             }
 9299:             if (scalar(@new_locks) > 0) {
 9300:                 $current_permissions{$file} = \@new_locks;
 9301:             } else {
 9302:                 push(@del_keys, $file);
 9303:                 &del('file_permissions',\@del_keys, $domain, $user);
 9304:                 delete($current_permissions{$file});
 9305:             }
 9306:         }
 9307:     }
 9308:     &put('file_permissions',\%current_permissions,$domain,$user);
 9309:     return;
 9310: }
 9311: 
 9312: # ------------------------------------------------------------ Directory lister
 9313: 
 9314: sub dirlist {
 9315:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9316:     $uri=~s/^\///;
 9317:     $uri=~s/\/$//;
 9318:     my ($udom, $uname);
 9319:     if ($getuserdir) {
 9320:         $udom = $userdomain;
 9321:         $uname = $username;
 9322:     } else {
 9323:         (undef,$udom,$uname)=split(/\//,$uri);
 9324:         if(defined($userdomain)) {
 9325:             $udom = $userdomain;
 9326:         }
 9327:         if(defined($username)) {
 9328:             $uname = $username;
 9329:         }
 9330:     }
 9331:     my ($dirRoot,$listing,@listing_results);
 9332: 
 9333:     $dirRoot = $perlvar{'lonDocRoot'};
 9334:     if (defined($getpropath)) {
 9335:         $dirRoot = &propath($udom,$uname);
 9336:         $dirRoot =~ s/\/$//;
 9337:     } elsif (defined($getuserdir)) {
 9338:         my $subdir=$uname.'__';
 9339:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9340:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9341:                    ."/$udom/$subdir/$uname";
 9342:     } elsif (defined($alternateRoot)) {
 9343:         $dirRoot = $alternateRoot;
 9344:     }
 9345: 
 9346:     if($udom) {
 9347:         if($uname) {
 9348:             my $uhome = &homeserver($uname,$udom);
 9349:             if ($uhome eq 'no_host') {
 9350:                 return ([],'no_host');
 9351:             }
 9352:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9353:                               .$getuserdir.':'.&escape($dirRoot)
 9354:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9355:             if ($listing eq 'unknown_cmd') {
 9356:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9357:             } else {
 9358:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9359:             }
 9360:             if ($listing eq 'unknown_cmd') {
 9361:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9362:                 @listing_results = split(/:/,$listing);
 9363:             } else {
 9364:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9365:             }
 9366:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9367:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9368:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9369:                 return ([],$listing);
 9370:             } else {
 9371:                 return (\@listing_results);
 9372:             }
 9373:         } elsif(!$alternateRoot) {
 9374:             my (%allusers,%listerror);
 9375: 	    my %servers = &get_servers($udom,'library');
 9376:  	    foreach my $tryserver (keys(%servers)) {
 9377:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9378:                                   &escape($udom),$tryserver);
 9379:                 if ($listing eq 'unknown_cmd') {
 9380: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9381: 				      $udom, $tryserver);
 9382:                 } else {
 9383:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9384:                 }
 9385: 		if ($listing eq 'unknown_cmd') {
 9386: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9387: 				      $udom, $tryserver);
 9388: 		    @listing_results = split(/:/,$listing);
 9389: 		} else {
 9390: 		    @listing_results =
 9391: 			map { &unescape($_); } split(/:/,$listing);
 9392: 		}
 9393:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9394:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9395:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9396:                     $listerror{$tryserver} = $listing;
 9397:                 } else {
 9398: 		    foreach my $line (@listing_results) {
 9399: 			my ($entry) = split(/&/,$line,2);
 9400: 			$allusers{$entry} = 1;
 9401: 		    }
 9402: 		}
 9403:             }
 9404:             my @alluserslist=();
 9405:             foreach my $user (sort(keys(%allusers))) {
 9406:                 push(@alluserslist,$user.'&user');
 9407:             }
 9408:             return (\@alluserslist);
 9409:         } else {
 9410:             return ([],'missing username');
 9411:         }
 9412:     } elsif(!defined($getpropath)) {
 9413:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9414:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9415:         return (\@all_domains);
 9416:     } else {
 9417:         return ([],'missing domain');
 9418:     }
 9419: }
 9420: 
 9421: # --------------------------------------------- GetFileTimestamp
 9422: # This function utilizes dirlist and returns the date stamp for
 9423: # when it was last modified.  It will also return an error of -1
 9424: # if an error occurs
 9425: 
 9426: sub GetFileTimestamp {
 9427:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9428:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9429:     $studentName   = &LONCAPA::clean_username($studentName);
 9430:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9431:                                     undef,$getuserdir);
 9432:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9433:         return -1;
 9434:     }
 9435:     if (ref($fileref) eq 'ARRAY') {
 9436:         my @stats = split('&',$fileref->[0]);
 9437:         # @stats contains first the filename, then the stat output
 9438:         return $stats[10]; # so this is 10 instead of 9.
 9439:     } else {
 9440:         return -1;
 9441:     }
 9442: }
 9443: 
 9444: sub stat_file {
 9445:     my ($uri) = @_;
 9446:     $uri = &clutter_with_no_wrapper($uri);
 9447: 
 9448:     my ($udom,$uname,$file);
 9449:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9450: 	($udom,$uname,$file) =
 9451: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9452: 	$file = 'userfiles/'.$file;
 9453:     }
 9454:     if ($uri =~ m-^/res/-) {
 9455: 	($udom,$uname) = 
 9456: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9457: 	$file = $uri;
 9458:     }
 9459: 
 9460:     if (!$udom || !$uname || !$file) {
 9461: 	# unable to handle the uri
 9462: 	return ();
 9463:     }
 9464:     my $getpropath;
 9465:     if ($file =~ /^userfiles\//) {
 9466:         $getpropath = 1;
 9467:     }
 9468:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9469:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9470:         return ();
 9471:     } else {
 9472:         if (ref($listref) eq 'ARRAY') {
 9473:             my @stats = split('&',$listref->[0]);
 9474: 	    shift(@stats); #filename is first
 9475: 	    return @stats;
 9476:         }
 9477:     }
 9478:     return ();
 9479: }
 9480: 
 9481: # -------------------------------------------------------- Value of a Condition
 9482: 
 9483: # gets the value of a specific preevaluated condition
 9484: #    stored in the string  $env{user.state.<cid>}
 9485: # or looks up a condition reference in the bighash and if if hasn't
 9486: # already been evaluated recurses into docondval to get the value of
 9487: # the condition, then memoizing it to 
 9488: #   $env{user.state.<cid>.<condition>}
 9489: sub directcondval {
 9490:     my $number=shift;
 9491:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9492: 	&Apache::lonuserstate::evalstate();
 9493:     }
 9494:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9495: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9496:     } elsif ($number =~ /^_/) {
 9497: 	my $sub_condition;
 9498: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9499: 		&GDBM_READER(),0640)) {
 9500: 	    $sub_condition=$bighash{'conditions'.$number};
 9501: 	    untie(%bighash);
 9502: 	}
 9503: 	my $value = &docondval($sub_condition);
 9504: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9505: 	return $value;
 9506:     }
 9507:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9508:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9509:     } else {
 9510:        return 2;
 9511:     }
 9512: }
 9513: 
 9514: # get the collection of conditions for this resource
 9515: sub condval {
 9516:     my $condidx=shift;
 9517:     my $allpathcond='';
 9518:     foreach my $cond (split(/\|/,$condidx)) {
 9519: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9520: 	    $allpathcond.=
 9521: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9522: 	}
 9523:     }
 9524:     $allpathcond=~s/\|$//;
 9525:     return &docondval($allpathcond);
 9526: }
 9527: 
 9528: #evaluates an expression of conditions
 9529: sub docondval {
 9530:     my ($allpathcond) = @_;
 9531:     my $result=0;
 9532:     if ($env{'request.course.id'}
 9533: 	&& defined($allpathcond)) {
 9534: 	my $operand='|';
 9535: 	my @stack;
 9536: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9537: 	    if ($chunk eq '(') {
 9538: 		push @stack,($operand,$result);
 9539: 	    } elsif ($chunk eq ')') {
 9540: 		my $before=pop @stack;
 9541: 		if (pop @stack eq '&') {
 9542: 		    $result=$result>$before?$before:$result;
 9543: 		} else {
 9544: 		    $result=$result>$before?$result:$before;
 9545: 		}
 9546: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9547: 		$operand=$chunk;
 9548: 	    } else {
 9549: 		my $new=directcondval($chunk);
 9550: 		if ($operand eq '&') {
 9551: 		    $result=$result>$new?$new:$result;
 9552: 		} else {
 9553: 		    $result=$result>$new?$result:$new;
 9554: 		}
 9555: 	    }
 9556: 	}
 9557:     }
 9558:     return $result;
 9559: }
 9560: 
 9561: # ---------------------------------------------------- Devalidate courseresdata
 9562: 
 9563: sub devalidatecourseresdata {
 9564:     my ($coursenum,$coursedomain)=@_;
 9565:     my $hashid=$coursenum.':'.$coursedomain;
 9566:     &devalidate_cache_new('courseres',$hashid);
 9567: }
 9568: 
 9569: 
 9570: # --------------------------------------------------- Course Resourcedata Query
 9571: #
 9572: #  Parameters:
 9573: #      $coursenum    - Number of the course.
 9574: #      $coursedomain - Domain at which the course was created.
 9575: #  Returns:
 9576: #     A hash of the course parameters along (I think) with timestamps
 9577: #     and version info.
 9578: 
 9579: sub get_courseresdata {
 9580:     my ($coursenum,$coursedomain)=@_;
 9581:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9582:     my $hashid=$coursenum.':'.$coursedomain;
 9583:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9584:     my %dumpreply;
 9585:     unless (defined($cached)) {
 9586: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9587: 	$result=\%dumpreply;
 9588: 	my ($tmp) = keys(%dumpreply);
 9589: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9590: 	    &do_cache_new('courseres',$hashid,$result,600);
 9591: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9592: 	    return $tmp;
 9593: 	} elsif ($tmp =~ /^(error)/) {
 9594: 	    $result=undef;
 9595: 	    &do_cache_new('courseres',$hashid,$result,600);
 9596: 	}
 9597:     }
 9598:     return $result;
 9599: }
 9600: 
 9601: sub devalidateuserresdata {
 9602:     my ($uname,$udom)=@_;
 9603:     my $hashid="$udom:$uname";
 9604:     &devalidate_cache_new('userres',$hashid);
 9605: }
 9606: 
 9607: sub get_userresdata {
 9608:     my ($uname,$udom)=@_;
 9609:     #most student don\'t have any data set, check if there is some data
 9610:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9611: 
 9612:     my $hashid="$udom:$uname";
 9613:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9614:     if (!defined($cached)) {
 9615: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9616: 	$result=\%resourcedata;
 9617: 	&do_cache_new('userres',$hashid,$result,600);
 9618:     }
 9619:     my ($tmp)=keys(%$result);
 9620:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9621: 	return $result;
 9622:     }
 9623:     #error 2 occurs when the .db doesn't exist
 9624:     if ($tmp!~/error: 2 /) {
 9625: 	&logthis("<font color=\"blue\">WARNING:".
 9626: 		 " Trying to get resource data for ".
 9627: 		 $uname." at ".$udom.": ".
 9628: 		 $tmp."</font>");
 9629:     } elsif ($tmp=~/error: 2 /) {
 9630: 	#&EXT_cache_set($udom,$uname);
 9631: 	&do_cache_new('userres',$hashid,undef,600);
 9632: 	undef($tmp); # not really an error so don't send it back
 9633:     }
 9634:     return $tmp;
 9635: }
 9636: #----------------------------------------------- resdata - return resource data
 9637: #  Purpose:
 9638: #    Return resource data for either users or for a course.
 9639: #  Parameters:
 9640: #     $name      - Course/user name.
 9641: #     $domain    - Name of the domain the user/course is registered on.
 9642: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9643: #     @which     - Array of names of resources desired.
 9644: #  Returns:
 9645: #     The value of the first reasource in @which that is found in the
 9646: #     resource hash.
 9647: #  Exceptional Conditions:
 9648: #     If the $type passed in is not valid (not the string 'course' or 
 9649: #     'user', an undefined  reference is returned.
 9650: #     If none of the resources are found, an undef is returned
 9651: sub resdata {
 9652:     my ($name,$domain,$type,@which)=@_;
 9653:     my $result;
 9654:     if ($type eq 'course') {
 9655: 	$result=&get_courseresdata($name,$domain);
 9656:     } elsif ($type eq 'user') {
 9657: 	$result=&get_userresdata($name,$domain);
 9658:     }
 9659:     if (!ref($result)) { return $result; }    
 9660:     foreach my $item (@which) {
 9661: 	if (defined($result->{$item->[0]})) {
 9662: 	    return [$result->{$item->[0]},$item->[1]];
 9663: 	}
 9664:     }
 9665:     return undef;
 9666: }
 9667: 
 9668: sub get_numsuppfiles {
 9669:     my ($cnum,$cdom,$ignorecache)=@_;
 9670:     my $hashid=$cnum.':'.$cdom;
 9671:     my ($suppcount,$cached);
 9672:     unless ($ignorecache) {
 9673:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9674:     }
 9675:     unless (defined($cached)) {
 9676:         my $chome=&homeserver($cnum,$cdom);
 9677:         unless ($chome eq 'no_host') {
 9678:             ($suppcount,my $errors) = (0,0);
 9679:             my $suppmap = 'supplemental.sequence';
 9680:             ($suppcount,$errors) = 
 9681:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9682:         }
 9683:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9684:     }
 9685:     return $suppcount;
 9686: }
 9687: 
 9688: #
 9689: # EXT resource caching routines
 9690: #
 9691: 
 9692: sub clear_EXT_cache_status {
 9693:     &delenv('cache.EXT.');
 9694: }
 9695: 
 9696: sub EXT_cache_status {
 9697:     my ($target_domain,$target_user) = @_;
 9698:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9699:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9700:         # We know already the user has no data
 9701:         return 1;
 9702:     } else {
 9703:         return 0;
 9704:     }
 9705: }
 9706: 
 9707: sub EXT_cache_set {
 9708:     my ($target_domain,$target_user) = @_;
 9709:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9710:     #&appenv({$cachename => time});
 9711: }
 9712: 
 9713: # --------------------------------------------------------- Value of a Variable
 9714: sub EXT {
 9715: 
 9716:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9717:     unless ($varname) { return ''; }
 9718:     #get real user name/domain, courseid and symb
 9719:     my $courseid;
 9720:     my $publicuser;
 9721:     if ($symbparm) {
 9722: 	$symbparm=&get_symb_from_alias($symbparm);
 9723:     }
 9724:     if (!($uname && $udom)) {
 9725:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9726:       if (!$symbparm) {	$symbparm=$cursymb; }
 9727:     } else {
 9728: 	$courseid=$env{'request.course.id'};
 9729:     }
 9730:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9731:     my $rest;
 9732:     if (defined($therest[0])) {
 9733:        $rest=join('.',@therest);
 9734:     } else {
 9735:        $rest='';
 9736:     }
 9737: 
 9738:     my $qualifierrest=$qualifier;
 9739:     if ($rest) { $qualifierrest.='.'.$rest; }
 9740:     my $spacequalifierrest=$space;
 9741:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9742:     if ($realm eq 'user') {
 9743: # --------------------------------------------------------------- user.resource
 9744: 	if ($space eq 'resource') {
 9745: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9746: 		  || defined($Apache::lonhomework::parsing_a_task))
 9747: 		 &&
 9748: 		 ($symbparm eq &symbread()) ) {	
 9749: 		# if we are in the middle of processing the resource the
 9750: 		# get the value we are planning on committing
 9751:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9752:                     return $Apache::lonhomework::results{$qualifierrest};
 9753:                 } else {
 9754:                     return $Apache::lonhomework::history{$qualifierrest};
 9755:                 }
 9756: 	    } else {
 9757: 		my %restored;
 9758: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9759: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9760: 		} else {
 9761: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9762: 		}
 9763: 		return $restored{$qualifierrest};
 9764: 	    }
 9765: # ----------------------------------------------------------------- user.access
 9766:         } elsif ($space eq 'access') {
 9767: 	    # FIXME - not supporting calls for a specific user
 9768:             return &allowed($qualifier,$rest);
 9769: # ------------------------------------------ user.preferences, user.environment
 9770:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9771: 	    if (($uname eq $env{'user.name'}) &&
 9772: 		($udom eq $env{'user.domain'})) {
 9773: 		return $env{join('.',('environment',$qualifierrest))};
 9774: 	    } else {
 9775: 		my %returnhash;
 9776: 		if (!$publicuser) {
 9777: 		    %returnhash=&userenvironment($udom,$uname,
 9778: 						 $qualifierrest);
 9779: 		}
 9780: 		return $returnhash{$qualifierrest};
 9781: 	    }
 9782: # ----------------------------------------------------------------- user.course
 9783:         } elsif ($space eq 'course') {
 9784: 	    # FIXME - not supporting calls for a specific user
 9785:             return $env{join('.',('request.course',$qualifier))};
 9786: # ------------------------------------------------------------------- user.role
 9787:         } elsif ($space eq 'role') {
 9788: 	    # FIXME - not supporting calls for a specific user
 9789:             my ($role,$where)=split(/\./,$env{'request.role'});
 9790:             if ($qualifier eq 'value') {
 9791: 		return $role;
 9792:             } elsif ($qualifier eq 'extent') {
 9793:                 return $where;
 9794:             }
 9795: # ----------------------------------------------------------------- user.domain
 9796:         } elsif ($space eq 'domain') {
 9797:             return $udom;
 9798: # ------------------------------------------------------------------- user.name
 9799:         } elsif ($space eq 'name') {
 9800:             return $uname;
 9801: # ---------------------------------------------------- Any other user namespace
 9802:         } else {
 9803: 	    my %reply;
 9804: 	    if (!$publicuser) {
 9805: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9806: 	    }
 9807: 	    return $reply{$qualifierrest};
 9808:         }
 9809:     } elsif ($realm eq 'query') {
 9810: # ---------------------------------------------- pull stuff out of query string
 9811:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9812: 						[$spacequalifierrest]);
 9813: 	return $env{'form.'.$spacequalifierrest}; 
 9814:    } elsif ($realm eq 'request') {
 9815: # ------------------------------------------------------------- request.browser
 9816:         if ($space eq 'browser') {
 9817:             return $env{'browser.'.$qualifier};
 9818: # ------------------------------------------------------------ request.filename
 9819:         } else {
 9820:             return $env{'request.'.$spacequalifierrest};
 9821:         }
 9822:     } elsif ($realm eq 'course') {
 9823: # ---------------------------------------------------------- course.description
 9824:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9825:     } elsif ($realm eq 'resource') {
 9826: 
 9827: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9828: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9829: 	}
 9830: 
 9831:         if ($qualifier eq '') {
 9832: 	    if ($space eq 'title') {
 9833: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9834: 	        return &gettitle($symbparm);
 9835: 	    }
 9836: 	
 9837: 	    if ($space eq 'map') {
 9838: 	        my ($map) = &decode_symb($symbparm);
 9839: 	        return &symbread($map);
 9840: 	    }
 9841:             if ($space eq 'maptitle') {
 9842:                 my ($map) = &decode_symb($symbparm);
 9843:                 return &gettitle($map);
 9844:             }
 9845: 	    if ($space eq 'filename') {
 9846: 	        if ($symbparm) {
 9847: 		    return &clutter((&decode_symb($symbparm))[2]);
 9848: 	        }
 9849: 	        return &hreflocation('',$env{'request.filename'});
 9850: 	    }
 9851: 
 9852:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9853:                 if ($space eq 'visibleparts') {
 9854:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9855:                     my $item;
 9856:                     if (ref($navmap)) {
 9857:                         my $res = $navmap->getBySymb($symbparm);
 9858:                         my $parts = $res->parts();
 9859:                         if (ref($parts) eq 'ARRAY') {
 9860:                             $item = join(',',@{$parts});
 9861:                         }
 9862:                         undef($navmap);
 9863:                     }
 9864:                     return $item;
 9865:                 }
 9866:             }
 9867:         }
 9868: 
 9869: 	my ($section, $group, @groups);
 9870: 	my ($courselevelm,$courselevel);
 9871:         if (($courseid eq '') && ($cid)) {
 9872:             $courseid = $cid;
 9873:         }
 9874: 	if (($symbparm && $courseid) && 
 9875: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9876: 
 9877: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9878: 
 9879: # ----------------------------------------------------- Cascading lookup scheme
 9880: 	    my $symbp=$symbparm;
 9881: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9882: 
 9883: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9884: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9885: 
 9886: 	    if (($env{'user.name'} eq $uname) &&
 9887: 		($env{'user.domain'} eq $udom)) {
 9888: 		$section=$env{'request.course.sec'};
 9889:                 @groups = split(/:/,$env{'request.course.groups'});  
 9890:                 @groups=&sort_course_groups($courseid,@groups); 
 9891: 	    } else {
 9892: 		if (! defined($usection)) {
 9893: 		    $section=&getsection($udom,$uname,$courseid);
 9894: 		} else {
 9895: 		    $section = $usection;
 9896: 		}
 9897:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9898: 	    }
 9899: 
 9900: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9901: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9902: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9903: 
 9904: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9905: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9906: 	    $courselevelm=$courseid.'.'.$mapparm;
 9907: 
 9908: # ----------------------------------------------------------- first, check user
 9909: 
 9910: 	    my $userreply=&resdata($uname,$udom,'user',
 9911: 				       ([$courselevelr,'resource'],
 9912: 					[$courselevelm,'map'     ],
 9913: 					[$courselevel, 'course'  ]));
 9914: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9915: 
 9916: # ------------------------------------------------ second, check some of course
 9917:             my $coursereply;
 9918:             if (@groups > 0) {
 9919:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9920:                                        $mapparm,$spacequalifierrest);
 9921:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9922:             }
 9923: 
 9924: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9925: 				  $env{'course.'.$courseid.'.domain'},
 9926: 				  'course',
 9927: 				  ([$seclevelr,   'resource'],
 9928: 				   [$seclevelm,   'map'     ],
 9929: 				   [$seclevel,    'course'  ],
 9930: 				   [$courselevelr,'resource']));
 9931: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9932: 
 9933: # ------------------------------------------------------ third, check map parms
 9934: 	    my %parmhash=();
 9935: 	    my $thisparm='';
 9936: 	    if (tie(%parmhash,'GDBM_File',
 9937: 		    $env{'request.course.fn'}.'_parms.db',
 9938: 		    &GDBM_READER(),0640)) {
 9939: 		$thisparm=$parmhash{$symbparm};
 9940: 		untie(%parmhash);
 9941: 	    }
 9942: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9943: 	}
 9944: # ------------------------------------------ fourth, look in resource metadata
 9945: 
 9946: 	$spacequalifierrest=~s/\./\_/;
 9947: 	my $filename;
 9948: 	if (!$symbparm) { $symbparm=&symbread(); }
 9949: 	if ($symbparm) {
 9950: 	    $filename=(&decode_symb($symbparm))[2];
 9951: 	} else {
 9952: 	    $filename=$env{'request.filename'};
 9953: 	}
 9954: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9955: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9956: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9957: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9958: 
 9959: # ---------------------------------------------- fourth, look in rest of course
 9960: 	if ($symbparm && defined($courseid) && 
 9961: 	    $courseid eq $env{'request.course.id'}) {
 9962: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9963: 				     $env{'course.'.$courseid.'.domain'},
 9964: 				     'course',
 9965: 				     ([$courselevelm,'map'   ],
 9966: 				      [$courselevel, 'course']));
 9967: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9968: 	}
 9969: # ------------------------------------------------------------------ Cascade up
 9970: 	unless ($space eq '0') {
 9971: 	    my @parts=split(/_/,$space);
 9972: 	    my $id=pop(@parts);
 9973: 	    my $part=join('_',@parts);
 9974: 	    if ($part eq '') { $part='0'; }
 9975: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9976: 				 $symbparm,$udom,$uname,$section,1);
 9977: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9978: 	}
 9979: 	if ($recurse) { return undef; }
 9980: 	my $pack_def=&packages_tab_default($filename,$varname);
 9981: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9982: # ---------------------------------------------------- Any other user namespace
 9983:     } elsif ($realm eq 'environment') {
 9984: # ----------------------------------------------------------------- environment
 9985: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9986: 	    return $env{'environment.'.$spacequalifierrest};
 9987: 	} else {
 9988: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9989: 		return '';
 9990: 	    }
 9991: 	    my %returnhash=&userenvironment($udom,$uname,
 9992: 					    $spacequalifierrest);
 9993: 	    return $returnhash{$spacequalifierrest};
 9994: 	}
 9995:     } elsif ($realm eq 'system') {
 9996: # ----------------------------------------------------------------- system.time
 9997: 	if ($space eq 'time') {
 9998: 	    return time;
 9999:         }
10000:     } elsif ($realm eq 'server') {
10001: # ----------------------------------------------------------------- system.time
10002: 	if ($space eq 'name') {
10003: 	    return $ENV{'SERVER_NAME'};
10004:         }
10005:     }
10006:     return '';
10007: }
10008: 
10009: sub get_reply {
10010:     my ($reply_value) = @_;
10011:     if (ref($reply_value) eq 'ARRAY') {
10012:         if (wantarray) {
10013: 	    return @$reply_value;
10014:         }
10015:         return $reply_value->[0];
10016:     } else {
10017:         return $reply_value;
10018:     }
10019: }
10020: 
10021: sub check_group_parms {
10022:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10023:     my @groupitems = ();
10024:     my $resultitem;
10025:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10026:     foreach my $group (@{$groups}) {
10027:         foreach my $level (@levels) {
10028:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10029:              push(@groupitems,[$item,$level->[1]]);
10030:         }
10031:     }
10032:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10033:                             $env{'course.'.$courseid.'.domain'},
10034:                                      'course',@groupitems);
10035:     return $coursereply;
10036: }
10037: 
10038: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10039:     my ($courseid,@groups) = @_;
10040:     @groups = sort(@groups);
10041:     return @groups;
10042: }
10043: 
10044: sub packages_tab_default {
10045:     my ($uri,$varname)=@_;
10046:     my (undef,$part,$name)=split(/\./,$varname);
10047: 
10048:     my (@extension,@specifics,$do_default);
10049:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10050: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10051: 	if ($pack_type eq 'default') {
10052: 	    $do_default=1;
10053: 	} elsif ($pack_type eq 'extension') {
10054: 	    push(@extension,[$package,$pack_type,$pack_part]);
10055: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10056: 	    # only look at packages defaults for packages that this id is
10057: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10058: 	}
10059:     }
10060:     # first look for a package that matches the requested part id
10061:     foreach my $package (@specifics) {
10062: 	my (undef,$pack_type,$pack_part)=@{$package};
10063: 	next if ($pack_part ne $part);
10064: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10065: 	    return $packagetab{"$pack_type&$name&default"};
10066: 	}
10067:     }
10068:     # look for any possible matching non extension_ package
10069:     foreach my $package (@specifics) {
10070: 	my (undef,$pack_type,$pack_part)=@{$package};
10071: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10072: 	    return $packagetab{"$pack_type&$name&default"};
10073: 	}
10074: 	if ($pack_type eq 'part') { $pack_part='0'; }
10075: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10076: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10077: 	}
10078:     }
10079:     # look for any posible extension_ match
10080:     foreach my $package (@extension) {
10081: 	my ($package,$pack_type)=@{$package};
10082: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10083: 	    return $packagetab{"$pack_type&$name&default"};
10084: 	}
10085: 	if (defined($packagetab{$package."&$name&default"})) {
10086: 	    return $packagetab{$package."&$name&default"};
10087: 	}
10088:     }
10089:     # look for a global default setting
10090:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10091: 	return $packagetab{"default&$name&default"};
10092:     }
10093:     return undef;
10094: }
10095: 
10096: sub add_prefix_and_part {
10097:     my ($prefix,$part)=@_;
10098:     my $keyroot;
10099:     if (defined($prefix) && $prefix !~ /^__/) {
10100: 	# prefix that has a part already
10101: 	$keyroot=$prefix;
10102:     } elsif (defined($prefix)) {
10103: 	# prefix that is missing a part
10104: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10105:     } else {
10106: 	# no prefix at all
10107: 	if (defined($part)) { $keyroot='_'.$part; }
10108:     }
10109:     return $keyroot;
10110: }
10111: 
10112: # ---------------------------------------------------------------- Get metadata
10113: 
10114: my %metaentry;
10115: my %importedpartids;
10116: sub metadata {
10117:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10118:     $uri=&declutter($uri);
10119:     # if it is a non metadata possible uri return quickly
10120:     if (($uri eq '') || 
10121: 	(($uri =~ m|^/*adm/|) && 
10122: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10123:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10124: 	return undef;
10125:     }
10126:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10127: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10128: 	return undef;
10129:     }
10130:     my $filename=$uri;
10131:     $uri=~s/\.meta$//;
10132: #
10133: # Is the metadata already cached?
10134: # Look at timestamp of caching
10135: # Everything is cached by the main uri, libraries are never directly cached
10136: #
10137:     if (!defined($liburi)) {
10138: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10139: 	if (defined($cached)) { return $result->{':'.$what}; }
10140:     }
10141:     {
10142: # Imported parts would go here
10143:         my %importedids=();
10144:         my @origfileimportpartids=();
10145:         my $importedparts=0;
10146: #
10147: # Is this a recursive call for a library?
10148: #
10149: #	if (! exists($metacache{$uri})) {
10150: #	    $metacache{$uri}={};
10151: #	}
10152: 	my $cachetime = 60*60;
10153:         if ($liburi) {
10154: 	    $liburi=&declutter($liburi);
10155:             $filename=$liburi;
10156:         } else {
10157: 	    &devalidate_cache_new('meta',$uri);
10158: 	    undef(%metaentry);
10159: 	}
10160:         my %metathesekeys=();
10161:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10162: 	my $metastring;
10163: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10164: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10165: 	    $metastring = 
10166: 		&Apache::lonnet::ssi_body($which,
10167: 					  ('grade_target' => 'meta'));
10168: 	    $cachetime = 1; # only want this cached in the child not long term
10169: 	} elsif (($uri !~ m -^(editupload)/-) && 
10170:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10171: 	    my $file=&filelocation('',&clutter($filename));
10172: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10173: 	    $metastring=&getfile($file);
10174: 	}
10175:         my $parser=HTML::LCParser->new(\$metastring);
10176:         my $token;
10177:         undef %metathesekeys;
10178:         while ($token=$parser->get_token) {
10179: 	    if ($token->[0] eq 'S') {
10180: 		if (defined($token->[2]->{'package'})) {
10181: #
10182: # This is a package - get package info
10183: #
10184: 		    my $package=$token->[2]->{'package'};
10185: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10186: 		    if (defined($token->[2]->{'id'})) { 
10187: 			$keyroot.='_'.$token->[2]->{'id'}; 
10188: 		    }
10189: 		    if ($metaentry{':packages'}) {
10190: 			$metaentry{':packages'}.=','.$package.$keyroot;
10191: 		    } else {
10192: 			$metaentry{':packages'}=$package.$keyroot;
10193: 		    }
10194: 		    foreach my $pack_entry (keys(%packagetab)) {
10195: 			my $part=$keyroot;
10196: 			$part=~s/^\_//;
10197: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10198: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10199: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10200: 			    # ignore package.tab specified default values
10201:                             # here &package_tab_default() will fetch those
10202: 			    if ($subp eq 'default') { next; }
10203: 			    my $value=$packagetab{$pack_entry};
10204: 			    my $unikey;
10205: 			    if ($pack =~ /_0$/) {
10206: 				$unikey='parameter_0_'.$name;
10207: 				$part=0;
10208: 			    } else {
10209: 				$unikey='parameter'.$keyroot.'_'.$name;
10210: 			    }
10211: 			    if ($subp eq 'display') {
10212: 				$value.=' [Part: '.$part.']';
10213: 			    }
10214: 			    $metaentry{':'.$unikey.'.part'}=$part;
10215: 			    $metathesekeys{$unikey}=1;
10216: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10217: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10218: 			    }
10219: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10220: 				$metaentry{':'.$unikey}=
10221: 				    $metaentry{':'.$unikey.'.default'};
10222: 			    }
10223: 			}
10224: 		    }
10225: 		} else {
10226: #
10227: # This is not a package - some other kind of start tag
10228: #
10229: 		    my $entry=$token->[1];
10230: 		    my $unikey='';
10231: 
10232: 		    if ($entry eq 'import') {
10233: #
10234: # Importing a library here
10235: #
10236:                         my $location=$parser->get_text('/import');
10237:                         my $dir=$filename;
10238:                         $dir=~s|[^/]*$||;
10239:                         $location=&filelocation($dir,$location);
10240:                        
10241:                         my $importmode=$token->[2]->{'importmode'};
10242:                         if ($importmode eq 'problem') {
10243: # Import as problem/response
10244:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10245:                         } elsif ($importmode eq 'part') {
10246: # Import as part(s)
10247:                            $importedparts=1;
10248: # We need to get the original file and the imported file to get the part order correct
10249: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10250: # Load and inspect original file
10251:                            if ($#origfileimportpartids<0) {
10252:                               undef(%importedpartids);
10253:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10254:                               my $origfile=&getfile($origfilelocation);
10255:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10256:                            }
10257: 
10258: # Load and inspect imported file
10259:                            my $impfile=&getfile($location);
10260:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10261:                            if ($#impfilepartids>=0) {
10262: # This problem had parts
10263:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10264:                            } else {
10265: # Importing by turning a single problem into a problem part
10266: # It gets the import-tags ID as part-ID
10267:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10268:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10269:                            }
10270:                         } else {
10271: # Normal import
10272:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10273:                            if (defined($token->[2]->{'id'})) {
10274:                               $unikey.='_'.$token->[2]->{'id'};
10275:                            }
10276:                         }
10277: 
10278: 			if ($depthcount<20) {
10279: 			    my $metadata = 
10280: 				&metadata($uri,'keys', $location,$unikey,
10281: 					  $depthcount+1);
10282: 			    foreach my $meta (split(',',$metadata)) {
10283: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10284: 				$metathesekeys{$meta}=1;
10285: 			    }
10286: 			
10287:                         }
10288: 		    } else {
10289: #
10290: # Not importing, some other kind of non-package, non-library start tag
10291: # 
10292:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10293:                         if (defined($token->[2]->{'id'})) {
10294:                             $unikey.='_'.$token->[2]->{'id'};
10295:                         }
10296: 			if (defined($token->[2]->{'name'})) { 
10297: 			    $unikey.='_'.$token->[2]->{'name'}; 
10298: 			}
10299: 			$metathesekeys{$unikey}=1;
10300: 			foreach my $param (@{$token->[3]}) {
10301: 			    $metaentry{':'.$unikey.'.'.$param} =
10302: 				$token->[2]->{$param};
10303: 			}
10304: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10305: 			my $default=$metaentry{':'.$unikey.'.default'};
10306: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10307: 		 # only ws inside the tag, and not in default, so use default
10308: 		 # as value
10309: 			    $metaentry{':'.$unikey}=$default;
10310: 			} elsif ( $internaltext =~ /\S/ ) {
10311: 		  # something interesting inside the tag
10312: 			    $metaentry{':'.$unikey}=$internaltext;
10313: 			} else {
10314: 		  # no interesting values, don't set a default
10315: 			}
10316: # end of not-a-package not-a-library import
10317: 		    }
10318: # end of not-a-package start tag
10319: 		}
10320: # the next is the end of "start tag"
10321: 	    }
10322: 	}
10323: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10324: 	$extension = lc($extension);
10325: 	if ($extension eq 'htm') { $extension='html'; }
10326: 
10327: 	foreach my $key (keys(%packagetab)) {
10328: 	    #no specific packages #how's our extension
10329: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10330: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10331: 					 \%metathesekeys);
10332: 	}
10333: 
10334: 	if (!exists($metaentry{':packages'})
10335: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10336: 	    foreach my $key (keys(%packagetab)) {
10337: 		#no specific packages well let's get default then
10338: 		if ($key!~/^default&/) { next; }
10339: 		&metadata_create_package_def($uri,$key,'default',
10340: 					     \%metathesekeys);
10341: 	    }
10342: 	}
10343: # are there custom rights to evaluate
10344: 	if ($metaentry{':copyright'} eq 'custom') {
10345: 
10346:     #
10347:     # Importing a rights file here
10348:     #
10349: 	    unless ($depthcount) {
10350: 		my $location=$metaentry{':customdistributionfile'};
10351: 		my $dir=$filename;
10352: 		$dir=~s|[^/]*$||;
10353: 		$location=&filelocation($dir,$location);
10354: 		my $rights_metadata =
10355: 		    &metadata($uri,'keys',$location,'_rights',
10356: 			      $depthcount+1);
10357: 		foreach my $rights (split(',',$rights_metadata)) {
10358: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10359: 		    $metathesekeys{$rights}=1;
10360: 		}
10361: 	    }
10362: 	}
10363: 	# uniqifiy package listing
10364: 	my %seen;
10365: 	my @uniq_packages =
10366: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10367: 	$metaentry{':packages'} = join(',',@uniq_packages);
10368: 
10369:         if ($importedparts) {
10370: # We had imported parts and need to rebuild partorder
10371:            $metaentry{':partorder'}='';
10372:            $metathesekeys{'partorder'}=1;
10373:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10374:                if ($origfileimportpartids[$index] eq 'part') {
10375: # original part, part of the problem
10376:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10377:                } else {
10378: # we have imported parts at this position
10379:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10380:                }
10381:            }
10382:            $metaentry{':partorder'}=~s/^\,//;
10383:         }
10384: 
10385: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10386: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10387: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10388: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10389: # this is the end of "was not already recently cached
10390:     }
10391:     return $metaentry{':'.$what};
10392: }
10393: 
10394: sub metadata_create_package_def {
10395:     my ($uri,$key,$package,$metathesekeys)=@_;
10396:     my ($pack,$name,$subp)=split(/\&/,$key);
10397:     if ($subp eq 'default') { next; }
10398:     
10399:     if (defined($metaentry{':packages'})) {
10400: 	$metaentry{':packages'}.=','.$package;
10401:     } else {
10402: 	$metaentry{':packages'}=$package;
10403:     }
10404:     my $value=$packagetab{$key};
10405:     my $unikey;
10406:     $unikey='parameter_0_'.$name;
10407:     $metaentry{':'.$unikey.'.part'}=0;
10408:     $$metathesekeys{$unikey}=1;
10409:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10410: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10411:     }
10412:     if (defined($metaentry{':'.$unikey.'.default'})) {
10413: 	$metaentry{':'.$unikey}=
10414: 	    $metaentry{':'.$unikey.'.default'};
10415:     }
10416: }
10417: 
10418: sub metadata_generate_part0 {
10419:     my ($metadata,$metacache,$uri) = @_;
10420:     my %allnames;
10421:     foreach my $metakey (keys(%$metadata)) {
10422: 	if ($metakey=~/^parameter\_(.*)/) {
10423: 	  my $part=$$metacache{':'.$metakey.'.part'};
10424: 	  my $name=$$metacache{':'.$metakey.'.name'};
10425: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10426: 	    $allnames{$name}=$part;
10427: 	  }
10428: 	}
10429:     }
10430:     foreach my $name (keys(%allnames)) {
10431:       $$metadata{"parameter_0_$name"}=1;
10432:       my $key=":parameter_0_$name";
10433:       $$metacache{"$key.part"}='0';
10434:       $$metacache{"$key.name"}=$name;
10435:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10436: 					   $allnames{$name}.'_'.$name.
10437: 					   '.type'};
10438:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10439: 			     '.display'};
10440:       my $expr='[Part: '.$allnames{$name}.']';
10441:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10442:       $$metacache{"$key.display"}=$olddis;
10443:     }
10444: }
10445: 
10446: # ------------------------------------------------------ Devalidate title cache
10447: 
10448: sub devalidate_title_cache {
10449:     my ($url)=@_;
10450:     if (!$env{'request.course.id'}) { return; }
10451:     my $symb=&symbread($url);
10452:     if (!$symb) { return; }
10453:     my $key=$env{'request.course.id'}."\0".$symb;
10454:     &devalidate_cache_new('title',$key);
10455: }
10456: 
10457: # ------------------------------------------------- Get the title of a course
10458: 
10459: sub current_course_title {
10460:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10461: }
10462: # ------------------------------------------------- Get the title of a resource
10463: 
10464: sub gettitle {
10465:     my $urlsymb=shift;
10466:     my $symb=&symbread($urlsymb);
10467:     if ($symb) {
10468: 	my $key=$env{'request.course.id'}."\0".$symb;
10469: 	my ($result,$cached)=&is_cached_new('title',$key);
10470: 	if (defined($cached)) { 
10471: 	    return $result;
10472: 	}
10473: 	my ($map,$resid,$url)=&decode_symb($symb);
10474: 	my $title='';
10475: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10476: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10477: 	} else {
10478: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10479: 		    &GDBM_READER(),0640)) {
10480: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10481: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10482: 		untie(%bighash);
10483: 	    }
10484: 	}
10485: 	$title=~s/\&colon\;/\:/gs;
10486: 	if ($title) {
10487: # Remember both $symb and $title for dynamic metadata
10488:             $accesshash{$symb.'___crstitle'}=$title;
10489:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10490: # Cache this title and then return it
10491: 	    return &do_cache_new('title',$key,$title,600);
10492: 	}
10493: 	$urlsymb=$url;
10494:     }
10495:     my $title=&metadata($urlsymb,'title');
10496:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10497:     return $title;
10498: }
10499: 
10500: sub get_slot {
10501:     my ($which,$cnum,$cdom)=@_;
10502:     if (!$cnum || !$cdom) {
10503: 	(undef,my $courseid)=&whichuser();
10504: 	$cdom=$env{'course.'.$courseid.'.domain'};
10505: 	$cnum=$env{'course.'.$courseid.'.num'};
10506:     }
10507:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10508:     my %slotinfo;
10509:     if (exists($remembered{$key})) {
10510: 	$slotinfo{$which} = $remembered{$key};
10511:     } else {
10512: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10513: 	&Apache::lonhomework::showhash(%slotinfo);
10514: 	my ($tmp)=keys(%slotinfo);
10515: 	if ($tmp=~/^error:/) { return (); }
10516: 	$remembered{$key} = $slotinfo{$which};
10517:     }
10518:     if (ref($slotinfo{$which}) eq 'HASH') {
10519: 	return %{$slotinfo{$which}};
10520:     }
10521:     return $slotinfo{$which};
10522: }
10523: 
10524: sub get_reservable_slots {
10525:     my ($cnum,$cdom,$uname,$udom) = @_;
10526:     my $now = time;
10527:     my $reservable_info;
10528:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10529:     if (exists($remembered{$key})) {
10530:         $reservable_info = $remembered{$key};
10531:     } else {
10532:         my %resv;
10533:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10534:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10535:         $reservable_info = \%resv;
10536:         $remembered{$key} = $reservable_info;
10537:     }
10538:     return $reservable_info;
10539: }
10540: 
10541: sub get_course_slots {
10542:     my ($cnum,$cdom) = @_;
10543:     my $hashid=$cnum.':'.$cdom;
10544:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10545:     if (defined($cached)) {
10546:         if (ref($result) eq 'HASH') {
10547:             return %{$result};
10548:         }
10549:     } else {
10550:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10551:         my ($tmp) = keys(%slots);
10552:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10553:             &do_cache_new('allslots',$hashid,\%slots,600);
10554:             return %slots;
10555:         }
10556:     }
10557:     return;
10558: }
10559: 
10560: sub devalidate_slots_cache {
10561:     my ($cnum,$cdom)=@_;
10562:     my $hashid=$cnum.':'.$cdom;
10563:     &devalidate_cache_new('allslots',$hashid);
10564: }
10565: 
10566: sub get_coursechange {
10567:     my ($cdom,$cnum) = @_;
10568:     if ($cdom eq '' || $cnum eq '') {
10569:         return unless ($env{'request.course.id'});
10570:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10571:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10572:     }
10573:     my $hashid=$cdom.'_'.$cnum;
10574:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10575:     if ((defined($cached)) && ($change ne '')) {
10576:         return $change;
10577:     } else {
10578:         my %crshash;
10579:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10580:         if ($crshash{'internal.contentchange'} eq '') {
10581:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10582:             if ($change eq '') {
10583:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10584:                 $change = $crshash{'internal.created'};
10585:             }
10586:         } else {
10587:             $change = $crshash{'internal.contentchange'};
10588:         }
10589:         my $cachetime = 600;
10590:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10591:     }
10592:     return $change;
10593: }
10594: 
10595: sub devalidate_coursechange_cache {
10596:     my ($cnum,$cdom)=@_;
10597:     my $hashid=$cnum.':'.$cdom;
10598:     &devalidate_cache_new('crschange',$hashid);
10599: }
10600: 
10601: # ------------------------------------------------- Update symbolic store links
10602: 
10603: sub symblist {
10604:     my ($mapname,%newhash)=@_;
10605:     $mapname=&deversion(&declutter($mapname));
10606:     my %hash;
10607:     if (($env{'request.course.fn'}) && (%newhash)) {
10608:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10609:                       &GDBM_WRCREAT(),0640)) {
10610: 	    foreach my $url (keys(%newhash)) {
10611: 		next if ($url eq 'last_known'
10612: 			 && $env{'form.no_update_last_known'});
10613: 		$hash{declutter($url)}=&encode_symb($mapname,
10614: 						    $newhash{$url}->[1],
10615: 						    $newhash{$url}->[0]);
10616:             }
10617:             if (untie(%hash)) {
10618: 		return 'ok';
10619:             }
10620:         }
10621:     }
10622:     return 'error';
10623: }
10624: 
10625: # --------------------------------------------------------------- Verify a symb
10626: 
10627: sub symbverify {
10628:     my ($symb,$thisurl,$encstate)=@_;
10629:     my $thisfn=$thisurl;
10630:     $thisfn=&declutter($thisfn);
10631: # direct jump to resource in page or to a sequence - will construct own symbs
10632:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10633: # check URL part
10634:     my ($map,$resid,$url)=&decode_symb($symb);
10635: 
10636:     unless ($url eq $thisfn) { return 0; }
10637: 
10638:     $symb=&symbclean($symb);
10639:     $thisurl=&deversion($thisurl);
10640:     $thisfn=&deversion($thisfn);
10641: 
10642:     my %bighash;
10643:     my $okay=0;
10644: 
10645:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10646:                             &GDBM_READER(),0640)) {
10647:         my $noclutter;
10648:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10649:             $thisurl =~ s/\?.+$//;
10650:             if ($map =~ m{^uploaded/.+\.page$}) {
10651:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10652:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10653:                 $noclutter = 1;
10654:             }
10655:         }
10656:         my $ids;
10657:         if ($noclutter) {
10658:             $ids=$bighash{'ids_'.$thisurl};
10659:         } else {
10660:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10661:         }
10662:         unless ($ids) {
10663:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10664:             $ids=$bighash{$idkey};
10665:         }
10666:         if ($ids) {
10667: # ------------------------------------------------------------------- Has ID(s)
10668:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10669:                 $symb =~ s/\?.+$//;
10670:             }
10671: 	    foreach my $id (split(/\,/,$ids)) {
10672: 	       my ($mapid,$resid)=split(/\./,$id);
10673:                if (
10674:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10675:    eq $symb) {
10676:                    if (ref($encstate)) {
10677:                        $$encstate = $bighash{'encrypted_'.$id};
10678:                    }
10679: 		   if (($env{'request.role.adv'}) ||
10680: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10681:                        ($thisurl eq '/adm/navmaps')) {
10682: 		       $okay=1;
10683:                        last;
10684: 		   }
10685: 	       }
10686: 	   }
10687:         }
10688: 	untie(%bighash);
10689:     }
10690:     return $okay;
10691: }
10692: 
10693: # --------------------------------------------------------------- Clean-up symb
10694: 
10695: sub symbclean {
10696:     my $symb=shift;
10697:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10698: # remove version from map
10699:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10700: 
10701: # remove version from URL
10702:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10703: 
10704: # remove wrapper
10705: 
10706:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10707:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10708:     return $symb;
10709: }
10710: 
10711: # ---------------------------------------------- Split symb to find map and url
10712: 
10713: sub encode_symb {
10714:     my ($map,$resid,$url)=@_;
10715:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10716: }
10717: 
10718: sub decode_symb {
10719:     my $symb=shift;
10720:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10721:     my ($map,$resid,$url)=split(/___/,$symb);
10722:     return (&fixversion($map),$resid,&fixversion($url));
10723: }
10724: 
10725: sub fixversion {
10726:     my $fn=shift;
10727:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10728:     my %bighash;
10729:     my $uri=&clutter($fn);
10730:     my $key=$env{'request.course.id'}.'_'.$uri;
10731: # is this cached?
10732:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10733:     if (defined($cached)) { return $result; }
10734: # unfortunately not cached, or expired
10735:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10736: 	    &GDBM_READER(),0640)) {
10737:  	if ($bighash{'version_'.$uri}) {
10738:  	    my $version=$bighash{'version_'.$uri};
10739:  	    unless (($version eq 'mostrecent') || 
10740: 		    ($version==&getversion($uri))) {
10741:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10742:  	    }
10743:  	}
10744:  	untie %bighash;
10745:     }
10746:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10747: }
10748: 
10749: sub deversion {
10750:     my $url=shift;
10751:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10752:     return $url;
10753: }
10754: 
10755: # ------------------------------------------------------ Return symb list entry
10756: 
10757: sub symbread {
10758:     my ($thisfn,$donotrecurse)=@_;
10759:     my $cache_str;
10760:     if ($thisfn ne '') {
10761:         $cache_str='request.symbread.cached.'.$thisfn;
10762:         if ($env{$cache_str} ne '') {
10763:             return $env{$cache_str};
10764:         }
10765:     } else {
10766: # no filename provided? try from environment
10767:         if ($env{'request.symb'}) {
10768: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10769: 	}
10770: 	$thisfn=$env{'request.filename'};
10771:     }
10772:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10773: # is that filename actually a symb? Verify, clean, and return
10774:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10775: 	if (&symbverify($thisfn,$1)) {
10776: 	    return $env{$cache_str}=&symbclean($thisfn);
10777: 	}
10778:     }
10779:     $thisfn=declutter($thisfn);
10780:     my %hash;
10781:     my %bighash;
10782:     my $syval='';
10783:     if (($env{'request.course.fn'}) && ($thisfn)) {
10784:         my $targetfn = $thisfn;
10785:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10786:             $targetfn = 'adm/wrapper/'.$thisfn;
10787:         }
10788: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10789: 	    $targetfn=$1;
10790: 	}
10791:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10792:                       &GDBM_READER(),0640)) {
10793: 	    $syval=$hash{$targetfn};
10794:             untie(%hash);
10795:         }
10796: # ---------------------------------------------------------- There was an entry
10797:         if ($syval) {
10798: 	    #unless ($syval=~/\_\d+$/) {
10799: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10800: 		    #&appenv({'request.ambiguous' => $thisfn});
10801: 		    #return $env{$cache_str}='';
10802: 		#}    
10803: 		#$syval.=$1;
10804: 	    #}
10805:         } else {
10806: # ------------------------------------------------------- Was not in symb table
10807:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10808:                             &GDBM_READER(),0640)) {
10809: # ---------------------------------------------- Get ID(s) for current resource
10810:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10811:               unless ($ids) { 
10812:                  $ids=$bighash{'ids_/'.$thisfn};
10813:               }
10814:               unless ($ids) {
10815: # alias?
10816: 		  $ids=$bighash{'mapalias_'.$thisfn};
10817:               }
10818:               if ($ids) {
10819: # ------------------------------------------------------------------- Has ID(s)
10820:                  my @possibilities=split(/\,/,$ids);
10821:                  if ($#possibilities==0) {
10822: # ----------------------------------------------- There is only one possibility
10823: 		     my ($mapid,$resid)=split(/\./,$ids);
10824: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10825: 						    $resid,$thisfn);
10826:                  } elsif (!$donotrecurse) {
10827: # ------------------------------------------ There is more than one possibility
10828:                      my $realpossible=0;
10829:                      foreach my $id (@possibilities) {
10830: 			 my $file=$bighash{'src_'.$id};
10831:                          if (&allowed('bre',$file)) {
10832:          		    my ($mapid,$resid)=split(/\./,$id);
10833:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10834: 				$realpossible++;
10835:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10836: 						    $resid,$thisfn);
10837:                             }
10838: 			 }
10839:                      }
10840: 		     if ($realpossible!=1) { $syval=''; }
10841:                  } else {
10842:                      $syval='';
10843:                  }
10844: 	      }
10845:               untie(%bighash)
10846:            }
10847:         }
10848:         if ($syval) {
10849: 	    return $env{$cache_str}=$syval;
10850:         }
10851:     }
10852:     &appenv({'request.ambiguous' => $thisfn});
10853:     return $env{$cache_str}='';
10854: }
10855: 
10856: # ---------------------------------------------------------- Return random seed
10857: 
10858: sub numval {
10859:     my $txt=shift;
10860:     $txt=~tr/A-J/0-9/;
10861:     $txt=~tr/a-j/0-9/;
10862:     $txt=~tr/K-T/0-9/;
10863:     $txt=~tr/k-t/0-9/;
10864:     $txt=~tr/U-Z/0-5/;
10865:     $txt=~tr/u-z/0-5/;
10866:     $txt=~s/\D//g;
10867:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10868:     return int($txt);
10869: }
10870: 
10871: sub numval2 {
10872:     my $txt=shift;
10873:     $txt=~tr/A-J/0-9/;
10874:     $txt=~tr/a-j/0-9/;
10875:     $txt=~tr/K-T/0-9/;
10876:     $txt=~tr/k-t/0-9/;
10877:     $txt=~tr/U-Z/0-5/;
10878:     $txt=~tr/u-z/0-5/;
10879:     $txt=~s/\D//g;
10880:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10881:     my $total;
10882:     foreach my $val (@txts) { $total+=$val; }
10883:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10884:     return int($total);
10885: }
10886: 
10887: sub numval3 {
10888:     use integer;
10889:     my $txt=shift;
10890:     $txt=~tr/A-J/0-9/;
10891:     $txt=~tr/a-j/0-9/;
10892:     $txt=~tr/K-T/0-9/;
10893:     $txt=~tr/k-t/0-9/;
10894:     $txt=~tr/U-Z/0-5/;
10895:     $txt=~tr/u-z/0-5/;
10896:     $txt=~s/\D//g;
10897:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10898:     my $total;
10899:     foreach my $val (@txts) { $total+=$val; }
10900:     if ($_64bit) { $total=(($total<<32)>>32); }
10901:     return $total;
10902: }
10903: 
10904: sub digest {
10905:     my ($data)=@_;
10906:     my $digest=&Digest::MD5::md5($data);
10907:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10908:     my ($e,$f);
10909:     {
10910:         use integer;
10911:         $e=($a+$b);
10912:         $f=($c+$d);
10913:         if ($_64bit) {
10914:             $e=(($e<<32)>>32);
10915:             $f=(($f<<32)>>32);
10916:         }
10917:     }
10918:     if (wantarray) {
10919: 	return ($e,$f);
10920:     } else {
10921: 	my $g;
10922: 	{
10923: 	    use integer;
10924: 	    $g=($e+$f);
10925: 	    if ($_64bit) {
10926: 		$g=(($g<<32)>>32);
10927: 	    }
10928: 	}
10929: 	return $g;
10930:     }
10931: }
10932: 
10933: sub latest_rnd_algorithm_id {
10934:     return '64bit5';
10935: }
10936: 
10937: sub get_rand_alg {
10938:     my ($courseid)=@_;
10939:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10940:     if ($courseid) {
10941: 	return $env{"course.$courseid.rndseed"};
10942:     }
10943:     return &latest_rnd_algorithm_id();
10944: }
10945: 
10946: sub validCODE {
10947:     my ($CODE)=@_;
10948:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10949:     return 0;
10950: }
10951: 
10952: sub getCODE {
10953:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10954:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10955: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10956: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10957: 	return $Apache::lonhomework::history{'resource.CODE'};
10958:     }
10959:     return undef;
10960: }
10961: #
10962: #  Determines the random seed for a specific context:
10963: #
10964: # parameters:
10965: #   symb      - in course context the symb for the seed.
10966: #   course_id - The course id of the form domain_coursenum.
10967: #   domain    - Domain for the user.
10968: #   course    - Course for the user.
10969: #   cenv      - environment of the course.
10970: #
10971: # NOTE:
10972: #   All parameters are picked out of the environment if missing
10973: #   or not defined.
10974: #   If a symb cannot be determined the current time is used instead.
10975: #
10976: #  For a given well defined symb, courside, domain, username,
10977: #  and course environment, the seed is reproducible.
10978: #
10979: sub rndseed {
10980:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10981:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10982:     if (!defined($symb)) {
10983: 	unless ($symb=$wsymb) { return time; }
10984:     }
10985:     if (!defined $courseid) { 
10986: 	$courseid=$wcourseid; 
10987:     }
10988:     if (!defined $domain) { $domain=$wdomain; }
10989:     if (!defined $username) { $username=$wusername }
10990: 
10991:     my $which;
10992:     if (defined($cenv->{'rndseed'})) {
10993: 	$which = $cenv->{'rndseed'};
10994:     } else {
10995: 	$which =&get_rand_alg($courseid);
10996:     }
10997:     if (defined(&getCODE())) {
10998: 
10999: 	if ($which eq '64bit5') {
11000: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11001: 	} elsif ($which eq '64bit4') {
11002: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11003: 	} else {
11004: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11005: 	}
11006:     } elsif ($which eq '64bit5') {
11007: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11008:     } elsif ($which eq '64bit4') {
11009: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11010:     } elsif ($which eq '64bit3') {
11011: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11012:     } elsif ($which eq '64bit2') {
11013: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11014:     } elsif ($which eq '64bit') {
11015: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11016:     }
11017:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11018: }
11019: 
11020: sub rndseed_32bit {
11021:     my ($symb,$courseid,$domain,$username)=@_;
11022:     {
11023: 	use integer;
11024: 	my $symbchck=unpack("%32C*",$symb) << 27;
11025: 	my $symbseed=numval($symb) << 22;
11026: 	my $namechck=unpack("%32C*",$username) << 17;
11027: 	my $nameseed=numval($username) << 12;
11028: 	my $domainseed=unpack("%32C*",$domain) << 7;
11029: 	my $courseseed=unpack("%32C*",$courseid);
11030: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11031: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11032: 	#&logthis("rndseed :$num:$symb");
11033: 	if ($_64bit) { $num=(($num<<32)>>32); }
11034: 	return $num;
11035:     }
11036: }
11037: 
11038: sub rndseed_64bit {
11039:     my ($symb,$courseid,$domain,$username)=@_;
11040:     {
11041: 	use integer;
11042: 	my $symbchck=unpack("%32S*",$symb) << 21;
11043: 	my $symbseed=numval($symb) << 10;
11044: 	my $namechck=unpack("%32S*",$username);
11045: 	
11046: 	my $nameseed=numval($username) << 21;
11047: 	my $domainseed=unpack("%32S*",$domain) << 10;
11048: 	my $courseseed=unpack("%32S*",$courseid);
11049: 	
11050: 	my $num1=$symbchck+$symbseed+$namechck;
11051: 	my $num2=$nameseed+$domainseed+$courseseed;
11052: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11053: 	#&logthis("rndseed :$num:$symb");
11054: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11055: 	return "$num1,$num2";
11056:     }
11057: }
11058: 
11059: sub rndseed_64bit2 {
11060:     my ($symb,$courseid,$domain,$username)=@_;
11061:     {
11062: 	use integer;
11063: 	# strings need to be an even # of cahracters long, it it is odd the
11064:         # last characters gets thrown away
11065: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11066: 	my $symbseed=numval($symb) << 10;
11067: 	my $namechck=unpack("%32S*",$username.' ');
11068: 	
11069: 	my $nameseed=numval($username) << 21;
11070: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11071: 	my $courseseed=unpack("%32S*",$courseid.' ');
11072: 	
11073: 	my $num1=$symbchck+$symbseed+$namechck;
11074: 	my $num2=$nameseed+$domainseed+$courseseed;
11075: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11076: 	#&logthis("rndseed :$num:$symb");
11077: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11078: 	return "$num1,$num2";
11079:     }
11080: }
11081: 
11082: sub rndseed_64bit3 {
11083:     my ($symb,$courseid,$domain,$username)=@_;
11084:     {
11085: 	use integer;
11086: 	# strings need to be an even # of cahracters long, it it is odd the
11087:         # last characters gets thrown away
11088: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11089: 	my $symbseed=numval2($symb) << 10;
11090: 	my $namechck=unpack("%32S*",$username.' ');
11091: 	
11092: 	my $nameseed=numval2($username) << 21;
11093: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11094: 	my $courseseed=unpack("%32S*",$courseid.' ');
11095: 	
11096: 	my $num1=$symbchck+$symbseed+$namechck;
11097: 	my $num2=$nameseed+$domainseed+$courseseed;
11098: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11099: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11100: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11101: 	
11102: 	return "$num1:$num2";
11103:     }
11104: }
11105: 
11106: sub rndseed_64bit4 {
11107:     my ($symb,$courseid,$domain,$username)=@_;
11108:     {
11109: 	use integer;
11110: 	# strings need to be an even # of cahracters long, it it is odd the
11111:         # last characters gets thrown away
11112: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11113: 	my $symbseed=numval3($symb) << 10;
11114: 	my $namechck=unpack("%32S*",$username.' ');
11115: 	
11116: 	my $nameseed=numval3($username) << 21;
11117: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11118: 	my $courseseed=unpack("%32S*",$courseid.' ');
11119: 	
11120: 	my $num1=$symbchck+$symbseed+$namechck;
11121: 	my $num2=$nameseed+$domainseed+$courseseed;
11122: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11123: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11124: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11125: 	
11126: 	return "$num1:$num2";
11127:     }
11128: }
11129: 
11130: sub rndseed_64bit5 {
11131:     my ($symb,$courseid,$domain,$username)=@_;
11132:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11133:     return "$num1:$num2";
11134: }
11135: 
11136: sub rndseed_CODE_64bit {
11137:     my ($symb,$courseid,$domain,$username)=@_;
11138:     {
11139: 	use integer;
11140: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11141: 	my $symbseed=numval2($symb);
11142: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11143: 	my $CODEseed=numval(&getCODE());
11144: 	my $courseseed=unpack("%32S*",$courseid.' ');
11145: 	my $num1=$symbseed+$CODEchck;
11146: 	my $num2=$CODEseed+$courseseed+$symbchck;
11147: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11148: 	#&logthis("rndseed :$num1:$num2:$symb");
11149: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11150: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11151: 	return "$num1:$num2";
11152:     }
11153: }
11154: 
11155: sub rndseed_CODE_64bit4 {
11156:     my ($symb,$courseid,$domain,$username)=@_;
11157:     {
11158: 	use integer;
11159: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11160: 	my $symbseed=numval3($symb);
11161: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11162: 	my $CODEseed=numval3(&getCODE());
11163: 	my $courseseed=unpack("%32S*",$courseid.' ');
11164: 	my $num1=$symbseed+$CODEchck;
11165: 	my $num2=$CODEseed+$courseseed+$symbchck;
11166: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11167: 	#&logthis("rndseed :$num1:$num2:$symb");
11168: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11169: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11170: 	return "$num1:$num2";
11171:     }
11172: }
11173: 
11174: sub rndseed_CODE_64bit5 {
11175:     my ($symb,$courseid,$domain,$username)=@_;
11176:     my $code = &getCODE();
11177:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11178:     return "$num1:$num2";
11179: }
11180: 
11181: sub setup_random_from_rndseed {
11182:     my ($rndseed)=@_;
11183:     if ($rndseed =~/([,:])/) {
11184: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11185: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11186:     } else {
11187: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11188:     }
11189: }
11190: 
11191: sub latest_receipt_algorithm_id {
11192:     return 'receipt3';
11193: }
11194: 
11195: sub recunique {
11196:     my $fucourseid=shift;
11197:     my $unique;
11198:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11199: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11200: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11201:     } else {
11202: 	$unique=$perlvar{'lonReceipt'};
11203:     }
11204:     return unpack("%32C*",$unique);
11205: }
11206: 
11207: sub recprefix {
11208:     my $fucourseid=shift;
11209:     my $prefix;
11210:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11211: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11212: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11213:     } else {
11214: 	$prefix=$perlvar{'lonHostID'};
11215:     }
11216:     return unpack("%32C*",$prefix);
11217: }
11218: 
11219: sub ireceipt {
11220:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11221: 
11222:     my $return =&recprefix($fucourseid).'-';
11223: 
11224:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11225: 	$env{'request.state'} eq 'construct') {
11226: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11227: 	return $return;
11228:     }
11229: 
11230:     my $cuname=unpack("%32C*",$funame);
11231:     my $cudom=unpack("%32C*",$fudom);
11232:     my $cucourseid=unpack("%32C*",$fucourseid);
11233:     my $cusymb=unpack("%32C*",$fusymb);
11234:     my $cunique=&recunique($fucourseid);
11235:     my $cpart=unpack("%32S*",$part);
11236:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11237: 
11238: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11239: 			       
11240: 	$return.= ($cunique%$cuname+
11241: 		   $cunique%$cudom+
11242: 		   $cusymb%$cuname+
11243: 		   $cusymb%$cudom+
11244: 		   $cucourseid%$cuname+
11245: 		   $cucourseid%$cudom+
11246: 		   $cpart%$cuname+
11247: 		   $cpart%$cudom);
11248:     } else {
11249: 	$return.= ($cunique%$cuname+
11250: 		   $cunique%$cudom+
11251: 		   $cusymb%$cuname+
11252: 		   $cusymb%$cudom+
11253: 		   $cucourseid%$cuname+
11254: 		   $cucourseid%$cudom);
11255:     }
11256:     return $return;
11257: }
11258: 
11259: sub receipt {
11260:     my ($part)=@_;
11261:     my ($symb,$courseid,$domain,$name) = &whichuser();
11262:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11263: }
11264: 
11265: sub whichuser {
11266:     my ($passedsymb)=@_;
11267:     my ($symb,$courseid,$domain,$name,$publicuser);
11268:     if (defined($env{'form.grade_symb'})) {
11269: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11270: 	my $allowed=&allowed('vgr',$tmp_courseid);
11271: 	if (!$allowed &&
11272: 	    exists($env{'request.course.sec'}) &&
11273: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11274: 	    $allowed=&allowed('vgr',$tmp_courseid.
11275: 			      '/'.$env{'request.course.sec'});
11276: 	}
11277: 	if ($allowed) {
11278: 	    ($symb)=&get_env_multiple('form.grade_symb');
11279: 	    $courseid=$tmp_courseid;
11280: 	    ($domain)=&get_env_multiple('form.grade_domain');
11281: 	    ($name)=&get_env_multiple('form.grade_username');
11282: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11283: 	}
11284:     }
11285:     if (!$passedsymb) {
11286: 	$symb=&symbread();
11287:     } else {
11288: 	$symb=$passedsymb;
11289:     }
11290:     $courseid=$env{'request.course.id'};
11291:     $domain=$env{'user.domain'};
11292:     $name=$env{'user.name'};
11293:     if ($name eq 'public' && $domain eq 'public') {
11294: 	if (!defined($env{'form.username'})) {
11295: 	    $env{'form.username'}.=time.rand(10000000);
11296: 	}
11297: 	$name.=$env{'form.username'};
11298:     }
11299:     return ($symb,$courseid,$domain,$name,$publicuser);
11300: 
11301: }
11302: 
11303: # ------------------------------------------------------------ Serves up a file
11304: # returns either the contents of the file or 
11305: # -1 if the file doesn't exist
11306: #
11307: # if the target is a file that was uploaded via DOCS, 
11308: # a check will be made to see if a current copy exists on the local server,
11309: # if it does this will be served, otherwise a copy will be retrieved from
11310: # the home server for the course and stored in /home/httpd/html/userfiles on
11311: # the local server.   
11312: 
11313: sub getfile {
11314:     my ($file) = @_;
11315:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11316:     &repcopy($file);
11317:     return &readfile($file);
11318: }
11319: 
11320: sub repcopy_userfile {
11321:     my ($file)=@_;
11322:     my $londocroot = $perlvar{'lonDocRoot'};
11323:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11324:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11325:     my ($cdom,$cnum,$filename) = 
11326: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11327:     my $uri="/uploaded/$cdom/$cnum/$filename";
11328:     if (-e "$file") {
11329: # we already have a local copy, check it out
11330: 	my @fileinfo = stat($file);
11331: 	my $rtncode;
11332: 	my $info;
11333: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11334: 	if ($lwpresp ne 'ok') {
11335: # there is no such file anymore, even though we had a local copy
11336: 	    if ($rtncode eq '404') {
11337: 		unlink($file);
11338: 	    }
11339: 	    return -1;
11340: 	}
11341: 	if ($info < $fileinfo[9]) {
11342: # nice, the file we have is up-to-date, just say okay
11343: 	    return 'ok';
11344: 	} else {
11345: # the file is outdated, get rid of it
11346: 	    unlink($file);
11347: 	}
11348:     }
11349: # one way or the other, at this point, we don't have the file
11350: # construct the correct path for the file
11351:     my @parts = ($cdom,$cnum); 
11352:     if ($filename =~ m|^(.+)/[^/]+$|) {
11353: 	push @parts, split(/\//,$1);
11354:     }
11355:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11356:     foreach my $part (@parts) {
11357: 	$path .= '/'.$part;
11358: 	if (!-e $path) {
11359: 	    mkdir($path,0770);
11360: 	}
11361:     }
11362: # now the path exists for sure
11363: # get a user agent
11364:     my $ua=new LWP::UserAgent;
11365:     my $transferfile=$file.'.in.transfer';
11366: # FIXME: this should flock
11367:     if (-e $transferfile) { return 'ok'; }
11368:     my $request;
11369:     $uri=~s/^\///;
11370:     my $homeserver = &homeserver($cnum,$cdom);
11371:     my $protocol = $protocol{$homeserver};
11372:     $protocol = 'http' if ($protocol ne 'https');
11373:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11374:     my $response=$ua->request($request,$transferfile);
11375: # did it work?
11376:     if ($response->is_error()) {
11377: 	unlink($transferfile);
11378: 	&logthis("Userfile repcopy failed for $uri");
11379: 	return -1;
11380:     }
11381: # worked, rename the transfer file
11382:     rename($transferfile,$file);
11383:     return 'ok';
11384: }
11385: 
11386: sub tokenwrapper {
11387:     my $uri=shift;
11388:     $uri=~s|^https?\://([^/]+)||;
11389:     $uri=~s|^/||;
11390:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11391:     my $token=$1;
11392:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11393:     if ($udom && $uname && $file) {
11394: 	$file=~s|(\?\.*)*$||;
11395:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11396:         my $homeserver = &homeserver($uname,$udom);
11397:         my $protocol = $protocol{$homeserver};
11398:         $protocol = 'http' if ($protocol ne 'https');
11399:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11400:                (($uri=~/\?/)?'&':'?').'token='.$token.
11401:                                '&tokenissued='.$perlvar{'lonHostID'};
11402:     } else {
11403:         return '/adm/notfound.html';
11404:     }
11405: }
11406: 
11407: # call with reqtype HEAD: get last modification time
11408: # call with reqtype GET: get the file contents
11409: # Do not call this with reqtype GET for large files! It loads everything into memory
11410: #
11411: sub getuploaded {
11412:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11413:     $uri=~s/^\///;
11414:     my $homeserver = &homeserver($cnum,$cdom);
11415:     my $protocol = $protocol{$homeserver};
11416:     $protocol = 'http' if ($protocol ne 'https');
11417:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11418:     my $ua=new LWP::UserAgent;
11419:     my $request=new HTTP::Request($reqtype,$uri);
11420:     my $response=$ua->request($request);
11421:     $$rtncode = $response->code;
11422:     if (! $response->is_success()) {
11423: 	return 'failed';
11424:     }      
11425:     if ($reqtype eq 'HEAD') {
11426: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11427:     } elsif ($reqtype eq 'GET') {
11428: 	$$info = $response->content;
11429:     }
11430:     return 'ok';
11431: }
11432: 
11433: sub readfile {
11434:     my $file = shift;
11435:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11436:     my $fh;
11437:     open($fh,"<$file");
11438:     my $a='';
11439:     while (my $line = <$fh>) { $a .= $line; }
11440:     return $a;
11441: }
11442: 
11443: sub filelocation {
11444:     my ($dir,$file) = @_;
11445:     my $location;
11446:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11447: 
11448:     if ($file =~ m-^/adm/-) {
11449: 	$file=~s-^/adm/wrapper/-/-;
11450: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11451:     }
11452: 
11453:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11454:         $location = $file;
11455:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11456:         my ($udom,$uname,$filename)=
11457:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11458:         my $home=&homeserver($uname,$udom);
11459:         my $is_me=0;
11460:         my @ids=&current_machine_ids();
11461:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11462:         if ($is_me) {
11463:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11464:         } else {
11465:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11466:   	      $udom.'/'.$uname.'/'.$filename;
11467:         }
11468:     } elsif ($file =~ m-^/adm/-) {
11469: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11470:     } else {
11471:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11472:         $file=~s:^/(res|priv)/:/:;
11473:         my $space=$1;
11474:         if ( !( $file =~ m:^/:) ) {
11475:             $location = $dir. '/'.$file;
11476:         } else {
11477:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11478:         }
11479:     }
11480:     $location=~s://+:/:g; # remove duplicate /
11481:     while ($location=~m{/\.\./}) {
11482: 	if ($location =~ m{/[^/]+/\.\./}) {
11483: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11484: 	} else {
11485: 	    $location=~ s{/\.\./}{/}g;
11486: 	}
11487:     } #remove dir/..
11488:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11489:     return $location;
11490: }
11491: 
11492: sub hreflocation {
11493:     my ($dir,$file)=@_;
11494:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11495: 	$file=filelocation($dir,$file);
11496:     } elsif ($file=~m-^/adm/-) {
11497: 	$file=~s-^/adm/wrapper/-/-;
11498: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11499:     }
11500:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11501: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11502:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11503: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11504: 	        {/uploaded/$1/$2/}x;
11505:     }
11506:     if ($file=~ m{^/userfiles/}) {
11507: 	$file =~ s{^/userfiles/}{/uploaded/};
11508:     }
11509:     return $file;
11510: }
11511: 
11512: 
11513: 
11514: 
11515: 
11516: sub current_machine_domains {
11517:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11518: }
11519: 
11520: sub machine_domains {
11521:     my ($hostname) = @_;
11522:     my @domains;
11523:     my %hostname = &all_hostnames();
11524:     while( my($id, $name) = each(%hostname)) {
11525: #	&logthis("-$id-$name-$hostname-");
11526: 	if ($hostname eq $name) {
11527: 	    push(@domains,&host_domain($id));
11528: 	}
11529:     }
11530:     return @domains;
11531: }
11532: 
11533: sub current_machine_ids {
11534:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11535: }
11536: 
11537: sub machine_ids {
11538:     my ($hostname) = @_;
11539:     $hostname ||= &hostname($perlvar{'lonHostID'});
11540:     my @ids;
11541:     my %name_to_host = &all_names();
11542:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11543: 	return @{ $name_to_host{$hostname} };
11544:     }
11545:     return;
11546: }
11547: 
11548: sub additional_machine_domains {
11549:     my @domains;
11550:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11551:     while( my $line = <$fh>) {
11552:         $line =~ s/\s//g;
11553:         push(@domains,$line);
11554:     }
11555:     return @domains;
11556: }
11557: 
11558: sub default_login_domain {
11559:     my $domain = $perlvar{'lonDefDomain'};
11560:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11561:     foreach my $posdom (&current_machine_domains(),
11562:                         &additional_machine_domains()) {
11563:         if (lc($posdom) eq lc($testdomain)) {
11564:             $domain=$posdom;
11565:             last;
11566:         }
11567:     }
11568:     return $domain;
11569: }
11570: 
11571: # ------------------------------------------------------------- Declutters URLs
11572: 
11573: sub declutter {
11574:     my $thisfn=shift;
11575:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11576:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11577:     $thisfn=~s/^\///;
11578:     $thisfn=~s|^adm/wrapper/||;
11579:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11580:     $thisfn=~s/^res\///;
11581:     $thisfn=~s/^priv\///;
11582:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11583:         $thisfn=~s/\?.+$//;
11584:     }
11585:     return $thisfn;
11586: }
11587: 
11588: # ------------------------------------------------------------- Clutter up URLs
11589: 
11590: sub clutter {
11591:     my $thisfn='/'.&declutter(shift);
11592:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11593: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11594:        $thisfn='/res'.$thisfn; 
11595:     }
11596:     if ($thisfn !~m|^/adm|) {
11597: 	if ($thisfn =~ m|^/ext/|) {
11598: 	    $thisfn='/adm/wrapper'.$thisfn;
11599: 	} else {
11600: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11601: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11602: 	    if ($embstyle eq 'ssi'
11603: 		|| ($embstyle eq 'hdn')
11604: 		|| ($embstyle eq 'rat')
11605: 		|| ($embstyle eq 'prv')
11606: 		|| ($embstyle eq 'ign')) {
11607: 		#do nothing with these
11608: 	    } elsif (($embstyle eq 'img') 
11609: 		|| ($embstyle eq 'emb')
11610: 		|| ($embstyle eq 'wrp')) {
11611: 		$thisfn='/adm/wrapper'.$thisfn;
11612: 	    } elsif ($embstyle eq 'unk'
11613: 		     && $thisfn!~/\.(sequence|page)$/) {
11614: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11615: 	    } else {
11616: #		&logthis("Got a blank emb style");
11617: 	    }
11618: 	}
11619:     }
11620:     return $thisfn;
11621: }
11622: 
11623: sub clutter_with_no_wrapper {
11624:     my $uri = &clutter(shift);
11625:     if ($uri =~ m-^/adm/-) {
11626: 	$uri =~ s-^/adm/wrapper/-/-;
11627: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11628:     }
11629:     return $uri;
11630: }
11631: 
11632: sub freeze_escape {
11633:     my ($value)=@_;
11634:     if (ref($value)) {
11635: 	$value=&nfreeze($value);
11636: 	return '__FROZEN__'.&escape($value);
11637:     }
11638:     return &escape($value);
11639: }
11640: 
11641: 
11642: sub thaw_unescape {
11643:     my ($value)=@_;
11644:     if ($value =~ /^__FROZEN__/) {
11645: 	substr($value,0,10,undef);
11646: 	$value=&unescape($value);
11647: 	return &thaw($value);
11648:     }
11649:     return &unescape($value);
11650: }
11651: 
11652: sub correct_line_ends {
11653:     my ($result)=@_;
11654:     $$result =~s/\r\n/\n/mg;
11655:     $$result =~s/\r/\n/mg;
11656: }
11657: # ================================================================ Main Program
11658: 
11659: sub goodbye {
11660:    &logthis("Starting Shut down");
11661: #not converted to using infrastruture and probably shouldn't be
11662:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11663: #converted
11664: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11665:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11666: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11667: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11668: #1.1 only
11669: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11670: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11671: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11672: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11673:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11674:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11675:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11676:    &flushcourselogs();
11677:    &logthis("Shutting down");
11678: }
11679: 
11680: sub get_dns {
11681:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11682:     if (!$ignore_cache) {
11683: 	my ($content,$cached)=
11684: 	    &Apache::lonnet::is_cached_new('dns',$url);
11685: 	if ($cached) {
11686: 	    &$func($content,$hashref);
11687: 	    return;
11688: 	}
11689:     }
11690: 
11691:     my %alldns;
11692:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11693:     foreach my $dns (<$config>) {
11694: 	next if ($dns !~ /^\^(\S*)/x);
11695:         my $line = $1;
11696:         my ($host,$protocol) = split(/:/,$line);
11697:         if ($protocol ne 'https') {
11698:             $protocol = 'http';
11699:         }
11700: 	$alldns{$host} = $protocol;
11701:     }
11702:     while (%alldns) {
11703: 	my ($dns) = keys(%alldns);
11704: 	my $ua=new LWP::UserAgent;
11705:         $ua->timeout(30);
11706: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11707: 	my $response=$ua->request($request);
11708:         delete($alldns{$dns});
11709: 	next if ($response->is_error());
11710: 	my @content = split("\n",$response->content);
11711: 	unless ($nocache) {
11712: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11713: 	}
11714: 	&$func(\@content,$hashref);
11715: 	return;
11716:     }
11717:     close($config);
11718:     my $which = (split('/',$url))[3];
11719:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11720:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11721:     my @content = <$config>;
11722:     &$func(\@content,$hashref);
11723:     return;
11724: }
11725: 
11726: # ------------------------------------------------------Get DNS checksums file
11727: sub parse_dns_checksums_tab {
11728:     my ($lines,$hashref) = @_;
11729:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11730:     my $loncaparev = &get_server_loncaparev($machine_dom);
11731:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11732:     my (%chksum,%revnum);
11733:     if (ref($lines) eq 'ARRAY') {
11734:         chomp(@{$lines});
11735:         my $version = shift(@{$lines});
11736:         if ($version eq $release) {  
11737:             foreach my $line (@{$lines}) {
11738:                 my ($file,$version,$shasum) = split(/,/,$line);
11739:                 $chksum{$file} = $shasum;
11740:                 $revnum{$file} = $version;
11741:             }
11742:             if (ref($hashref) eq 'HASH') {
11743:                 %{$hashref} = (
11744:                                 sums     => \%chksum,
11745:                                 versions => \%revnum,
11746:                               );
11747:             }
11748:         }
11749:     }
11750:     return;
11751: }
11752: 
11753: sub fetch_dns_checksums {
11754:     my %checksums;
11755:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11756:     my $loncaparev = &get_server_loncaparev($machine_dom);
11757:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11758:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11759:              \%checksums);
11760:     return \%checksums;
11761: }
11762: 
11763: # ------------------------------------------------------------ Read domain file
11764: {
11765:     my $loaded;
11766:     my %domain;
11767: 
11768:     sub parse_domain_tab {
11769: 	my ($lines) = @_;
11770: 	foreach my $line (@$lines) {
11771: 	    next if ($line =~ /^(\#|\s*$ )/x);
11772: 
11773: 	    chomp($line);
11774: 	    my ($name,@elements) = split(/:/,$line,9);
11775: 	    my %this_domain;
11776: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11777: 			       'lang_def', 'city', 'longi', 'lati',
11778: 			       'primary') {
11779: 		$this_domain{$field} = shift(@elements);
11780: 	    }
11781: 	    $domain{$name} = \%this_domain;
11782: 	}
11783:     }
11784: 
11785:     sub reset_domain_info {
11786: 	undef($loaded);
11787: 	undef(%domain);
11788:     }
11789: 
11790:     sub load_domain_tab {
11791: 	my ($ignore_cache) = @_;
11792: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11793: 	my $fh;
11794: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11795: 	    my @lines = <$fh>;
11796: 	    &parse_domain_tab(\@lines);
11797: 	}
11798: 	close($fh);
11799: 	$loaded = 1;
11800:     }
11801: 
11802:     sub domain {
11803: 	&load_domain_tab() if (!$loaded);
11804: 
11805: 	my ($name,$what) = @_;
11806: 	return if ( !exists($domain{$name}) );
11807: 
11808: 	if (!$what) {
11809: 	    return $domain{$name}{'description'};
11810: 	}
11811: 	return $domain{$name}{$what};
11812:     }
11813: 
11814:     sub domain_info {
11815:         &load_domain_tab() if (!$loaded);
11816:         return %domain;
11817:     }
11818: 
11819: }
11820: 
11821: 
11822: # ------------------------------------------------------------- Read hosts file
11823: {
11824:     my %hostname;
11825:     my %hostdom;
11826:     my %libserv;
11827:     my $loaded;
11828:     my %name_to_host;
11829:     my %internetdom;
11830:     my %LC_dns_serv;
11831: 
11832:     sub parse_hosts_tab {
11833: 	my ($file) = @_;
11834: 	foreach my $configline (@$file) {
11835: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11836:             chomp($configline);
11837: 	    if ($configline =~ /^\^/) {
11838:                 if ($configline =~ /^\^([\w.\-]+)/) {
11839:                     $LC_dns_serv{$1} = 1;
11840:                 }
11841:                 next;
11842:             }
11843: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11844: 	    $name=~s/\s//g;
11845: 	    if ($id && $domain && $role && $name) {
11846: 		$hostname{$id}=$name;
11847: 		push(@{$name_to_host{$name}}, $id);
11848: 		$hostdom{$id}=$domain;
11849: 		if ($role eq 'library') { $libserv{$id}=$name; }
11850:                 if (defined($protocol)) {
11851:                     if ($protocol eq 'https') {
11852:                         $protocol{$id} = $protocol;
11853:                     } else {
11854:                         $protocol{$id} = 'http'; 
11855:                     }
11856:                 } else {
11857:                     $protocol{$id} = 'http';
11858:                 }
11859:                 if (defined($intdom)) {
11860:                     $internetdom{$id} = $intdom;
11861:                 }
11862: 	    }
11863: 	}
11864:     }
11865:     
11866:     sub reset_hosts_info {
11867: 	&purge_remembered();
11868: 	&reset_domain_info();
11869: 	&reset_hosts_ip_info();
11870: 	undef(%name_to_host);
11871: 	undef(%hostname);
11872: 	undef(%hostdom);
11873: 	undef(%libserv);
11874: 	undef($loaded);
11875:     }
11876: 
11877:     sub load_hosts_tab {
11878: 	my ($ignore_cache) = @_;
11879: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11880: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11881: 	my @config = <$config>;
11882: 	&parse_hosts_tab(\@config);
11883: 	close($config);
11884: 	$loaded=1;
11885:     }
11886: 
11887:     sub hostname {
11888: 	&load_hosts_tab() if (!$loaded);
11889: 
11890: 	my ($lonid) = @_;
11891: 	return $hostname{$lonid};
11892:     }
11893: 
11894:     sub all_hostnames {
11895: 	&load_hosts_tab() if (!$loaded);
11896: 
11897: 	return %hostname;
11898:     }
11899: 
11900:     sub all_names {
11901: 	&load_hosts_tab() if (!$loaded);
11902: 
11903: 	return %name_to_host;
11904:     }
11905: 
11906:     sub all_host_domain {
11907:         &load_hosts_tab() if (!$loaded);
11908:         return %hostdom;
11909:     }
11910: 
11911:     sub is_library {
11912: 	&load_hosts_tab() if (!$loaded);
11913: 
11914: 	return exists($libserv{$_[0]});
11915:     }
11916: 
11917:     sub all_library {
11918: 	&load_hosts_tab() if (!$loaded);
11919: 
11920: 	return %libserv;
11921:     }
11922: 
11923:     sub unique_library {
11924: 	#2x reverse removes all hostnames that appear more than once
11925:         my %unique = reverse &all_library();
11926:         return reverse %unique;
11927:     }
11928: 
11929:     sub get_servers {
11930: 	&load_hosts_tab() if (!$loaded);
11931: 
11932: 	my ($domain,$type) = @_;
11933: 	my %possible_hosts = ($type eq 'library') ? %libserv
11934: 	                                          : %hostname;
11935: 	my %result;
11936: 	if (ref($domain) eq 'ARRAY') {
11937: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11938: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11939: 		    $result{$host} = $hostname;
11940: 		}
11941: 	    }
11942: 	} else {
11943: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11944: 		if ($hostdom{$host} eq $domain) {
11945: 		    $result{$host} = $hostname;
11946: 		}
11947: 	    }
11948: 	}
11949: 	return %result;
11950:     }
11951: 
11952:     sub get_unique_servers {
11953:         my %unique = reverse &get_servers(@_);
11954: 	return reverse %unique;
11955:     }
11956: 
11957:     sub host_domain {
11958: 	&load_hosts_tab() if (!$loaded);
11959: 
11960: 	my ($lonid) = @_;
11961: 	return $hostdom{$lonid};
11962:     }
11963: 
11964:     sub all_domains {
11965: 	&load_hosts_tab() if (!$loaded);
11966: 
11967: 	my %seen;
11968: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11969: 	return @uniq;
11970:     }
11971: 
11972:     sub internet_dom {
11973:         &load_hosts_tab() if (!$loaded);
11974: 
11975:         my ($lonid) = @_;
11976:         return $internetdom{$lonid};
11977:     }
11978: 
11979:     sub is_LC_dns {
11980:         &load_hosts_tab() if (!$loaded);
11981: 
11982:         my ($hostname) = @_;
11983:         return exists($LC_dns_serv{$hostname});
11984:     }
11985: 
11986: }
11987: 
11988: { 
11989:     my %iphost;
11990:     my %name_to_ip;
11991:     my %lonid_to_ip;
11992: 
11993:     sub get_hosts_from_ip {
11994: 	my ($ip) = @_;
11995: 	my %iphosts = &get_iphost();
11996: 	if (ref($iphosts{$ip})) {
11997: 	    return @{$iphosts{$ip}};
11998: 	}
11999: 	return;
12000:     }
12001:     
12002:     sub reset_hosts_ip_info {
12003: 	undef(%iphost);
12004: 	undef(%name_to_ip);
12005: 	undef(%lonid_to_ip);
12006:     }
12007: 
12008:     sub get_host_ip {
12009: 	my ($lonid) = @_;
12010: 	if (exists($lonid_to_ip{$lonid})) {
12011: 	    return $lonid_to_ip{$lonid};
12012: 	}
12013: 	my $name=&hostname($lonid);
12014:    	my $ip = gethostbyname($name);
12015: 	return if (!$ip || length($ip) ne 4);
12016: 	$ip=inet_ntoa($ip);
12017: 	$name_to_ip{$name}   = $ip;
12018: 	$lonid_to_ip{$lonid} = $ip;
12019: 	return $ip;
12020:     }
12021:     
12022:     sub get_iphost {
12023: 	my ($ignore_cache) = @_;
12024: 
12025: 	if (!$ignore_cache) {
12026: 	    if (%iphost) {
12027: 		return %iphost;
12028: 	    }
12029: 	    my ($ip_info,$cached)=
12030: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12031: 	    if ($cached) {
12032: 		%iphost      = %{$ip_info->[0]};
12033: 		%name_to_ip  = %{$ip_info->[1]};
12034: 		%lonid_to_ip = %{$ip_info->[2]};
12035: 		return %iphost;
12036: 	    }
12037: 	}
12038: 
12039: 	# get yesterday's info for fallback
12040: 	my %old_name_to_ip;
12041: 	my ($ip_info,$cached)=
12042: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12043: 	if ($cached) {
12044: 	    %old_name_to_ip = %{$ip_info->[1]};
12045: 	}
12046: 
12047: 	my %name_to_host = &all_names();
12048: 	foreach my $name (keys(%name_to_host)) {
12049: 	    my $ip;
12050: 	    if (!exists($name_to_ip{$name})) {
12051: 		$ip = gethostbyname($name);
12052: 		if (!$ip || length($ip) ne 4) {
12053: 		    if (defined($old_name_to_ip{$name})) {
12054: 			$ip = $old_name_to_ip{$name};
12055: 			&logthis("Can't find $name defaulting to old $ip");
12056: 		    } else {
12057: 			&logthis("Name $name no IP found");
12058: 			next;
12059: 		    }
12060: 		} else {
12061: 		    $ip=inet_ntoa($ip);
12062: 		}
12063: 		$name_to_ip{$name} = $ip;
12064: 	    } else {
12065: 		$ip = $name_to_ip{$name};
12066: 	    }
12067: 	    foreach my $id (@{ $name_to_host{$name} }) {
12068: 		$lonid_to_ip{$id} = $ip;
12069: 	    }
12070: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12071: 	}
12072: 	&do_cache_new('iphost','iphost',
12073: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12074: 		      48*60*60);
12075: 
12076: 	return %iphost;
12077:     }
12078: 
12079:     #
12080:     #  Given a DNS returns the loncapa host name for that DNS 
12081:     # 
12082:     sub host_from_dns {
12083:         my ($dns) = @_;
12084:         my @hosts;
12085:         my $ip;
12086: 
12087:         if (exists($name_to_ip{$dns})) {
12088:             $ip = $name_to_ip{$dns};
12089:         }
12090:         if (!$ip) {
12091:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12092:             if (length($ip) == 4) { 
12093: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12094:             }
12095:         }
12096:         if ($ip) {
12097: 	    @hosts = get_hosts_from_ip($ip);
12098: 	    return $hosts[0];
12099:         }
12100:         return undef;
12101:     }
12102: 
12103:     sub get_internet_names {
12104:         my ($lonid) = @_;
12105:         return if ($lonid eq '');
12106:         my ($idnref,$cached)=
12107:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12108:         if ($cached) {
12109:             return $idnref;
12110:         }
12111:         my $ip = &get_host_ip($lonid);
12112:         my @hosts = &get_hosts_from_ip($ip);
12113:         my %iphost = &get_iphost();
12114:         my (@idns,%seen);
12115:         foreach my $id (@hosts) {
12116:             my $dom = &host_domain($id);
12117:             my $prim_id = &domain($dom,'primary');
12118:             my $prim_ip = &get_host_ip($prim_id);
12119:             next if ($seen{$prim_ip});
12120:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12121:                 foreach my $id (@{$iphost{$prim_ip}}) {
12122:                     my $intdom = &internet_dom($id);
12123:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12124:                         push(@idns,$intdom);
12125:                     }
12126:                 }
12127:             }
12128:             $seen{$prim_ip} = 1;
12129:         }
12130:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12131:     }
12132: 
12133: }
12134: 
12135: sub all_loncaparevs {
12136:     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);
12137: }
12138: 
12139: # ---------------------------------------------------------- Read loncaparev table
12140: {
12141:     sub load_loncaparevs { 
12142:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12143:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12144:                 while (my $configline=<$config>) {
12145:                     chomp($configline);
12146:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12147:                     $loncaparevs{$hostid}=$loncaparev;
12148:                 }
12149:                 close($config);
12150:             }
12151:         }
12152:     }
12153: }
12154: 
12155: # ---------------------------------------------------------- Read serverhostID table
12156: {
12157:     sub load_serverhomeIDs {
12158:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12159:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12160:                 while (my $configline=<$config>) {
12161:                     chomp($configline);
12162:                     my ($name,$id)=split(/:/,$configline);
12163:                     $serverhomeIDs{$name}=$id;
12164:                 }
12165:                 close($config);
12166:             }
12167:         }
12168:     }
12169: }
12170: 
12171: 
12172: BEGIN {
12173: 
12174: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12175:     unless ($readit) {
12176: {
12177:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12178:     %perlvar = (%perlvar,%{$configvars});
12179: }
12180: 
12181: 
12182: # ------------------------------------------------------ Read spare server file
12183: {
12184:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12185: 
12186:     while (my $configline=<$config>) {
12187:        chomp($configline);
12188:        if ($configline) {
12189: 	   my ($host,$type) = split(':',$configline,2);
12190: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12191: 	   push(@{ $spareid{$type} }, $host);
12192:        }
12193:     }
12194:     close($config);
12195: }
12196: # ------------------------------------------------------------ Read permissions
12197: {
12198:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12199: 
12200:     while (my $configline=<$config>) {
12201: 	chomp($configline);
12202: 	if ($configline) {
12203: 	    my ($role,$perm)=split(/ /,$configline);
12204: 	    if ($perm ne '') { $pr{$role}=$perm; }
12205: 	}
12206:     }
12207:     close($config);
12208: }
12209: 
12210: # -------------------------------------------- Read plain texts for permissions
12211: {
12212:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12213: 
12214:     while (my $configline=<$config>) {
12215: 	chomp($configline);
12216: 	if ($configline) {
12217: 	    my ($short,@plain)=split(/:/,$configline);
12218:             %{$prp{$short}} = ();
12219: 	    if (@plain > 0) {
12220:                 $prp{$short}{'std'} = $plain[0];
12221:                 for (my $i=1; $i<@plain; $i++) {
12222:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12223:                 }
12224:             }
12225: 	}
12226:     }
12227:     close($config);
12228: }
12229: 
12230: # ---------------------------------------------------------- Read package table
12231: {
12232:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12233: 
12234:     while (my $configline=<$config>) {
12235: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12236: 	chomp($configline);
12237: 	my ($short,$plain)=split(/:/,$configline);
12238: 	my ($pack,$name)=split(/\&/,$short);
12239: 	if ($plain ne '') {
12240: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12241: 	    $packagetab{$short}=$plain; 
12242: 	}
12243:     }
12244:     close($config);
12245: }
12246: 
12247: # ---------------------------------------------------------- Read loncaparev table
12248: 
12249: &load_loncaparevs();
12250: 
12251: # ---------------------------------------------------------- Read serverhostID table
12252: 
12253: &load_serverhomeIDs();
12254: 
12255: # ---------------------------------------------------------- Read releaseslist XML
12256: {
12257:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12258:     if (-e $file) {
12259:         my $parser = HTML::LCParser->new($file);
12260:         while (my $token = $parser->get_token()) {
12261:             if ($token->[0] eq 'S') {
12262:                 my $item = $token->[1];
12263:                 my $name = $token->[2]{'name'};
12264:                 my $value = $token->[2]{'value'};
12265:                 if ($item ne '' && $name ne '' && $value ne '') {
12266:                     my $release = $parser->get_text();
12267:                     $release =~ s/(^\s*|\s*$ )//gx;
12268:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12269:                 }
12270:             }
12271:         }
12272:     }
12273: }
12274: 
12275: # ---------------------------------------------------------- Read managers table
12276: {
12277:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12278:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12279:             while (my $configline=<$config>) {
12280:                 chomp($configline);
12281:                 next if ($configline =~ /^\#/);
12282:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12283:                     $managerstab{$configline} = 1;
12284:                 }
12285:             }
12286:             close($config);
12287:         }
12288:     }
12289: }
12290: 
12291: # ------------- set up temporary directory
12292: {
12293:     $tmpdir = LONCAPA::tempdir();
12294: 
12295: }
12296: 
12297: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12298: 				'compress_threshold'=> 20_000,
12299:  			        });
12300: 
12301: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12302: $dumpcount=0;
12303: $locknum=0;
12304: 
12305: &logtouch();
12306: &logthis('<font color="yellow">INFO: Read configuration</font>');
12307: $readit=1;
12308:     {
12309: 	use integer;
12310: 	my $test=(2**32)+1;
12311: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12312: 	&logthis(" Detected 64bit platform ($_64bit)");
12313:     }
12314: 
12315:     {
12316:         eval {
12317:             ($apache) =
12318:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12319:         };
12320:         if ($@) {
12321:            $apache = 1.3;
12322:         }
12323:     }
12324: 
12325: }
12326: }
12327: 
12328: 1;
12329: __END__
12330: 
12331: =pod
12332: 
12333: =head1 NAME
12334: 
12335: Apache::lonnet - Subroutines to ask questions about things in the network.
12336: 
12337: =head1 SYNOPSIS
12338: 
12339: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12340: 
12341:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12342: 
12343: Common parameters:
12344: 
12345: =over 4
12346: 
12347: =item *
12348: 
12349: $uname : an internal username (if $cname expecting a course Id specifically)
12350: 
12351: =item *
12352: 
12353: $udom : a domain (if $cdom expecting a course's domain specifically)
12354: 
12355: =item *
12356: 
12357: $symb : a resource instance identifier
12358: 
12359: =item *
12360: 
12361: $namespace : the name of a .db file that contains the data needed or
12362: being set.
12363: 
12364: =back
12365: 
12366: =head1 OVERVIEW
12367: 
12368: lonnet provides subroutines which interact with the
12369: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12370: about classes, users, and resources.
12371: 
12372: For many of these objects you can also use this to store data about
12373: them or modify them in various ways.
12374: 
12375: =head2 Symbs
12376: 
12377: To identify a specific instance of a resource, LON-CAPA uses symbols
12378: or "symbs"X<symb>. These identifiers are built from the URL of the
12379: map, the resource number of the resource in the map, and the URL of
12380: the resource itself. The latter is somewhat redundant, but might help
12381: if maps change.
12382: 
12383: An example is
12384: 
12385:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12386: 
12387: The respective map entry is
12388: 
12389:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12390:   title="Problem 2">
12391:  </resource>
12392: 
12393: Symbs are used by the random number generator, as well as to store and
12394: restore data specific to a certain instance of for example a problem.
12395: 
12396: =head2 Storing And Retrieving Data
12397: 
12398: X<store()>X<cstore()>X<restore()>Three of the most important functions
12399: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12400: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12401: is is the non-critical message twin of cstore. These functions are for
12402: handlers to store a perl hash to a user's permanent data space in an
12403: easy manner, and to retrieve it again on another call. It is expected
12404: that a handler would use this once at the beginning to retrieve data,
12405: and then again once at the end to send only the new data back.
12406: 
12407: The data is stored in the user's data directory on the user's
12408: homeserver under the ID of the course.
12409: 
12410: The hash that is returned by restore will have all of the previous
12411: value for all of the elements of the hash.
12412: 
12413: Example:
12414: 
12415:  #creating a hash
12416:  my %hash;
12417:  $hash{'foo'}='bar';
12418: 
12419:  #storing it
12420:  &Apache::lonnet::cstore(\%hash);
12421: 
12422:  #changing a value
12423:  $hash{'foo'}='notbar';
12424: 
12425:  #adding a new value
12426:  $hash{'bar'}='foo';
12427:  &Apache::lonnet::cstore(\%hash);
12428: 
12429:  #retrieving the hash
12430:  my %history=&Apache::lonnet::restore();
12431: 
12432:  #print the hash
12433:  foreach my $key (sort(keys(%history))) {
12434:    print("\%history{$key} = $history{$key}");
12435:  }
12436: 
12437: Will print out:
12438: 
12439:  %history{1:foo} = bar
12440:  %history{1:keys} = foo:timestamp
12441:  %history{1:timestamp} = 990455579
12442:  %history{2:bar} = foo
12443:  %history{2:foo} = notbar
12444:  %history{2:keys} = foo:bar:timestamp
12445:  %history{2:timestamp} = 990455580
12446:  %history{bar} = foo
12447:  %history{foo} = notbar
12448:  %history{timestamp} = 990455580
12449:  %history{version} = 2
12450: 
12451: Note that the special hash entries C<keys>, C<version> and
12452: C<timestamp> were added to the hash. C<version> will be equal to the
12453: total number of versions of the data that have been stored. The
12454: C<timestamp> attribute will be the UNIX time the hash was
12455: stored. C<keys> is available in every historical section to list which
12456: keys were added or changed at a specific historical revision of a
12457: hash.
12458: 
12459: B<Warning>: do not store the hash that restore returns directly. This
12460: will cause a mess since it will restore the historical keys as if the
12461: were new keys. I.E. 1:foo will become 1:1:foo etc.
12462: 
12463: Calling convention:
12464: 
12465:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12466:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12467: 
12468: For more detailed information, see lonnet specific documentation.
12469: 
12470: =head1 RETURN MESSAGES
12471: 
12472: =over 4
12473: 
12474: =item * B<con_lost>: unable to contact remote host
12475: 
12476: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12477: when the connection is brought back up
12478: 
12479: =item * B<con_failed>: unable to contact remote host and unable to save message
12480: for later delivery
12481: 
12482: =item * B<error:>: an error a occurred, a description of the error follows the :
12483: 
12484: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12485: that was requested
12486: 
12487: =back
12488: 
12489: =head1 PUBLIC SUBROUTINES
12490: 
12491: =head2 Session Environment Functions
12492: 
12493: =over 4
12494: 
12495: =item * 
12496: X<appenv()>
12497: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12498: the user envirnoment file, and will be restored for each access this
12499: user makes during this session, also modifies the %env for the current
12500: process. Optional rolesarrayref - if defined contains a reference to an array
12501: of roles which are exempt from the restriction on modifying user.role entries 
12502: in the user's environment.db and in %env.    
12503: 
12504: =item *
12505: X<delenv()>
12506: B<delenv($delthis,$regexp)>: removes all items from the session
12507: environment file that begin with $delthis. If the 
12508: optional second arg - $regexp - is true, $delthis is treated as a 
12509: regular expression, otherwise \Q$delthis\E is used. 
12510: The values are also deleted from the current processes %env.
12511: 
12512: =item * get_env_multiple($name) 
12513: 
12514: gets $name from the %env hash, it seemlessly handles the cases where multiple
12515: values may be defined and end up as an array ref.
12516: 
12517: returns an array of values
12518: 
12519: =back
12520: 
12521: =head2 User Information
12522: 
12523: =over 4
12524: 
12525: =item *
12526: X<queryauthenticate()>
12527: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12528: authentication scheme
12529: 
12530: =item *
12531: X<authenticate()>
12532: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12533: authenticate user from domain's lib servers (first use the current
12534: one). C<$upass> should be the users password.
12535: $checkdefauth is optional (value is 1 if a check should be made to
12536:    authenticate user using default authentication method, and allow
12537:    account creation if username does not have account in the domain).
12538: $clientcancheckhost is optional (value is 1 if checking whether the
12539:    server can host will occur on the client side in lonauth.pm).   
12540: 
12541: =item *
12542: X<homeserver()>
12543: B<homeserver($uname,$udom)>: find the server which has
12544: the user's directory and files (there must be only one), this caches
12545: the answer, and also caches if there is a borken connection.
12546: 
12547: =item *
12548: X<idget()>
12549: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12550: (IDs are a unique resource in a domain, there must be only 1 ID per
12551: username, and only 1 username per ID in a specific domain) (returns
12552: hash: id=>name,id=>name)
12553: 
12554: =item *
12555: X<idrget()>
12556: B<idrget($udom,@unames)>: find the IDs behind a list of
12557: usernames (returns hash: name=>id,name=>id)
12558: 
12559: =item *
12560: X<idput()>
12561: B<idput($udom,%ids)>: store away a list of names and associated IDs
12562: 
12563: =item *
12564: X<rolesinit()>
12565: B<rolesinit($udom,$username)>: get user privileges.
12566: returns user role, first access and timer interval hashes
12567: 
12568: =item *
12569: X<privileged()>
12570: B<privileged($username,$domain)>: returns a true if user has a
12571: privileged and active role (i.e. su or dc), false otherwise.
12572: 
12573: =item *
12574: X<getsection()>
12575: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12576: course $cname, return section name/number or '' for "not in course"
12577: and '-1' for "no section"
12578: 
12579: =item *
12580: X<userenvironment()>
12581: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12582: passed in @what from the requested user's environment, returns a hash
12583: 
12584: =item * 
12585: X<userlog_query()>
12586: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12587: activity.log file. %filters defines filters applied when parsing the
12588: log file. These can be start or end timestamps, or the type of action
12589: - log to look for Login or Logout events, check for Checkin or
12590: Checkout, role for role selection. The response is in the form
12591: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12592: escaped strings of the action recorded in the activity.log file.
12593: 
12594: =back
12595: 
12596: =head2 User Roles
12597: 
12598: =over 4
12599: 
12600: =item *
12601: 
12602: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12603:  F: full access
12604:  U,I,K: authentication modes (cxx only)
12605:  '': forbidden
12606:  1: user needs to choose course
12607:  2: browse allowed
12608:  A: passphrase authentication needed
12609: 
12610: =item *
12611: 
12612: constructaccess($url,$setpriv) : check for access to construction space URL
12613: 
12614: See if the owner domain and name in the URL match those in the
12615: expected environment.  If so, return three element list
12616: ($ownername,$ownerdomain,$ownerhome).
12617: 
12618: Otherwise return the null string.
12619: 
12620: If second argument 'setpriv' is true, it assigns the privileges,
12621: and returns the same three element list, unless the owner has
12622: blocked "ad hoc" Domain Coordinator access to the Author Space,
12623: in which case the null string is returned.
12624: 
12625: =item *
12626: 
12627: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12628: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12629: and course level
12630: 
12631: =item *
12632: 
12633: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12634: (rolesplain.tab); plain text explanation of a user role term.
12635: $type is Course (default) or Community.
12636: If $forcedefault evaluates to true, text returned will be default 
12637: text for $type. Otherwise, if this is a course, the text returned 
12638: will be a custom name for the role (if defined in the course's 
12639: environment).  If no custom name is defined the default is returned.
12640:    
12641: =item *
12642: 
12643: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12644: All arguments are optional. Returns a hash of a roles, either for
12645: co-author/assistant author roles for a user's Construction Space
12646: (default), or if $context is 'userroles', roles for the user himself,
12647: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12648: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12649: For each key, value is set to colon-separated start and end times for
12650: the role.  If no username and domain are specified, will default to
12651: current user/domain. Types, roles, and roledoms are references to arrays
12652: of role statuses (active, future or previous), roles 
12653: (e.g., cc,in, st etc.) and domains of the roles which can be used
12654: to restrict the list of roles reported. If no array ref is 
12655: provided for types, will default to return only active roles.
12656: 
12657: =item *
12658: 
12659: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12660: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12661: 
12662: Additional optional arguments are: $type (if role checking is to be restricted 
12663: to certain user status types -- previous (expired roles), active (currently
12664: available roles) or future (roles available in the future), and
12665: $hideprivileged -- if true will not report course roles for users who
12666: have active Domain Coordinator role in course's domain or in additional
12667: domains (specified in 'Domains to check for privileged users' in course
12668: environment -- set via:  Course Settings -> Classlists and staff listing).
12669: 
12670: =item *
12671: 
12672: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12673: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12674: $possdomains and $possroles are optional array refs -- to domains to check and
12675: roles to check.  If $possdomains is not specified, a dump will be done of the
12676: users' roles.db to check for a dc or su role in any domain. This can be
12677: time consuming if &privileged is called repeatedly (e.g., when displaying a
12678: classlist), so in such cases, supplying a $possdomains array is preferred, as
12679: this then allows &privileged_by_domain() to be used, which caches the identity
12680: of privileged users, eliminating the need for repeated calls to &dump().
12681: 
12682: =item *
12683: 
12684: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12685: where the outer hash keys are domains specified in the $possdomains array ref,
12686: next inner hash keys are privileged roles specified in the $roles array ref,
12687: and the innermost hash contains key = value pairs for username:domain = end:start
12688: for active or future "privileged" users with that role in that domain. To avoid
12689: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12690: innerhash are cached using priv_$role and $dom as the identifiers.
12691: 
12692: =back
12693: 
12694: =head2 User Modification
12695: 
12696: =over 4
12697: 
12698: =item *
12699: 
12700: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12701: user for the level given by URL.  Optional start and end dates (leave empty
12702: string or zero for "no date")
12703: 
12704: =item *
12705: 
12706: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12707: change a users, password, possible return values are: ok,
12708: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12709: refused
12710: 
12711: =item *
12712: 
12713: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12714: 
12715: =item *
12716: 
12717: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12718:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12719: 
12720: will update user information (firstname,middlename,lastname,generation,
12721: permanentemail), and if forceid is true, student/employee ID also.
12722: A user's institutional affiliation(s) can also be updated.
12723: User information fields will not be overwritten with empty entries 
12724: unless the field is included in the $candelete array reference.
12725: This array is included when a single user is modified via "Manage Users",
12726: or when Autoupdate.pl is run by cron in a domain.
12727: 
12728: =item *
12729: 
12730: modifystudent
12731: 
12732: modify a student's enrollment and identification information.
12733: The course id is resolved based on the current user's environment.  
12734: This means the invoking user must be a course coordinator or otherwise
12735: associated with a course.
12736: 
12737: This call is essentially a wrapper for lonnet::modifyuser and
12738: lonnet::modify_student_enrollment
12739: 
12740: Inputs: 
12741: 
12742: =over 4
12743: 
12744: =item B<$udom> Student's loncapa domain
12745: 
12746: =item B<$uname> Student's loncapa login name
12747: 
12748: =item B<$uid> Student/Employee ID
12749: 
12750: =item B<$umode> Student's authentication mode
12751: 
12752: =item B<$upass> Student's password
12753: 
12754: =item B<$first> Student's first name
12755: 
12756: =item B<$middle> Student's middle name
12757: 
12758: =item B<$last> Student's last name
12759: 
12760: =item B<$gene> Student's generation
12761: 
12762: =item B<$usec> Student's section in course
12763: 
12764: =item B<$end> Unix time of the roles expiration
12765: 
12766: =item B<$start> Unix time of the roles start date
12767: 
12768: =item B<$forceid> If defined, allow $uid to be changed
12769: 
12770: =item B<$desiredhome> server to use as home server for student
12771: 
12772: =item B<$email> Student's permanent e-mail address
12773: 
12774: =item B<$type> Type of enrollment (auto or manual)
12775: 
12776: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12777: 
12778: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12779: 
12780: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12781: 
12782: =item B<$context> role change context (shown in User Management Logs display in a course)
12783: 
12784: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12785: 
12786: =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.
12787: 
12788: =back
12789: 
12790: =item *
12791: 
12792: modify_student_enrollment
12793: 
12794: Change a student's enrollment status in a class.  The environment variable
12795: 'role.request.course' must be defined for this function to proceed.
12796: 
12797: Inputs:
12798: 
12799: =over 4
12800: 
12801: =item $udom, student's domain
12802: 
12803: =item $uname, student's name
12804: 
12805: =item $uid, student's user id
12806: 
12807: =item $first, student's first name
12808: 
12809: =item $middle
12810: 
12811: =item $last
12812: 
12813: =item $gene
12814: 
12815: =item $usec
12816: 
12817: =item $end
12818: 
12819: =item $start
12820: 
12821: =item $type
12822: 
12823: =item $locktype
12824: 
12825: =item $cid
12826: 
12827: =item $selfenroll
12828: 
12829: =item $context
12830: 
12831: =item $credits, number of credits student will earn from this class
12832: 
12833: =back
12834: 
12835: 
12836: =item *
12837: 
12838: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12839: custom role; give a custom role to a user for the level given by URL.  Specify
12840: name and domain of role author, and role name
12841: 
12842: =item *
12843: 
12844: revokerole($udom,$uname,$url,$role) : revoke a role for url
12845: 
12846: =item *
12847: 
12848: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12849: 
12850: =back
12851: 
12852: =head2 Course Infomation
12853: 
12854: =over 4
12855: 
12856: =item *
12857: 
12858: coursedescription($courseid,$options) : returns a hash of information about the
12859: specified course id, including all environment settings for the
12860: course, the description of the course will be in the hash under the
12861: key 'description'
12862: 
12863: $options is an optional parameter that if supplied is a hash reference that controls
12864: what how this function works.  It has the following key/values:
12865: 
12866: =over 4
12867: 
12868: =item freshen_cache
12869: 
12870: If defined, and the environment cache for the course is valid, it is 
12871: returned in the returned hash.
12872: 
12873: =item one_time
12874: 
12875: If defined, the last cache time is set to _now_
12876: 
12877: =item user
12878: 
12879: If defined, the supplied username is used instead of the current user.
12880: 
12881: 
12882: =back
12883: 
12884: =item *
12885: 
12886: resdata($name,$domain,$type,@which) : request for current parameter
12887: setting for a specific $type, where $type is either 'course' or 'user',
12888: @what should be a list of parameters to ask about. This routine caches
12889: answers for 10 minutes.
12890: 
12891: =item *
12892: 
12893: get_courseresdata($courseid, $domain) : dump the entire course resource
12894: data base, returning a hash that is keyed by the resource name and has
12895: values that are the resource value.  I believe that the timestamps and
12896: versions are also returned.
12897: 
12898: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12899: supplemental content area. This routine caches the number of files for 
12900: 10 minutes.
12901: 
12902: =back
12903: 
12904: =head2 Course Modification
12905: 
12906: =over 4
12907: 
12908: =item *
12909: 
12910: writecoursepref($courseid,%prefs) : write preferences (environment
12911: database) for a course
12912: 
12913: =item *
12914: 
12915: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12916: 
12917: =item *
12918: 
12919: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12920: 
12921: =item *
12922: 
12923: is_course($courseid), is_course($cdom, $cnum)
12924: 
12925: Accepts either a combined $courseid (in the form of domain_courseid) or the
12926: two component version $cdom, $cnum. It checks if the specified course exists.
12927: 
12928: Returns:
12929:     undef if the course doesn't exist, otherwise
12930:     in scalar context the combined courseid.
12931:     in list context the two components of the course identifier, domain and 
12932:     courseid.    
12933: 
12934: =back
12935: 
12936: =head2 Resource Subroutines
12937: 
12938: =over 4
12939: 
12940: =item *
12941: 
12942: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12943: 
12944: =item *
12945: 
12946: repcopy($filename) : subscribes to the requested file, and attempts to
12947: replicate from the owning library server, Might return
12948: 'unavailable', 'not_found', 'forbidden', 'ok', or
12949: 'bad_request', also attempts to grab the metadata for the
12950: resource. Expects the local filesystem pathname
12951: (/home/httpd/html/res/....)
12952: 
12953: =back
12954: 
12955: =head2 Resource Information
12956: 
12957: =over 4
12958: 
12959: =item *
12960: 
12961: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12962: and returns the value of a variety of different possible values,
12963: $varname should be a request string, and the other parameters can be
12964: used to specify who and what one is asking about. Ordinarily, $cid 
12965: does not need to be specified, as it is retrived from 
12966: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12967: within lonuserstate::loadmap() when initializing a course, before
12968: $env{'request.course.id'} has been set, so it needs to be provided
12969: in that one case.
12970: 
12971: Possible values for $varname are environment.lastname (or other item
12972: from the envirnment hash), user.name (or someother aspect about the
12973: user), resource.0.maxtries (or some other part and parameter of a
12974: resource)
12975: 
12976: =item *
12977: 
12978: directcondval($number) : get current value of a condition; reads from a state
12979: string
12980: 
12981: =item *
12982: 
12983: condval($condidx) : value of condition index based on state
12984: 
12985: =item *
12986: 
12987: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12988: resource's metadata, $what should be either a specific key, or either
12989: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12990: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12991: 
12992: this function automatically caches all requests
12993: 
12994: =item *
12995: 
12996: metadata_query($query,$custom,$customshow) : make a metadata query against the
12997: network of library servers; returns file handle of where SQL and regex results
12998: will be stored for query
12999: 
13000: =item *
13001: 
13002: symbread($filename) : return symbolic list entry (filename argument optional);
13003: returns the data handle
13004: 
13005: =item *
13006: 
13007: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13008: and is a possible symb for the URL in $thisfn, and if is an encrypted
13009: resource that the user accessed using /enc/ returns a 1 on success, 0
13010: on failure, user must be in a course, as it assumes the existence of
13011: the course initial hash, and uses $env('request.course.id'}.  The third
13012: arg is an optional reference to a scalar.  If this arg is passed in the 
13013: call to symbverify, it will be set to 1 if the symb has been set to be 
13014: encrypted; otherwise it will be null.  
13015: 
13016: =item *
13017: 
13018: symbclean($symb) : removes versions numbers from a symb, returns the
13019: cleaned symb
13020: 
13021: =item *
13022: 
13023: is_on_map($uri) : checks if the $uri is somewhere on the current
13024: course map, user must be in a course for it to work.
13025: 
13026: =item *
13027: 
13028: numval($salt) : return random seed value (addend for rndseed)
13029: 
13030: =item *
13031: 
13032: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13033: a random seed, all arguments are optional, if they aren't sent it uses the
13034: environment to derive them. Note: if symb isn't sent and it can't get one
13035: from &symbread it will use the current time as its return value
13036: 
13037: =item *
13038: 
13039: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13040: unfakeable, receipt
13041: 
13042: =item *
13043: 
13044: receipt() : API to ireceipt working off of env values; given out to users
13045: 
13046: =item *
13047: 
13048: countacc($url) : count the number of accesses to a given URL
13049: 
13050: =item *
13051: 
13052: 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
13053: 
13054: =item *
13055: 
13056: 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)
13057: 
13058: =item *
13059: 
13060: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13061: 
13062: =item *
13063: 
13064: devalidate($symb) : devalidate temporary spreadsheet calculations,
13065: forcing spreadsheet to reevaluate the resource scores next time.
13066: 
13067: =item * 
13068: 
13069: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13070: when viewing in course context.
13071: 
13072:  input: six args -- filename (decluttered), course number, course domain,
13073:                     url, symb (if registered) and group (if this is a 
13074:                     group item -- e.g., bulletin board, group page etc.).
13075: 
13076:  output: array of five scalars --
13077:          $cfile -- url for file editing if editable on current server
13078:          $home -- homeserver of resource (i.e., for author if published,
13079:                                           or course if uploaded.).
13080:          $switchserver --  1 if server switch will be needed.
13081:          $forceedit -- 1 if icon/link should be to go to edit mode 
13082:          $forceview -- 1 if icon/link should be to go to view mode
13083: 
13084: =item *
13085: 
13086: is_course_upload($file,$cnum,$cdom)
13087: 
13088: Used in course context to determine if current file was uploaded to 
13089: the course (i.e., would be found in /userfiles/docs on the course's 
13090: homeserver.
13091: 
13092:   input: 3 args -- filename (decluttered), course number and course domain.
13093:   output: boolean -- 1 if file was uploaded.
13094: 
13095: =back
13096: 
13097: =head2 Storing/Retreiving Data
13098: 
13099: =over 4
13100: 
13101: =item *
13102: 
13103: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13104: for this url; hashref needs to be given and should be a \%hashname; the
13105: remaining args aren't required and if they aren't passed or are '' they will
13106: be derived from the env
13107: 
13108: =item *
13109: 
13110: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13111: uses critical subroutine
13112: 
13113: =item *
13114: 
13115: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13116: all args are optional
13117: 
13118: =item *
13119: 
13120: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13121: dumps the complete (or key matching regexp) namespace into a hash
13122: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13123: normally &store()ed into
13124: 
13125: $range should be either an integer '100' (give me the first 100
13126:                                            matching records)
13127:               or be  two integers sperated by a - with no spaces
13128:                  '30-50' (give me the 30th through the 50th matching
13129:                           records)
13130: 
13131: 
13132: =item *
13133: 
13134: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13135: replaces a &store() version of data with a replacement set of data
13136: for a particular resource in a namespace passed in the $storehash hash 
13137: reference
13138: 
13139: =item *
13140: 
13141: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13142: works very similar to store/cstore, but all data is stored in a
13143: temporary location and can be reset using tmpreset, $storehash should
13144: be a hash reference, returns nothing on success
13145: 
13146: =item *
13147: 
13148: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13149: similar to restore, but all data is stored in a temporary location and
13150: can be reset using tmpreset. Returns a hash of values on success,
13151: error string otherwise.
13152: 
13153: =item *
13154: 
13155: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13156: deltes all keys for $symb form the temporary storage hash.
13157: 
13158: =item *
13159: 
13160: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13161: reference filled in from namesp ($udom and $uname are optional)
13162: 
13163: =item *
13164: 
13165: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13166: namesp ($udom and $uname are optional)
13167: 
13168: =item *
13169: 
13170: dump($namespace,$udom,$uname,$regexp,$range) : 
13171: dumps the complete (or key matching regexp) namespace into a hash
13172: ($udom, $uname, $regexp, $range are optional)
13173: 
13174: $range should be either an integer '100' (give me the first 100
13175:                                            matching records)
13176:               or be  two integers sperated by a - with no spaces
13177:                  '30-50' (give me the 30th through the 50th matching
13178:                           records)
13179: =item *
13180: 
13181: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13182: $store can be a scalar, an array reference, or if the amount to be 
13183: incremented is > 1, a hash reference.
13184: 
13185: ($udom and $uname are optional)
13186: 
13187: =item *
13188: 
13189: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13190: ($udom and $uname are optional)
13191: 
13192: =item *
13193: 
13194: cput($namespace,$storehash,$udom,$uname) : critical put
13195: ($udom and $uname are optional)
13196: 
13197: =item *
13198: 
13199: newput($namespace,$storehash,$udom,$uname) :
13200: 
13201: Attempts to store the items in the $storehash, but only if they don't
13202: currently exist, if this succeeds you can be certain that you have 
13203: successfully created a new key value pair in the $namespace db.
13204: 
13205: 
13206: Args:
13207:  $namespace: name of database to store values to
13208:  $storehash: hashref to store to the db
13209:  $udom: (optional) domain of user containing the db
13210:  $uname: (optional) name of user caontaining the db
13211: 
13212: Returns:
13213:  'ok' -> succeeded in storing all keys of $storehash
13214:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13215:                         least <key> already existed in the db (other
13216:                         requested keys may also already exist)
13217:  'error: <msg>' -> unable to tie the DB or other error occurred
13218:  'con_lost' -> unable to contact request server
13219:  'refused' -> action was not allowed by remote machine
13220: 
13221: 
13222: =item *
13223: 
13224: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13225: reference filled in from namesp (encrypts the return communication)
13226: ($udom and $uname are optional)
13227: 
13228: =item *
13229: 
13230: log($udom,$name,$home,$message) : write to permanent log for user; use
13231: critical subroutine
13232: 
13233: =item *
13234: 
13235: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13236: array reference filled in from namespace found in domain level on either
13237: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13238: 
13239: =item *
13240: 
13241: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13242: domain level either on specified domain server ($uhome) or primary domain 
13243: server ($udom and $uhome are optional)
13244: 
13245: =item * 
13246: 
13247: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13248: for: authentication, language, quotas, timezone, date locale, and portal URL in
13249: the target domain.
13250: 
13251: May also include additional key => value pairs for the following groups:
13252: 
13253: =over
13254: 
13255: =item
13256: disk quotas (MB allocated by default to portfolios and authoring spaces).
13257: 
13258: =over
13259: 
13260: =item defaultquota, authorquota
13261: 
13262: =back
13263: 
13264: =item
13265: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13266: portfolio for users).
13267: 
13268: =over
13269: 
13270: =item
13271: aboutme, blog, webdav, portfolio
13272: 
13273: =back
13274: 
13275: =item
13276: requestcourses: ability to request courses, and how requests are processed.
13277: 
13278: =over
13279: 
13280: =item
13281: official, unofficial, community
13282: 
13283: =back
13284: 
13285: =item
13286: inststatus: types of institutional affiliation, and order in which they are displayed.
13287: 
13288: =over
13289: 
13290: =item
13291: inststatustypes, inststatusorder
13292: 
13293: =back
13294: 
13295: =item
13296: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13297: for course's uploaded content.
13298: 
13299: =over
13300: 
13301: =item
13302: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13303: 
13304: =back
13305: 
13306: =item
13307: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13308: on your servers.
13309: 
13310: =over
13311: 
13312: =item 
13313: remotesessions, hostedsessions
13314: 
13315: =back
13316: 
13317: =back
13318: 
13319: In cases where a domain coordinator has never used the "Set Domain Configuration"
13320: utility to create a configuration.db file on a domain's primary library server 
13321: only the following domain defaults: auth_def, auth_arg_def, lang_def
13322: -- corresponding values are authentication type (internal, krb4, krb5,
13323: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13324: will be available. Values are retrieved from cache (if current), unless the
13325: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13326: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13327: 
13328: Typical usage:
13329: 
13330: %domdefaults = &get_domain_defaults($target_domain);
13331: 
13332: =back
13333: 
13334: =head2 Network Status Functions
13335: 
13336: =over 4
13337: 
13338: =item *
13339: 
13340: dirlist() : return directory list based on URI (first arg).
13341: 
13342: Inputs: 1 required, 5 optional.
13343: 
13344: =over
13345: 
13346: =item 
13347: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13348: 
13349: =item
13350: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13351: 
13352: =item
13353: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13354: 
13355: =item
13356: $getpropath - boolean: 1 if prepend path using &propath(). 
13357: 
13358: =item
13359: $getuserdir - boolean: 1 if prepend path for "userfiles".
13360: 
13361: =item 
13362: $alternateRoot - path to prepend in place of path from $uri.
13363: 
13364: =back
13365: 
13366: Returns: Array of up to two items.
13367: 
13368: =over
13369: 
13370: a reference to an array of files/subdirectories
13371: 
13372: =over
13373: 
13374: Each element in the array of files/subdirectories is a & separated list of
13375: item name and the result of running stat on the item.  If dirlist was requested
13376: for a file instead of a directory, the item name will be ''. For a directory 
13377: listing, if the item is a metadata file, the element will end &N&M 
13378: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13379: default copyright set (1).  
13380: 
13381: =back
13382: 
13383: a scalar containing error condition (if encountered).
13384: 
13385: =over
13386: 
13387: =item 
13388: no_host (no homeserver identified for $username:$domain).
13389: 
13390: =item 
13391: no_such_host (server contacted for listing not identified as valid host).
13392: 
13393: =item 
13394: con_lost (connection to remote server failed).
13395: 
13396: =item 
13397: refused (invalid $username:$domain received on lond side).
13398: 
13399: =item 
13400: no_such_dir (directory at specified path on lond side does not exist). 
13401: 
13402: =item 
13403: empty (directory at specified path on lond side is empty).
13404: 
13405: =over
13406: 
13407: This is currently not encountered because the &ls3, &ls2, 
13408: &ls (_handler) routines on the lond side do not filter out
13409: . and .. from a directory listing. 
13410: 
13411: =back
13412: 
13413: =back
13414: 
13415: =back
13416: 
13417: =item *
13418: 
13419: spareserver() : find server with least workload from spare.tab
13420: 
13421: 
13422: =item *
13423: 
13424: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13425: if there is no corresponding loncapa host.
13426: 
13427: =back
13428: 
13429: 
13430: =head2 Apache Request
13431: 
13432: =over 4
13433: 
13434: =item *
13435: 
13436: ssi($url,%hash) : server side include, does a complete request cycle on url to
13437: localhost, posts hash
13438: 
13439: =back
13440: 
13441: =head2 Data to String to Data
13442: 
13443: =over 4
13444: 
13445: =item *
13446: 
13447: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13448: and '&' separators, supports elements that are arrayrefs and hashrefs
13449: 
13450: =item *
13451: 
13452: hashref2str($hashref) : convert a hashref into a string complete with
13453: escaping and '=' and '&' separators, supports elements that are
13454: arrayrefs and hashrefs
13455: 
13456: =item *
13457: 
13458: arrayref2str($arrayref) : convert an arrayref into a string complete
13459: with escaping and '&' separators, supports elements that are arrayrefs
13460: and hashrefs
13461: 
13462: =item *
13463: 
13464: str2hash($string) : convert string to hash using unescaping and
13465: splitting on '=' and '&', supports elements that are arrayrefs and
13466: hashrefs
13467: 
13468: =item *
13469: 
13470: str2array($string) : convert string to hash using unescaping and
13471: splitting on '&', supports elements that are arrayrefs and hashrefs
13472: 
13473: =back
13474: 
13475: =head2 Logging Routines
13476: 
13477: 
13478: These routines allow one to make log messages in the lonnet.log and
13479: lonnet.perm logfiles.
13480: 
13481: =over 4
13482: 
13483: =item *
13484: 
13485: logtouch() : make sure the logfile, lonnet.log, exists
13486: 
13487: =item *
13488: 
13489: logthis() : append message to the normal lonnet.log file, it gets
13490: preiodically rolled over and deleted.
13491: 
13492: =item *
13493: 
13494: logperm() : append a permanent message to lonnet.perm.log, this log
13495: file never gets deleted by any automated portion of the system, only
13496: messages of critical importance should go in here.
13497: 
13498: 
13499: =back
13500: 
13501: =head2 General File Helper Routines
13502: 
13503: =over 4
13504: 
13505: =item *
13506: 
13507: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13508: (a) files in /uploaded
13509:   (i) If a local copy of the file exists - 
13510:       compares modification date of local copy with last-modified date for 
13511:       definitive version stored on home server for course. If local copy is 
13512:       stale, requests a new version from the home server and stores it. 
13513:       If the original has been removed from the home server, then local copy 
13514:       is unlinked.
13515:   (ii) If local copy does not exist -
13516:       requests the file from the home server and stores it. 
13517:   
13518:   If $caller is 'uploadrep':  
13519:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13520:     for request for files originally uploaded via DOCS. 
13521:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13522:   
13523:   Otherwise:
13524:      This indicates a call from the content generation phase of the request.
13525:      -  returns the entire contents of the file or -1.
13526:      
13527: (b) files in /res
13528:    - returns the entire contents of a file or -1; 
13529:    it properly subscribes to and replicates the file if neccessary.
13530: 
13531: 
13532: =item *
13533: 
13534: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13535:                   reference
13536: 
13537: returns either a stat() list of data about the file or an empty list
13538: if the file doesn't exist or couldn't find out about it (connection
13539: problems or user unknown)
13540: 
13541: =item *
13542: 
13543: filelocation($dir,$file) : returns file system location of a file
13544: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13545: directory that relative $file lookups are to looked in ($dir of /a/dir
13546: and a file of ../bob will become /a/bob)
13547: 
13548: =item *
13549: 
13550: hreflocation($dir,$file) : returns file system location or a URL; same as
13551: filelocation except for hrefs
13552: 
13553: =item *
13554: 
13555: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13556: 
13557: =back
13558: 
13559: =head2 Usererfile file routines (/uploaded*)
13560: 
13561: =over 4
13562: 
13563: =item *
13564: 
13565: userfileupload(): main rotine for putting a file in a user or course's
13566:                   filespace, arguments are,
13567: 
13568:  formname - required - this is the name of the element in $env where the
13569:            filename, and the contents of the file to create/modifed exist
13570:            the filename is in $env{'form.'.$formname.'.filename'} and the
13571:            contents of the file is located in $env{'form.'.$formname}
13572:  context - if coursedoc, store the file in the course of the active role
13573:              of the current user; 
13574:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13575:            if 'canceloverwrite': delete file in tmp/overwrites directory
13576:  subdir - required - subdirectory to put the file in under ../userfiles/
13577:          if undefined, it will be placed in "unknown"
13578: 
13579:  (This routine calls clean_filename() to remove any dangerous
13580:  characters from the filename, and then calls finuserfileupload() to
13581:  complete the transaction)
13582: 
13583:  returns either the url of the uploaded file (/uploaded/....) if successful
13584:  and /adm/notfound.html if unsuccessful
13585: 
13586: =item *
13587: 
13588: clean_filename(): routine for cleaing a filename up for storage in
13589:                  userfile space, argument is:
13590: 
13591:  filename - proposed filename
13592: 
13593: returns: the new clean filename
13594: 
13595: =item *
13596: 
13597: finishuserfileupload(): routine that creates and sends the file to
13598: userspace, probably shouldn't be called directly
13599: 
13600:   docuname: username or courseid of destination for the file
13601:   docudom: domain of user/course of destination for the file
13602:   formname: same as for userfileupload()
13603:   fname: filename (including subdirectories) for the file
13604:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13605:   allfiles: reference to hash used to store objects found by parser
13606:   codebase: reference to hash used for codebases of java objects found by parser
13607:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13608:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13609:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13610:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13611:   context: if 'overwrite', will move the uploaded file from its temporary location to
13612:             userfiles to facilitate overwriting a previously uploaded file with same name.
13613:   mimetype: reference to scalar to accommodate mime type determined
13614:             from File::MMagic if $parser = parse.
13615: 
13616:  returns either the url of the uploaded file (/uploaded/....) if successful
13617:  and /adm/notfound.html if unsuccessful (or an error message if context 
13618:  was 'overwrite').
13619:  
13620: 
13621: =item *
13622: 
13623: renameuserfile(): renames an existing userfile to a new name
13624: 
13625:   Args:
13626:    docuname: username or courseid of destination for the file
13627:    docudom: domain of user/course of destination for the file
13628:    old: current file name (including any subdirs under userfiles)
13629:    new: desired file name (including any subdirs under userfiles)
13630: 
13631: =item *
13632: 
13633: mkdiruserfile(): creates a directory is a userfiles dir
13634: 
13635:   Args:
13636:    docuname: username or courseid of destination for the file
13637:    docudom: domain of user/course of destination for the file
13638:    dir: dir to create (including any subdirs under userfiles)
13639: 
13640: =item *
13641: 
13642: removeuserfile(): removes a file that exists in userfiles
13643: 
13644:   Args:
13645:    docuname: username or courseid of destination for the file
13646:    docudom: domain of user/course of destination for the file
13647:    fname: filname to delete (including any subdirs under userfiles)
13648: 
13649: =item *
13650: 
13651: removeuploadedurl(): convience function for removeuserfile()
13652: 
13653:   Args:
13654:    url:  a full /uploaded/... url to delete
13655: 
13656: =item * 
13657: 
13658: get_portfile_permissions():
13659:   Args:
13660:     domain: domain of user or course contain the portfolio files
13661:     user: name of user or num of course contain the portfolio files
13662:   Returns:
13663:     hashref of a dump of the proper file_permissions.db
13664:    
13665: 
13666: =item * 
13667: 
13668: get_access_controls():
13669: 
13670: Args:
13671:   current_permissions: the hash ref returned from get_portfile_permissions()
13672:   group: (optional) the group you want the files associated with
13673:   file: (optional) the file you want access info on
13674: 
13675: Returns:
13676:     a hash (keys are file names) of hashes containing
13677:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13678:         values are XML containing access control settings (see below) 
13679: 
13680: Internal notes:
13681: 
13682:  access controls are stored in file_permissions.db as key=value pairs.
13683:     key -> path to file/file_name\0uniqueID:scope_end_start
13684:         where scope -> public,guest,course,group,domains or users.
13685:               end -> UNIX time for end of access (0 -> no end date)
13686:               start -> UNIX time for start of access
13687: 
13688:     value -> XML description of access control
13689:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13690:             <start></start>
13691:             <end></end>
13692: 
13693:             <password></password>  for scope type = guest
13694: 
13695:             <domain></domain>     for scope type = course or group
13696:             <number></number>
13697:             <roles id="">
13698:              <role></role>
13699:              <access></access>
13700:              <section></section>
13701:              <group></group>
13702:             </roles>
13703: 
13704:             <dom></dom>         for scope type = domains
13705: 
13706:             <users>             for scope type = users
13707:              <user>
13708:               <uname></uname>
13709:               <udom></udom>
13710:              </user>
13711:             </users>
13712:            </scope> 
13713:               
13714:  Access data is also aggregated for each file in an additional key=value pair:
13715:  key -> path to file/file_name\0accesscontrol 
13716:  value -> reference to hash
13717:           hash contains key = value pairs
13718:           where key = uniqueID:scope_end_start
13719:                 value = UNIX time record was last updated
13720: 
13721:           Used to improve speed of look-ups of access controls for each file.  
13722:  
13723:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13724: 
13725: =item *
13726: 
13727: modify_access_controls():
13728: 
13729: Modifies access controls for a portfolio file
13730: Args
13731: 1. file name
13732: 2. reference to hash of required changes,
13733: 3. domain
13734: 4. username
13735:   where domain,username are the domain of the portfolio owner 
13736:   (either a user or a course) 
13737: 
13738: Returns:
13739: 1. result of additions or updates ('ok' or 'error', with error message). 
13740: 2. result of deletions ('ok' or 'error', with error message).
13741: 3. reference to hash of any new or updated access controls.
13742: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13743:    key = integer (inbound ID)
13744:    value = uniqueID
13745: 
13746: =item *
13747: 
13748: get_timebased_id():
13749: 
13750: Attempts to get a unique timestamp-based suffix for use with items added to a 
13751: course via the Course Editor (e.g., folders, composite pages, 
13752: group bulletin boards).
13753: 
13754: Args: (first three required; six others optional)
13755: 
13756: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13757:    docssequence, or name of group
13758: 
13759: 2. keyid (alphanumeric): name of temporary locking key in hash,
13760:    e.g., num, boardids
13761: 
13762: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13763:    file will be named nohist_namespace.db
13764: 
13765: 4. cdom: domain of course; default is current course domain from %env
13766: 
13767: 5. cnum: course number; default is current course number from %env
13768: 
13769: 6. idtype: set to concat if an additional digit is to be appended to the 
13770:    unix timestamp to form the suffix, if the plain timestamp is already
13771:    in use.  Default is to not do this, but simply increment the unix 
13772:    timestamp by 1 until a unique key is obtained.
13773: 
13774: 7. who: holder of locking key; defaults to user:domain for user.
13775: 
13776: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13777:    retrying); default is 3.
13778: 
13779: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13780: 
13781: Returns:
13782: 
13783: 1. suffix obtained (numeric)
13784: 
13785: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13786: 
13787: 3. error: contains (localized) error message if an error occurred.
13788: 
13789: 
13790: =back
13791: 
13792: =head2 HTTP Helper Routines
13793: 
13794: =over 4
13795: 
13796: =item *
13797: 
13798: escape() : unpack non-word characters into CGI-compatible hex codes
13799: 
13800: =item *
13801: 
13802: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13803: 
13804: =back
13805: 
13806: =head1 PRIVATE SUBROUTINES
13807: 
13808: =head2 Underlying communication routines (Shouldn't call)
13809: 
13810: =over 4
13811: 
13812: =item *
13813: 
13814: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13815: 
13816: =item *
13817: 
13818: reply() : uses subreply to send a message to remote machine, logs all failures
13819: 
13820: =item *
13821: 
13822: critical() : passes a critical message to another server; if cannot
13823: get through then place message in connection buffer directory and
13824: returns con_delayed, if incapable of saving message, returns
13825: con_failed
13826: 
13827: =item *
13828: 
13829: reconlonc() : tries to reconnect lonc client processes.
13830: 
13831: =back
13832: 
13833: =head2 Resource Access Logging
13834: 
13835: =over 4
13836: 
13837: =item *
13838: 
13839: flushcourselogs() : flush (save) buffer logs and access logs
13840: 
13841: =item *
13842: 
13843: courselog($what) : save message for course in hash
13844: 
13845: =item *
13846: 
13847: courseacclog($what) : save message for course using &courselog().  Perform
13848: special processing for specific resource types (problems, exams, quizzes, etc).
13849: 
13850: =item *
13851: 
13852: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13853: as a PerlChildExitHandler
13854: 
13855: =back
13856: 
13857: =head2 Other
13858: 
13859: =over 4
13860: 
13861: =item *
13862: 
13863: symblist($mapname,%newhash) : update symbolic storage links
13864: 
13865: =back
13866: 
13867: =cut
13868: 

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