File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1230: download - view: text, annotated - select for diffs
Tue Jul 9 00:17:27 2013 UTC (10 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Disk quotas for content uploaded directly to a course (userfiles/docs/ and
   userfiles/supplemental).
  - Default is 500 MB, unless set at domain level, or individual course level.
  - Domain defaults set by DC  for: official courses, unofficial courses and
    communities set via "Course/Community defaults" in "Set domain configuration".
  - Quota for individual courses/communities set  by DC via:
      "View or modify a course or community"
  - &excess_filesize_authorspace() renamed as excess_filesize_warning() to
    support quota checking in course context, as well as in author context.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1230 2013/07/09 00:17:27 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     if (($r->user() eq '') && ($apache >= 2.4)) {
  638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  639:             $r->user($disk_env{'user.name'});
  640:         } else {
  641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  642:         }
  643:     }
  644:     return $handle;
  645: }
  646: 
  647: sub timed_flock {
  648:     my ($file,$lock_type) = @_;
  649:     my $failed=0;
  650:     eval {
  651: 	local $SIG{__DIE__}='DEFAULT';
  652: 	local $SIG{ALRM}=sub {
  653: 	    $failed=1;
  654: 	    die("failed lock");
  655: 	};
  656: 	alarm(13);
  657: 	flock($file,$lock_type);
  658: 	alarm(0);
  659:     };
  660:     if ($failed) {
  661: 	return undef;
  662:     } else {
  663: 	return 1;
  664:     }
  665: }
  666: 
  667: # ---------------------------------------------------------- Append Environment
  668: 
  669: sub appenv {
  670:     my ($newenv,$roles) = @_;
  671:     if (ref($newenv) eq 'HASH') {
  672:         foreach my $key (keys(%{$newenv})) {
  673:             my $refused = 0;
  674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  675:                 $refused = 1;
  676:                 if (ref($roles) eq 'ARRAY') {
  677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  679:                         $refused = 0;
  680:                     }
  681:                 }
  682:             }
  683:             if ($refused) {
  684:                 &logthis("<font color=\"blue\">WARNING: ".
  685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  686:                          .'</font>');
  687: 	        delete($newenv->{$key});
  688:             } else {
  689:                 $env{$key}=$newenv->{$key};
  690:             }
  691:         }
  692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  693:         if ($opened
  694: 	    && &timed_flock($env_file,LOCK_EX)
  695: 	    &&
  696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  698: 	    while (my ($key,$value) = each(%{$newenv})) {
  699: 	        $disk_env{$key} = $value;
  700: 	    }
  701: 	    untie(%disk_env);
  702:         }
  703:     }
  704:     return 'ok';
  705: }
  706: # ----------------------------------------------------- Delete from Environment
  707: 
  708: sub delenv {
  709:     my ($delthis,$regexp,$roles) = @_;
  710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  711:         my $refused = 1;
  712:         if (ref($roles) eq 'ARRAY') {
  713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  714:             if (grep(/^\Q$role\E$/,@{$roles})) {
  715:                 $refused = 0;
  716:             }
  717:         }
  718:         if ($refused) {
  719:             &logthis("<font color=\"blue\">WARNING: ".
  720:                      "Attempt to delete from environment ".$delthis);
  721:             return 'error';
  722:         }
  723:     }
  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  725:     if ($opened
  726: 	&& &timed_flock($env_file,LOCK_EX)
  727: 	&&
  728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  730: 	foreach my $key (keys(%disk_env)) {
  731: 	    if ($regexp) {
  732:                 if ($key=~/^$delthis/) {
  733:                     delete($env{$key});
  734:                     delete($disk_env{$key});
  735:                 } 
  736:             } else {
  737:                 if ($key=~/^\Q$delthis\E/) {
  738: 		    delete($env{$key});
  739: 		    delete($disk_env{$key});
  740: 	        }
  741:             }
  742: 	}
  743: 	untie(%disk_env);
  744:     }
  745:     return 'ok';
  746: }
  747: 
  748: sub get_env_multiple {
  749:     my ($name) = @_;
  750:     my @values;
  751:     if (defined($env{$name})) {
  752:         # exists is it an array
  753:         if (ref($env{$name})) {
  754:             @values=@{ $env{$name} };
  755:         } else {
  756:             $values[0]=$env{$name};
  757:         }
  758:     }
  759:     return(@values);
  760: }
  761: 
  762: # ------------------------------------------------------------------- Locking
  763: 
  764: sub set_lock {
  765:     my ($text)=@_;
  766:     $locknum++;
  767:     my $id=$$.'-'.$locknum;
  768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  769:              'session.lock.'.$id => $text});
  770:     return $id;
  771: }
  772: 
  773: sub get_locks {
  774:     my $num=0;
  775:     my %texts=();
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           $num++;
  779:           $texts{$lock}=$env{'session.lock.'.$lock};
  780:        }
  781:    }
  782:    return ($num,%texts);
  783: }
  784: 
  785: sub remove_lock {
  786:     my ($id)=@_;
  787:     my $newlocks='';
  788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  789:        if (($lock=~/\w/) && ($lock ne $id)) {
  790:           $newlocks.=','.$lock;
  791:        }
  792:     }
  793:     &appenv({'session.locks' => $newlocks});
  794:     &delenv('session.lock.'.$id);
  795: }
  796: 
  797: sub remove_all_locks {
  798:     my $activelocks=$env{'session.locks'};
  799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  800:        if ($lock=~/\w/) {
  801:           &remove_lock($lock);
  802:        }
  803:     }
  804: }
  805: 
  806: 
  807: # ------------------------------------------ Find out current server userload
  808: sub userload {
  809:     my $numusers=0;
  810:     {
  811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  812: 	my $filename;
  813: 	my $curtime=time;
  814: 	while ($filename=readdir(LONIDS)) {
  815: 	    next if ($filename eq '.' || $filename eq '..');
  816: 	    next if ($filename =~ /publicuser_\d+\.id/);
  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  819: 	}
  820: 	closedir(LONIDS);
  821:     }
  822:     my $userloadpercent=0;
  823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  824:     if ($maxuserload) {
  825: 	$userloadpercent=100*$numusers/$maxuserload;
  826:     }
  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  828:     return $userloadpercent;
  829: }
  830: 
  831: # ------------------------------ Find server with least workload from spare.tab
  832: 
  833: sub spareserver {
  834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  835:     my $spare_server;
  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  838:                                                      :  $userloadpercent;
  839:     my ($uint_dom,$remotesessions);
  840:     if (($udom ne '') && (&domain($udom) ne '')) {
  841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  844:         $remotesessions = $udomdefaults{'remotesessions'};
  845:     }
  846:     my $spareshash = &this_host_spares($udom);
  847:     if (ref($spareshash) eq 'HASH') {
  848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  850:                 if ($uint_dom) {
  851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  852:                                                  $try_server));
  853:                 }
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     if ($uint_dom) {
  865:                         next unless (&spare_can_host($udom,$uint_dom,
  866:                                                      $remotesessions,$try_server));
  867:                     }
  868: 	            ($spare_server, $lowest_load) =
  869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  870:                 }
  871: 	    }
  872:         }
  873:     }
  874: 
  875:     if (!$want_server_name) {
  876:         my $protocol = 'http';
  877:         if ($protocol{$spare_server} eq 'https') {
  878:             $protocol = $protocol{$spare_server};
  879:         }
  880:         if (defined($spare_server)) {
  881:             my $hostname = &hostname($spare_server);
  882:             if (defined($hostname)) {
  883: 	        $spare_server = $protocol.'://'.$hostname;
  884:             }
  885:         }
  886:     }
  887:     return $spare_server;
  888: }
  889: 
  890: sub compare_server_load {
  891:     my ($try_server, $spare_server, $lowest_load) = @_;
  892: 
  893:     my $loadans     = &reply('load',    $try_server);
  894:     my $userloadans = &reply('userload',$try_server);
  895: 
  896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  898:     }
  899: 
  900:     my $load;
  901:     if ($loadans =~ /\d/) {
  902: 	if ($userloadans =~ /\d/) {
  903: 	    #both are numbers, pick the bigger one
  904: 	    $load = ($loadans > $userloadans) ? $loadans 
  905: 		                              : $userloadans;
  906: 	} else {
  907: 	    $load = $loadans;
  908: 	}
  909:     } else {
  910: 	$load = $userloadans;
  911:     }
  912: 
  913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  914: 	$spare_server = $try_server;
  915: 	$lowest_load  = $load;
  916:     }
  917:     return ($spare_server,$lowest_load);
  918: }
  919: 
  920: # --------------------------- ask offload servers if user already has a session
  921: sub find_existing_session {
  922:     my ($udom,$uname) = @_;
  923:     my $spareshash = &this_host_spares($udom);
  924:     if (ref($spareshash) eq 'HASH') {
  925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  928:             }
  929:         }
  930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  933:             }
  934:         }
  935:     }
  936:     return;
  937: }
  938: 
  939: # -------------------------------- ask if server already has a session for user
  940: sub has_user_session {
  941:     my ($lonid,$udom,$uname) = @_;
  942:     my $result = &reply(join(':','userhassession',
  943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  944:     return 1 if ($result eq 'ok');
  945: 
  946:     return 0;
  947: }
  948: 
  949: # --------- determine least loaded server in a user's domain which allows login
  950: 
  951: sub choose_server {
  952:     my ($udom,$checkloginvia) = @_;
  953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  954:     my %servers = &get_servers($udom);
  955:     my $lowest_load = 30000;
  956:     my ($login_host,$hostname,$portal_path,$isredirect);
  957:     foreach my $lonhost (keys(%servers)) {
  958:         my $loginvia;
  959:         if ($checkloginvia) {
  960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  961:             if ($loginvia) {
  962:                 my ($server,$path) = split(/:/,$loginvia);
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($server, $login_host, $lowest_load);
  965:                 if ($login_host eq $server) {
  966:                     $portal_path = $path;
  967:                     $isredirect = 1;
  968:                 }
  969:             } else {
  970:                 ($login_host, $lowest_load) =
  971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  972:                 if ($login_host eq $lonhost) {
  973:                     $portal_path = '';
  974:                     $isredirect = ''; 
  975:                 }
  976:             }
  977:         } else {
  978:             ($login_host, $lowest_load) =
  979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  980:         }
  981:     }
  982:     if ($login_host ne '') {
  983:         $hostname = &hostname($login_host);
  984:     }
  985:     return ($login_host,$hostname,$portal_path,$isredirect);
  986: }
  987: 
  988: # --------------------------------------------- Try to change a user's password
  989: 
  990: sub changepass {
  991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  992:     $currentpass = &escape($currentpass);
  993:     $newpass     = &escape($newpass);
  994:     my $lonhost = $perlvar{'lonHostID'};
  995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  996: 		       $server);
  997:     if (! $answer) {
  998: 	&logthis("No reply on password change request to $server ".
  999: 		 "by $uname in domain $udom.");
 1000:     } elsif ($answer =~ "^ok") {
 1001:         &logthis("$uname in $udom successfully changed their password ".
 1002: 		 "on $server.");
 1003:     } elsif ($answer =~ "^pwchange_failure") {
 1004: 	&logthis("$uname in $udom was unable to change their password ".
 1005: 		 "on $server.  The action was blocked by either lcpasswd ".
 1006: 		 "or pwchange");
 1007:     } elsif ($answer =~ "^non_authorized") {
 1008:         &logthis("$uname in $udom did not get their password correct when ".
 1009: 		 "attempting to change it on $server.");
 1010:     } elsif ($answer =~ "^auth_mode_error") {
 1011:         &logthis("$uname in $udom attempted to change their password despite ".
 1012: 		 "not being locally or internally authenticated on $server.");
 1013:     } elsif ($answer =~ "^unknown_user") {
 1014:         &logthis("$uname in $udom attempted to change their password ".
 1015: 		 "on $server but were unable to because $server is not ".
 1016: 		 "their home server.");
 1017:     } elsif ($answer =~ "^refused") {
 1018: 	&logthis("$server refused to change $uname in $udom password because ".
 1019: 		 "it was sent an unencrypted request to change the password.");
 1020:     } elsif ($answer =~ "invalid_client") {
 1021:         &logthis("$server refused to change $uname in $udom password because ".
 1022:                  "it was a reset by e-mail originating from an invalid server.");
 1023:     }
 1024:     return $answer;
 1025: }
 1026: 
 1027: # ----------------------- Try to determine user's current authentication scheme
 1028: 
 1029: sub queryauthenticate {
 1030:     my ($uname,$udom)=@_;
 1031:     my $uhome=&homeserver($uname,$udom);
 1032:     if (!$uhome) {
 1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1034: 	return 'no_host';
 1035:     }
 1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1039:     }
 1040:     return $answer;
 1041: }
 1042: 
 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
 1044: 
 1045: sub authenticate {
 1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1047:     $upass=&escape($upass);
 1048:     $uname= &LONCAPA::clean_username($uname);
 1049:     my $uhome=&homeserver($uname,$udom,1);
 1050:     my $newhome;
 1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: # Maybe the machine was offline and only re-appeared again recently?
 1053:         &reconlonc();
 1054: # One more
 1055: 	$uhome=&homeserver($uname,$udom,1);
 1056:         if (($uhome eq 'no_host') && $checkdefauth) {
 1057:             if (defined(&domain($udom,'primary'))) {
 1058:                 $newhome=&domain($udom,'primary');
 1059:             }
 1060:             if ($newhome ne '') {
 1061:                 $uhome = $newhome;
 1062:             }
 1063:         }
 1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1066: 	    return 'no_host';
 1067:         }
 1068:     }
 1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1070:     if ($answer eq 'authorized') {
 1071:         if ($newhome) {
 1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1073:             return 'no_account_on_host'; 
 1074:         } else {
 1075:             &logthis("User $uname at $udom authorized by $uhome");
 1076:             return $uhome;
 1077:         }
 1078:     }
 1079:     if ($answer eq 'non_authorized') {
 1080: 	&logthis("User $uname at $udom rejected by $uhome");
 1081: 	return 'no_host'; 
 1082:     }
 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1084:     return 'no_host';
 1085: }
 1086: 
 1087: sub can_host_session {
 1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1089:     my $canhost = 1;
 1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1091:     if (ref($remotesessions) eq 'HASH') {
 1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1094:                 $canhost = 0;
 1095:             } else {
 1096:                 $canhost = 1;
 1097:             }
 1098:         }
 1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1101:                 $canhost = 1;
 1102:             } else {
 1103:                 $canhost = 0;
 1104:             }
 1105:         }
 1106:         if ($canhost) {
 1107:             if ($remotesessions->{'version'} ne '') {
 1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1109:                 if ($reqmajor ne '' && $reqminor ne '') {
 1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1111:                         my $major = $1;
 1112:                         my $minor = $2;
 1113:                         if (($major < $reqmajor ) ||
 1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1115:                             $canhost = 0;
 1116:                         }
 1117:                     } else {
 1118:                         $canhost = 0;
 1119:                     }
 1120:                 }
 1121:             }
 1122:         }
 1123:     }
 1124:     if ($canhost) {
 1125:         if (ref($hostedsessions) eq 'HASH') {
 1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1129:                 if (($uint_dom ne '') && 
 1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1131:                     $canhost = 0;
 1132:                 } else {
 1133:                     $canhost = 1;
 1134:                 }
 1135:             }
 1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1137:                 if (($uint_dom ne '') && 
 1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1139:                     $canhost = 1;
 1140:                 } else {
 1141:                     $canhost = 0;
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     return $canhost;
 1147: }
 1148: 
 1149: sub spare_can_host {
 1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1151:     my $canhost=1;
 1152:     my @intdoms;
 1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1154:     if (ref($internet_names) eq 'ARRAY') {
 1155:         @intdoms = @{$internet_names};
 1156:     }
 1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1163:                                      $remotesessions,
 1164:                                      $defdomdefaults{'hostedsessions'});
 1165:     }
 1166:     return $canhost;
 1167: }
 1168: 
 1169: sub this_host_spares {
 1170:     my ($dom) = @_;
 1171:     my ($dom_in_use,$lonhost_in_use,$result);
 1172:     my @hosts = &current_machine_ids();
 1173:     foreach my $lonhost (@hosts) {
 1174:         if (&host_domain($lonhost) eq $dom) {
 1175:             $dom_in_use = $dom;
 1176:             $lonhost_in_use = $lonhost;
 1177:             last;
 1178:         }
 1179:     }
 1180:     if ($dom_in_use ne '') {
 1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1182:     }
 1183:     if (ref($result) ne 'HASH') {
 1184:         $lonhost_in_use = $perlvar{'lonHostID'};
 1185:         $dom_in_use = &host_domain($lonhost_in_use);
 1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1187:         if (ref($result) ne 'HASH') {
 1188:             $result = \%spareid;
 1189:         }
 1190:     }
 1191:     return $result;
 1192: }
 1193: 
 1194: sub spares_for_offload  {
 1195:     my ($dom_in_use,$lonhost_in_use) = @_;
 1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1197:     if (defined($cached)) {
 1198:         return $result;
 1199:     } else {
 1200:         my $cachetime = 60*60*24;
 1201:         my %domconfig =
 1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return;
 1212: }
 1213: 
 1214: sub get_lonbalancer_config {
 1215:     my ($servers) = @_;
 1216:     my ($currbalancer,$currtargets);
 1217:     if (ref($servers) eq 'HASH') {
 1218:         foreach my $server (keys(%{$servers})) {
 1219:             my %what = (
 1220:                          spareid => 1,
 1221:                          perlvar => 1,
 1222:                        );
 1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1224:             if ($result eq 'ok') {
 1225:                 if (ref($returnhash) eq 'HASH') {
 1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1228:                             $currbalancer = $server;
 1229:                             $currtargets = {};
 1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1233:                                 }
 1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1236:                                 }
 1237:                             }
 1238:                             last;
 1239:                         }
 1240:                     }
 1241:                 }
 1242:             }
 1243:         }
 1244:     }
 1245:     return ($currbalancer,$currtargets);
 1246: }
 1247: 
 1248: sub check_loadbalancing {
 1249:     my ($uname,$udom) = @_;
 1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1251:         $rule_in_effect,$offloadto,$otherserver);
 1252:     my $lonhost = $perlvar{'lonHostID'};
 1253:     my @hosts = &current_machine_ids();
 1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1257:     my $serverhomedom = &host_domain($lonhost);
 1258: 
 1259:     my $cachetime = 60*60*24;
 1260: 
 1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1262:         $dom_in_use = $udom;
 1263:         $homeintdom = 1;
 1264:     } else {
 1265:         $dom_in_use = $serverhomedom;
 1266:     }
 1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1268:     unless (defined($cached)) {
 1269:         my %domconfig =
 1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1273:         }
 1274:     }
 1275:     if (ref($result) eq 'HASH') {
 1276:         ($is_balancer,$currtargets,$currrules) = 
 1277:             &check_balancer_result($result,@hosts);
 1278:         if ($is_balancer) {
 1279:             if (ref($currrules) eq 'HASH') {
 1280:                 if ($homeintdom) {
 1281:                     if ($uname ne '') {
 1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1288:                             }
 1289:                         }
 1290:                         if ($rule_in_effect eq '') {
 1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1292:                             if ($userenv{'inststatus'} ne '') {
 1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1294:                                 my ($othertitle,$usertypes,$types) =
 1295:                                     &Apache::loncommon::sorted_inst_types($udom);
 1296:                                 if (ref($types) eq 'ARRAY') {
 1297:                                     foreach my $type (@{$types}) {
 1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1299:                                             if (exists($currrules->{$type})) {
 1300:                                                 $rule_in_effect = $currrules->{$type};
 1301:                                             }
 1302:                                         }
 1303:                                     }
 1304:                                 }
 1305:                             } else {
 1306:                                 if (exists($currrules->{'default'})) {
 1307:                                     $rule_in_effect = $currrules->{'default'};
 1308:                                 }
 1309:                             }
 1310:                         }
 1311:                     } else {
 1312:                         if (exists($currrules->{'default'})) {
 1313:                             $rule_in_effect = $currrules->{'default'};
 1314:                         }
 1315:                     }
 1316:                 } else {
 1317:                     if ($currrules->{'_LC_external'} ne '') {
 1318:                         $rule_in_effect = $currrules->{'_LC_external'};
 1319:                     }
 1320:                 }
 1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1322:                                                        $uname,$udom);
 1323:             }
 1324:         }
 1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1326:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1327:         unless (defined($cached)) {
 1328:             my %domconfig =
 1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1332:             }
 1333:         }
 1334:         if (ref($result) eq 'HASH') {
 1335:             ($is_balancer,$currtargets,$currrules) = 
 1336:                 &check_balancer_result($result,@hosts);
 1337:             if ($is_balancer) {
 1338:                 if (ref($currrules) eq 'HASH') {
 1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1341:                     }
 1342:                 }
 1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1344:                                                        $uname,$udom);
 1345:             }
 1346:         } else {
 1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1348:                 $is_balancer = 1;
 1349:                 $offloadto = &this_host_spares($dom_in_use);
 1350:             }
 1351:         }
 1352:     } else {
 1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1354:             $is_balancer = 1;
 1355:             $offloadto = &this_host_spares($dom_in_use);
 1356:         }
 1357:     }
 1358:     if ($is_balancer) {
 1359:         my $lowest_load = 30000;
 1360:         if (ref($offloadto) eq 'HASH') {
 1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1363:                     ($otherserver,$lowest_load) =
 1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1365:                 }
 1366:             }
 1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1368: 
 1369:             if (!$found_server) {
 1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1372:                         ($otherserver,$lowest_load) =
 1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1374:                     }
 1375:                 }
 1376:             }
 1377:         } elsif (ref($offloadto) eq 'ARRAY') {
 1378:             if (@{$offloadto} == 1) {
 1379:                 $otherserver = $offloadto->[0];
 1380:             } elsif (@{$offloadto} > 1) {
 1381:                 foreach my $try_server (@{$offloadto}) {
 1382:                     ($otherserver,$lowest_load) =
 1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1384:                 }
 1385:             }
 1386:         }
 1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1388:             $is_balancer = 0;
 1389:             if ($uname ne '' && $udom ne '') {
 1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1391:                     
 1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1393:                              'user.loadbalcheck.time' => time});
 1394:                 }
 1395:             }
 1396:         }
 1397:     }
 1398:     return ($is_balancer,$otherserver);
 1399: }
 1400: 
 1401: sub check_balancer_result {
 1402:     my ($result,@hosts) = @_;
 1403:     my ($is_balancer,$currtargets,$currrules);
 1404:     if (ref($result) eq 'HASH') {
 1405:         if ($result->{'lonhost'} ne '') {
 1406:             my $currbalancer = $result->{'lonhost'};
 1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1408:                 $is_balancer = 1;
 1409:                 $currtargets = $result->{'targets'};
 1410:                 $currrules = $result->{'rules'};
 1411:             }
 1412:         } else {
 1413:             foreach my $key (keys(%{$result})) {
 1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1415:                     (ref($result->{$key}) eq 'HASH')) {
 1416:                     $is_balancer = 1;
 1417:                     $currrules = $result->{$key}{'rules'};
 1418:                     $currtargets = $result->{$key}{'targets'};
 1419:                     last;
 1420:                 }
 1421:             }
 1422:         }
 1423:     }
 1424:     return ($is_balancer,$currtargets,$currrules);
 1425: }
 1426: 
 1427: sub get_loadbalancer_targets {
 1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1429:     my $offloadto;
 1430:     if ($rule_in_effect eq 'none') {
 1431:         return [$perlvar{'lonHostID'}];
 1432:     } elsif ($rule_in_effect eq '') {
 1433:         $offloadto = $currtargets;
 1434:     } else {
 1435:         if ($rule_in_effect eq 'homeserver') {
 1436:             my $homeserver = &homeserver($uname,$udom);
 1437:             if ($homeserver ne 'no_host') {
 1438:                 $offloadto = [$homeserver];
 1439:             }
 1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1441:             my %domconfig =
 1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1447:                     }
 1448:                 }
 1449:             } else {
 1450:                 my %servers = &internet_dom_servers($udom);
 1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1452:                 if (&hostname($remotebalancer) ne '') {
 1453:                     $offloadto = [$remotebalancer];
 1454:                 }
 1455:             }
 1456:         } elsif (&hostname($rule_in_effect) ne '') {
 1457:             $offloadto = [$rule_in_effect];
 1458:         }
 1459:     }
 1460:     return $offloadto;
 1461: }
 1462: 
 1463: sub internet_dom_servers {
 1464:     my ($dom) = @_;
 1465:     my (%uniqservers,%servers);
 1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1467:     my @machinedoms = &machine_domains($primaryserver);
 1468:     foreach my $mdom (@machinedoms) {
 1469:         my %currservers = %servers;
 1470:         my %server = &get_servers($mdom);
 1471:         %servers = (%currservers,%server);
 1472:     }
 1473:     my %by_hostname;
 1474:     foreach my $id (keys(%servers)) {
 1475:         push(@{$by_hostname{$servers{$id}}},$id);
 1476:     }
 1477:     foreach my $hostname (sort(keys(%by_hostname))) {
 1478:         if (@{$by_hostname{$hostname}} > 1) {
 1479:             my $match = 0;
 1480:             foreach my $id (@{$by_hostname{$hostname}}) {
 1481:                 if (&host_domain($id) eq $dom) {
 1482:                     $uniqservers{$id} = $hostname;
 1483:                     $match = 1;
 1484:                 }
 1485:             }
 1486:             unless ($match) {
 1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1488:             }
 1489:         } else {
 1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:         }
 1492:     }
 1493:     return %uniqservers;
 1494: }
 1495: 
 1496: # ---------------------- Find the homebase for a user from domain's lib servers
 1497: 
 1498: my %homecache;
 1499: sub homeserver {
 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
 1501:     my $index="$uname:$udom";
 1502: 
 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1504: 
 1505:     my %servers = &get_servers($udom,'library');
 1506:     foreach my $tryserver (keys(%servers)) {
 1507:         next if ($ignoreBadCache ne 'true' && 
 1508: 		 exists($badServerCache{$tryserver}));
 1509: 
 1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1511: 	if ($answer eq 'found') {
 1512: 	    delete($badServerCache{$tryserver}); 
 1513: 	    return $homecache{$index}=$tryserver;
 1514: 	} elsif ($answer eq 'no_host') {
 1515: 	    $badServerCache{$tryserver}=1;
 1516: 	}
 1517:     }    
 1518:     return 'no_host';
 1519: }
 1520: 
 1521: # ------------------------------------- Find the usernames behind a list of IDs
 1522: 
 1523: sub idget {
 1524:     my ($udom,@ids)=@_;
 1525:     my %returnhash=();
 1526:     
 1527:     my %servers = &get_servers($udom,'library');
 1528:     foreach my $tryserver (keys(%servers)) {
 1529: 	my $idlist=join('&',@ids);
 1530: 	$idlist=~tr/A-Z/a-z/; 
 1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1532: 	my @answer=();
 1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1534: 	    @answer=split(/\&/,$reply);
 1535: 	}                    ;
 1536: 	my $i;
 1537: 	for ($i=0;$i<=$#ids;$i++) {
 1538: 	    if ($answer[$i]) {
 1539: 		$returnhash{$ids[$i]}=$answer[$i];
 1540: 	    } 
 1541: 	}
 1542:     } 
 1543:     return %returnhash;
 1544: }
 1545: 
 1546: # ------------------------------------- Find the IDs behind a list of usernames
 1547: 
 1548: sub idrget {
 1549:     my ($udom,@unames)=@_;
 1550:     my %returnhash=();
 1551:     foreach my $uname (@unames) {
 1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1553:     }
 1554:     return %returnhash;
 1555: }
 1556: 
 1557: # ------------------------------- Store away a list of names and associated IDs
 1558: 
 1559: sub idput {
 1560:     my ($udom,%ids)=@_;
 1561:     my %servers=();
 1562:     foreach my $uname (keys(%ids)) {
 1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1564:         my $uhom=&homeserver($uname,$udom);
 1565:         if ($uhom ne 'no_host') {
 1566:             my $id=&escape($ids{$uname});
 1567:             $id=~tr/A-Z/a-z/;
 1568:             my $esc_unam=&escape($uname);
 1569: 	    if ($servers{$uhom}) {
 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1571:             } else {
 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
 1573:             }
 1574:         }
 1575:     }
 1576:     foreach my $server (keys(%servers)) {
 1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1578:     }
 1579: }
 1580: 
 1581: # ------------------------------dump from db file owned by domainconfig user
 1582: sub dump_dom {
 1583:     my ($namespace, $udom, $regexp) = @_;
 1584: 
 1585:     $udom ||= $env{'user.domain'};
 1586: 
 1587:     return () unless $udom;
 1588: 
 1589:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1590: }
 1591: 
 1592: # ------------------------------------------ get items from domain db files   
 1593: 
 1594: sub get_dom {
 1595:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1596:     my $items='';
 1597:     foreach my $item (@$storearr) {
 1598:         $items.=&escape($item).'&';
 1599:     }
 1600:     $items=~s/\&$//;
 1601:     if (!$udom) {
 1602:         $udom=$env{'user.domain'};
 1603:         if (defined(&domain($udom,'primary'))) {
 1604:             $uhome=&domain($udom,'primary');
 1605:         } else {
 1606:             undef($uhome);
 1607:         }
 1608:     } else {
 1609:         if (!$uhome) {
 1610:             if (defined(&domain($udom,'primary'))) {
 1611:                 $uhome=&domain($udom,'primary');
 1612:             }
 1613:         }
 1614:     }
 1615:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1616:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1617:         my %returnhash;
 1618:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1619:             return %returnhash;
 1620:         }
 1621:         my @pairs=split(/\&/,$rep);
 1622:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1623:             return @pairs;
 1624:         }
 1625:         my $i=0;
 1626:         foreach my $item (@$storearr) {
 1627:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1628:             $i++;
 1629:         }
 1630:         return %returnhash;
 1631:     } else {
 1632:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1633:     }
 1634: }
 1635: 
 1636: # -------------------------------------------- put items in domain db files 
 1637: 
 1638: sub put_dom {
 1639:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1640:     if (!$udom) {
 1641:         $udom=$env{'user.domain'};
 1642:         if (defined(&domain($udom,'primary'))) {
 1643:             $uhome=&domain($udom,'primary');
 1644:         } else {
 1645:             undef($uhome);
 1646:         }
 1647:     } else {
 1648:         if (!$uhome) {
 1649:             if (defined(&domain($udom,'primary'))) {
 1650:                 $uhome=&domain($udom,'primary');
 1651:             }
 1652:         }
 1653:     } 
 1654:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1655:         my $items='';
 1656:         foreach my $item (keys(%$storehash)) {
 1657:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1658:         }
 1659:         $items=~s/\&$//;
 1660:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1661:     } else {
 1662:         &logthis("put_dom failed - no homeserver and/or domain");
 1663:     }
 1664: }
 1665: 
 1666: # --------------------- newput for items in db file owned by domainconfig user
 1667: sub newput_dom {
 1668:     my ($namespace,$storehash,$udom) = @_;
 1669:     my $result;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:     }
 1673:     if ($udom) {
 1674:         my $uname = &get_domainconfiguser($udom);
 1675:         $result = &newput($namespace,$storehash,$udom,$uname);
 1676:     }
 1677:     return $result;
 1678: }
 1679: 
 1680: # --------------------- delete for items in db file owned by domainconfig user
 1681: sub del_dom {
 1682:     my ($namespace,$storearr,$udom)=@_;
 1683:     if (ref($storearr) eq 'ARRAY') {
 1684:         if (!$udom) {
 1685:             $udom=$env{'user.domain'};
 1686:         }
 1687:         if ($udom) {
 1688:             my $uname = &get_domainconfiguser($udom); 
 1689:             return &del($namespace,$storearr,$udom,$uname);
 1690:         }
 1691:     }
 1692: }
 1693: 
 1694: # ----------------------------------construct domainconfig user for a domain 
 1695: sub get_domainconfiguser {
 1696:     my ($udom) = @_;
 1697:     return $udom.'-domainconfig';
 1698: }
 1699: 
 1700: sub retrieve_inst_usertypes {
 1701:     my ($udom) = @_;
 1702:     my (%returnhash,@order);
 1703:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1704:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1705:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1706:         %returnhash = %{$domdefs{'inststatustypes'}};
 1707:         @order = @{$domdefs{'inststatusorder'}};
 1708:     } else {
 1709:         if (defined(&domain($udom,'primary'))) {
 1710:             my $uhome=&domain($udom,'primary');
 1711:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1712:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1713:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1714:                 return (\%returnhash,\@order);
 1715:             }
 1716:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1717:             my @pairs=split(/\&/,$hashitems);
 1718:             foreach my $item (@pairs) {
 1719:                 my ($key,$value)=split(/=/,$item,2);
 1720:                 $key = &unescape($key);
 1721:                 next if ($key =~ /^error: 2 /);
 1722:                 $returnhash{$key}=&thaw_unescape($value);
 1723:             }
 1724:             my @esc_order = split(/\&/,$orderitems);
 1725:             foreach my $item (@esc_order) {
 1726:                 push(@order,&unescape($item));
 1727:             }
 1728:         } else {
 1729:             &logthis("get_dom failed - no primary domain server for $udom");
 1730:         }
 1731:     }
 1732:     return (\%returnhash,\@order);
 1733: }
 1734: 
 1735: sub is_domainimage {
 1736:     my ($url) = @_;
 1737:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1738:         if (&domain($1) ne '') {
 1739:             return '1';
 1740:         }
 1741:     }
 1742:     return;
 1743: }
 1744: 
 1745: sub inst_directory_query {
 1746:     my ($srch) = @_;
 1747:     my $udom = $srch->{'srchdomain'};
 1748:     my %results;
 1749:     my $homeserver = &domain($udom,'primary');
 1750:     my $outcome;
 1751:     if ($homeserver ne '') {
 1752: 	my $queryid=&reply("querysend:instdirsearch:".
 1753: 			   &escape($srch->{'srchby'}).':'.
 1754: 			   &escape($srch->{'srchterm'}).':'.
 1755: 			   &escape($srch->{'srchtype'}),$homeserver);
 1756: 	my $host=&hostname($homeserver);
 1757: 	if ($queryid !~/^\Q$host\E\_/) {
 1758: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1759: 	    return;
 1760: 	}
 1761: 	my $response = &get_query_reply($queryid);
 1762: 	my $maxtries = 5;
 1763: 	my $tries = 1;
 1764: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1765: 	    $response = &get_query_reply($queryid);
 1766: 	    $tries ++;
 1767: 	}
 1768: 
 1769:         if (!&error($response) && $response ne 'refused') {
 1770:             if ($response eq 'unavailable') {
 1771:                 $outcome = $response;
 1772:             } else {
 1773:                 $outcome = 'ok';
 1774:                 my @matches = split(/\n/,$response);
 1775:                 foreach my $match (@matches) {
 1776:                     my ($key,$value) = split(/=/,$match);
 1777:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1778:                 }
 1779:             }
 1780:         }
 1781:     }
 1782:     return ($outcome,%results);
 1783: }
 1784: 
 1785: sub usersearch {
 1786:     my ($srch) = @_;
 1787:     my $dom = $srch->{'srchdomain'};
 1788:     my %results;
 1789:     my %libserv = &all_library();
 1790:     my $query = 'usersearch';
 1791:     foreach my $tryserver (keys(%libserv)) {
 1792:         if (&host_domain($tryserver) eq $dom) {
 1793:             my $host=&hostname($tryserver);
 1794:             my $queryid=
 1795:                 &reply("querysend:".&escape($query).':'.
 1796:                        &escape($srch->{'srchby'}).':'.
 1797:                        &escape($srch->{'srchtype'}).':'.
 1798:                        &escape($srch->{'srchterm'}),$tryserver);
 1799:             if ($queryid !~/^\Q$host\E\_/) {
 1800:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1801:                 next;
 1802:             }
 1803:             my $reply = &get_query_reply($queryid);
 1804:             my $maxtries = 1;
 1805:             my $tries = 1;
 1806:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1807:                 $reply = &get_query_reply($queryid);
 1808:                 $tries ++;
 1809:             }
 1810:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1811:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1812:             } else {
 1813:                 my @matches;
 1814:                 if ($reply =~ /\n/) {
 1815:                     @matches = split(/\n/,$reply);
 1816:                 } else {
 1817:                     @matches = split(/\&/,$reply);
 1818:                 }
 1819:                 foreach my $match (@matches) {
 1820:                     my ($uname,$udom,%userhash);
 1821:                     foreach my $entry (split(/:/,$match)) {
 1822:                         my ($key,$value) =
 1823:                             map {&unescape($_);} split(/=/,$entry);
 1824:                         $userhash{$key} = $value;
 1825:                         if ($key eq 'username') {
 1826:                             $uname = $value;
 1827:                         } elsif ($key eq 'domain') {
 1828:                             $udom = $value;
 1829:                         }
 1830:                     }
 1831:                     $results{$uname.':'.$udom} = \%userhash;
 1832:                 }
 1833:             }
 1834:         }
 1835:     }
 1836:     return %results;
 1837: }
 1838: 
 1839: sub get_instuser {
 1840:     my ($udom,$uname,$id) = @_;
 1841:     my $homeserver = &domain($udom,'primary');
 1842:     my ($outcome,%results);
 1843:     if ($homeserver ne '') {
 1844:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1845:                            &escape($id).':'.&escape($udom),$homeserver);
 1846:         my $host=&hostname($homeserver);
 1847:         if ($queryid !~/^\Q$host\E\_/) {
 1848:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1849:             return;
 1850:         }
 1851:         my $response = &get_query_reply($queryid);
 1852:         my $maxtries = 5;
 1853:         my $tries = 1;
 1854:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1855:             $response = &get_query_reply($queryid);
 1856:             $tries ++;
 1857:         }
 1858:         if (!&error($response) && $response ne 'refused') {
 1859:             if ($response eq 'unavailable') {
 1860:                 $outcome = $response;
 1861:             } else {
 1862:                 $outcome = 'ok';
 1863:                 my @matches = split(/\n/,$response);
 1864:                 foreach my $match (@matches) {
 1865:                     my ($key,$value) = split(/=/,$match);
 1866:                     $results{&unescape($key)} = &thaw_unescape($value);
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     my %userinfo;
 1872:     if (ref($results{$uname}) eq 'HASH') {
 1873:         %userinfo = %{$results{$uname}};
 1874:     } 
 1875:     return ($outcome,%userinfo);
 1876: }
 1877: 
 1878: sub inst_rulecheck {
 1879:     my ($udom,$uname,$id,$item,$rules) = @_;
 1880:     my %returnhash;
 1881:     if ($udom ne '') {
 1882:         if (ref($rules) eq 'ARRAY') {
 1883:             @{$rules} = map {&escape($_);} (@{$rules});
 1884:             my $rulestr = join(':',@{$rules});
 1885:             my $homeserver=&domain($udom,'primary');
 1886:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1887:                 my $response;
 1888:                 if ($item eq 'username') {                
 1889:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1890:                                               ':'.&escape($uname).':'.$rulestr,
 1891:                                               $homeserver));
 1892:                 } elsif ($item eq 'id') {
 1893:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1894:                                               ':'.&escape($id).':'.$rulestr,
 1895:                                               $homeserver));
 1896:                 } elsif ($item eq 'selfcreate') {
 1897:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1898:                                                &escape($udom).':'.&escape($uname).
 1899:                                               ':'.$rulestr,$homeserver));
 1900:                 }
 1901:                 if ($response ne 'refused') {
 1902:                     my @pairs=split(/\&/,$response);
 1903:                     foreach my $item (@pairs) {
 1904:                         my ($key,$value)=split(/=/,$item,2);
 1905:                         $key = &unescape($key);
 1906:                         next if ($key =~ /^error: 2 /);
 1907:                         $returnhash{$key}=&thaw_unescape($value);
 1908:                     }
 1909:                 }
 1910:             }
 1911:         }
 1912:     }
 1913:     return %returnhash;
 1914: }
 1915: 
 1916: sub inst_userrules {
 1917:     my ($udom,$check) = @_;
 1918:     my (%ruleshash,@ruleorder);
 1919:     if ($udom ne '') {
 1920:         my $homeserver=&domain($udom,'primary');
 1921:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1922:             my $response;
 1923:             if ($check eq 'id') {
 1924:                 $response=&reply('instidrules:'.&escape($udom),
 1925:                                  $homeserver);
 1926:             } elsif ($check eq 'email') {
 1927:                 $response=&reply('instemailrules:'.&escape($udom),
 1928:                                  $homeserver);
 1929:             } else {
 1930:                 $response=&reply('instuserrules:'.&escape($udom),
 1931:                                  $homeserver);
 1932:             }
 1933:             if (($response ne 'refused') && ($response ne 'error') && 
 1934:                 ($response ne 'unknown_cmd') && 
 1935:                 ($response ne 'no_such_host')) {
 1936:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1937:                 my @pairs=split(/\&/,$hashitems);
 1938:                 foreach my $item (@pairs) {
 1939:                     my ($key,$value)=split(/=/,$item,2);
 1940:                     $key = &unescape($key);
 1941:                     next if ($key =~ /^error: 2 /);
 1942:                     $ruleshash{$key}=&thaw_unescape($value);
 1943:                 }
 1944:                 my @esc_order = split(/\&/,$orderitems);
 1945:                 foreach my $item (@esc_order) {
 1946:                     push(@ruleorder,&unescape($item));
 1947:                 }
 1948:             }
 1949:         }
 1950:     }
 1951:     return (\%ruleshash,\@ruleorder);
 1952: }
 1953: 
 1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1955: 
 1956: sub get_domain_defaults {
 1957:     my ($domain) = @_;
 1958:     my $cachetime = 60*60*24;
 1959:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1960:     if (defined($cached)) {
 1961:         if (ref($result) eq 'HASH') {
 1962:             return %{$result};
 1963:         }
 1964:     }
 1965:     my %domdefaults;
 1966:     my %domconfig =
 1967:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1968:                                   'requestcourses','inststatus',
 1969:                                   'coursedefaults','usersessions',
 1970:                                   'requestauthor'],$domain);
 1971:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1972:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1973:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1974:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1975:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1976:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1977:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1978:     } else {
 1979:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1980:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1981:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1982:     }
 1983:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1984:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1986:         } else {
 1987:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1988:         }
 1989:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1990:         foreach my $item (@usertools) {
 1991:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1992:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1993:             }
 1994:         }
 1995:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 1996:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 1997:         }
 1998:     }
 1999:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2000:         foreach my $item ('official','unofficial','community') {
 2001:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2002:         }
 2003:     }
 2004:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2005:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2006:     }
 2007:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2008:         foreach my $item ('inststatustypes','inststatusorder') {
 2009:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2010:         }
 2011:     }
 2012:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2013:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2014:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2015:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2016:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2017:         }
 2018:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2019:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2020:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2021:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2022:         }
 2023:     }
 2024:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2025:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2026:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2027:         }
 2028:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2029:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2030:         }
 2031:     }
 2032:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2033:     return %domdefaults;
 2034: }
 2035: 
 2036: # --------------------------------------------------- Assign a key to a student
 2037: 
 2038: sub assign_access_key {
 2039: #
 2040: # a valid key looks like uname:udom#comments
 2041: # comments are being appended
 2042: #
 2043:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2044:     $kdom=
 2045:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2046:     $knum=
 2047:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2048:     $cdom=
 2049:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2050:     $cnum=
 2051:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2052:     $udom=$env{'user.name'} unless (defined($udom));
 2053:     $uname=$env{'user.domain'} unless (defined($uname));
 2054:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2055:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2056:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2057:                                                   # assigned to this person
 2058:                                                   # - this should not happen,
 2059:                                                   # unless something went wrong
 2060:                                                   # the first time around
 2061: # ready to assign
 2062:         $logentry=$1.'; '.$logentry;
 2063:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2064:                                                  $kdom,$knum) eq 'ok') {
 2065: # key now belongs to user
 2066: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2067:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2068:                 &appenv({'environment.'.$envkey => $ckey});
 2069:                 return 'ok';
 2070:             } else {
 2071:                 return 
 2072:   'error: Count not permanently assign key, will need to be re-entered later.';
 2073: 	    }
 2074:         } else {
 2075:             return 'error: Could not assign key, try again later.';
 2076:         }
 2077:     } elsif (!$existing{$ckey}) {
 2078: # the key does not exist
 2079: 	return 'error: The key does not exist';
 2080:     } else {
 2081: # the key is somebody else's
 2082: 	return 'error: The key is already in use';
 2083:     }
 2084: }
 2085: 
 2086: # ------------------------------------------ put an additional comment on a key
 2087: 
 2088: sub comment_access_key {
 2089: #
 2090: # a valid key looks like uname:udom#comments
 2091: # comments are being appended
 2092: #
 2093:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2094:     $cdom=
 2095:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2096:     $cnum=
 2097:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2098:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2099:     if ($existing{$ckey}) {
 2100:         $existing{$ckey}.='; '.$logentry;
 2101: # ready to assign
 2102:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2103:                                                  $cdom,$cnum) eq 'ok') {
 2104: 	    return 'ok';
 2105:         } else {
 2106: 	    return 'error: Count not store comment.';
 2107:         }
 2108:     } else {
 2109: # the key does not exist
 2110: 	return 'error: The key does not exist';
 2111:     }
 2112: }
 2113: 
 2114: # ------------------------------------------------------ Generate a set of keys
 2115: 
 2116: sub generate_access_keys {
 2117:     my ($number,$cdom,$cnum,$logentry)=@_;
 2118:     $cdom=
 2119:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2120:     $cnum=
 2121:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2122:     unless (&allowed('mky',$cdom)) { return 0; }
 2123:     unless (($cdom) && ($cnum)) { return 0; }
 2124:     if ($number>10000) { return 0; }
 2125:     sleep(2); # make sure don't get same seed twice
 2126:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2127:     my $total=0;
 2128:     for (my $i=1;$i<=$number;$i++) {
 2129:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2130:                   sprintf("%lx",int(100000*rand)).'-'.
 2131:                   sprintf("%lx",int(100000*rand));
 2132:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2133:        $newkey=~s/0/h/g; # and also 0 and O
 2134:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2135:        if ($existing{$newkey}) {
 2136:            $i--;
 2137:        } else {
 2138: 	  if (&put('accesskeys',
 2139:               { $newkey => '# generated '.localtime().
 2140:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2141:                            '; '.$logentry },
 2142: 		   $cdom,$cnum) eq 'ok') {
 2143:               $total++;
 2144: 	  }
 2145:        }
 2146:     }
 2147:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2148:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2149:     return $total;
 2150: }
 2151: 
 2152: # ------------------------------------------------------- Validate an accesskey
 2153: 
 2154: sub validate_access_key {
 2155:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2156:     $cdom=
 2157:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2158:     $cnum=
 2159:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2160:     $udom=$env{'user.domain'} unless (defined($udom));
 2161:     $uname=$env{'user.name'} unless (defined($uname));
 2162:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2163:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2164: }
 2165: 
 2166: # ------------------------------------- Find the section of student in a course
 2167: sub devalidate_getsection_cache {
 2168:     my ($udom,$unam,$courseid)=@_;
 2169:     my $hashid="$udom:$unam:$courseid";
 2170:     &devalidate_cache_new('getsection',$hashid);
 2171: }
 2172: 
 2173: sub courseid_to_courseurl {
 2174:     my ($courseid) = @_;
 2175:     #already url style courseid
 2176:     return $courseid if ($courseid =~ m{^/});
 2177: 
 2178:     if (exists($env{'course.'.$courseid.'.num'})) {
 2179: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2180: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2181: 	return "/$cdom/$cnum";
 2182:     }
 2183: 
 2184:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2185:     if (exists($courseinfo{'num'})) {
 2186: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2187:     }
 2188: 
 2189:     return undef;
 2190: }
 2191: 
 2192: sub getsection {
 2193:     my ($udom,$unam,$courseid)=@_;
 2194:     my $cachetime=1800;
 2195: 
 2196:     my $hashid="$udom:$unam:$courseid";
 2197:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2198:     if (defined($cached)) { return $result; }
 2199: 
 2200:     my %Pending; 
 2201:     my %Expired;
 2202:     #
 2203:     # Each role can either have not started yet (pending), be active, 
 2204:     #    or have expired.
 2205:     #
 2206:     # If there is an active role, we are done.
 2207:     #
 2208:     # If there is more than one role which has not started yet, 
 2209:     #     choose the one which will start sooner
 2210:     # If there is one role which has not started yet, return it.
 2211:     #
 2212:     # If there is more than one expired role, choose the one which ended last.
 2213:     # If there is a role which has expired, return it.
 2214:     #
 2215:     $courseid = &courseid_to_courseurl($courseid);
 2216:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2217:     foreach my $key (keys(%roleshash)) {
 2218:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2219:         my $section=$1;
 2220:         if ($key eq $courseid.'_st') { $section=''; }
 2221:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2222:         my $now=time;
 2223:         if (defined($end) && $end && ($now > $end)) {
 2224:             $Expired{$end}=$section;
 2225:             next;
 2226:         }
 2227:         if (defined($start) && $start && ($now < $start)) {
 2228:             $Pending{$start}=$section;
 2229:             next;
 2230:         }
 2231:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2232:     }
 2233:     #
 2234:     # Presumedly there will be few matching roles from the above
 2235:     # loop and the sorting time will be negligible.
 2236:     if (scalar(keys(%Pending))) {
 2237:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2238:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2239:     } 
 2240:     if (scalar(keys(%Expired))) {
 2241:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2242:         my $time = pop(@sorted);
 2243:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2244:     }
 2245:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2246: }
 2247: 
 2248: sub save_cache {
 2249:     &purge_remembered();
 2250:     #&Apache::loncommon::validate_page();
 2251:     undef(%env);
 2252:     undef($env_loaded);
 2253: }
 2254: 
 2255: my $to_remember=-1;
 2256: my %remembered;
 2257: my %accessed;
 2258: my $kicks=0;
 2259: my $hits=0;
 2260: sub make_key {
 2261:     my ($name,$id) = @_;
 2262:     if (length($id) > 65 
 2263: 	&& length(&escape($id)) > 200) {
 2264: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2265:     }
 2266:     return &escape($name.':'.$id);
 2267: }
 2268: 
 2269: sub devalidate_cache_new {
 2270:     my ($name,$id,$debug) = @_;
 2271:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2272:     $id=&make_key($name,$id);
 2273:     $memcache->delete($id);
 2274:     delete($remembered{$id});
 2275:     delete($accessed{$id});
 2276: }
 2277: 
 2278: sub is_cached_new {
 2279:     my ($name,$id,$debug) = @_;
 2280:     $id=&make_key($name,$id);
 2281:     if (exists($remembered{$id})) {
 2282: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2283: 	$accessed{$id}=[&gettimeofday()];
 2284: 	$hits++;
 2285: 	return ($remembered{$id},1);
 2286:     }
 2287:     my $value = $memcache->get($id);
 2288:     if (!(defined($value))) {
 2289: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2290: 	return (undef,undef);
 2291:     }
 2292:     if ($value eq '__undef__') {
 2293: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2294: 	$value=undef;
 2295:     }
 2296:     &make_room($id,$value,$debug);
 2297:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2298:     return ($value,1);
 2299: }
 2300: 
 2301: sub do_cache_new {
 2302:     my ($name,$id,$value,$time,$debug) = @_;
 2303:     $id=&make_key($name,$id);
 2304:     my $setvalue=$value;
 2305:     if (!defined($setvalue)) {
 2306: 	$setvalue='__undef__';
 2307:     }
 2308:     if (!defined($time) ) {
 2309: 	$time=600;
 2310:     }
 2311:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2312:     my $result = $memcache->set($id,$setvalue,$time);
 2313:     if (! $result) {
 2314: 	&logthis("caching of id -> $id  failed");
 2315: 	$memcache->disconnect_all();
 2316:     }
 2317:     # need to make a copy of $value
 2318:     &make_room($id,$value,$debug);
 2319:     return $value;
 2320: }
 2321: 
 2322: sub make_room {
 2323:     my ($id,$value,$debug)=@_;
 2324: 
 2325:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2326:                                     : $value;
 2327:     if ($to_remember<0) { return; }
 2328:     $accessed{$id}=[&gettimeofday()];
 2329:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2330:     my $to_kick;
 2331:     my $max_time=0;
 2332:     foreach my $other (keys(%accessed)) {
 2333: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2334: 	    $to_kick=$other;
 2335: 	    $max_time=&tv_interval($accessed{$other});
 2336: 	}
 2337:     }
 2338:     delete($remembered{$to_kick});
 2339:     delete($accessed{$to_kick});
 2340:     $kicks++;
 2341:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2342:     return;
 2343: }
 2344: 
 2345: sub purge_remembered {
 2346:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2347:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2348:     undef(%remembered);
 2349:     undef(%accessed);
 2350: }
 2351: # ------------------------------------- Read an entry from a user's environment
 2352: 
 2353: sub userenvironment {
 2354:     my ($udom,$unam,@what)=@_;
 2355:     my $items;
 2356:     foreach my $item (@what) {
 2357:         $items.=&escape($item).'&';
 2358:     }
 2359:     $items=~s/\&$//;
 2360:     my %returnhash=();
 2361:     my $uhome = &homeserver($unam,$udom);
 2362:     unless ($uhome eq 'no_host') {
 2363:         my @answer=split(/\&/, 
 2364:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2365:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2366:             return %returnhash;
 2367:         }
 2368:         my $i;
 2369:         for ($i=0;$i<=$#what;$i++) {
 2370: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2371:         }
 2372:     }
 2373:     return %returnhash;
 2374: }
 2375: 
 2376: # ---------------------------------------------------------- Get a studentphoto
 2377: sub studentphoto {
 2378:     my ($udom,$unam,$ext) = @_;
 2379:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2380:     if (defined($env{'request.course.id'})) {
 2381:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2382:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2383:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2384:             } else {
 2385:                 my ($result,$perm_reqd)=
 2386: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2387:                 if ($result eq 'ok') {
 2388:                     if (!($perm_reqd eq 'yes')) {
 2389:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2390:                     }
 2391:                 }
 2392:             }
 2393:         }
 2394:     } else {
 2395:         my ($result,$perm_reqd) = 
 2396: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2397:         if ($result eq 'ok') {
 2398:             if (!($perm_reqd eq 'yes')) {
 2399:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2400:             }
 2401:         }
 2402:     }
 2403:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2404: }
 2405: 
 2406: sub retrievestudentphoto {
 2407:     my ($udom,$unam,$ext,$type) = @_;
 2408:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2409:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2410:     if ($ret eq 'ok') {
 2411:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2412:         if ($type eq 'thumbnail') {
 2413:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2414:         }
 2415:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2416:         return $tokenurl;
 2417:     } else {
 2418:         if ($type eq 'thumbnail') {
 2419:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2420:         } else { 
 2421:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2422:         }
 2423:     }
 2424: }
 2425: 
 2426: # -------------------------------------------------------------------- New chat
 2427: 
 2428: sub chatsend {
 2429:     my ($newentry,$anon,$group)=@_;
 2430:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2431:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2432:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2433:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2434: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2435: 		   &escape($newentry)).':'.$group,$chome);
 2436: }
 2437: 
 2438: # ------------------------------------------ Find current version of a resource
 2439: 
 2440: sub getversion {
 2441:     my $fname=&clutter(shift);
 2442:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2443:     return &currentversion(&filelocation('',$fname));
 2444: }
 2445: 
 2446: sub currentversion {
 2447:     my $fname=shift;
 2448:     my $author=$fname;
 2449:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2450:     my ($udom,$uname)=split(/\//,$author);
 2451:     my $home=&homeserver($uname,$udom);
 2452:     if ($home eq 'no_host') { 
 2453:         return -1; 
 2454:     }
 2455:     my $answer=&reply("currentversion:$fname",$home);
 2456:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2457: 	return -1;
 2458:     }
 2459:     return $answer;
 2460: }
 2461: 
 2462: #
 2463: # Return special version number of resource if set by override, empty otherwise
 2464: #
 2465: sub usedversion {
 2466:     my $fname=shift;
 2467:     unless ($fname) { $fname=$env{'request.uri'}; }
 2468:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2469:     if ($urlversion) { return $urlversion; }
 2470:     return '';
 2471: }
 2472: 
 2473: # ----------------------------- Subscribe to a resource, return URL if possible
 2474: 
 2475: sub subscribe {
 2476:     my $fname=shift;
 2477:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2478:     $fname=~s/[\n\r]//g;
 2479:     my $author=$fname;
 2480:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2481:     my ($udom,$uname)=split(/\//,$author);
 2482:     my $home=homeserver($uname,$udom);
 2483:     if ($home eq 'no_host') {
 2484:         return 'not_found';
 2485:     }
 2486:     my $answer=reply("sub:$fname",$home);
 2487:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2488: 	$answer.=' by '.$home;
 2489:     }
 2490:     return $answer;
 2491: }
 2492:     
 2493: # -------------------------------------------------------------- Replicate file
 2494: 
 2495: sub repcopy {
 2496:     my $filename=shift;
 2497:     $filename=~s/\/+/\//g;
 2498:     my $londocroot = $perlvar{'lonDocRoot'};
 2499:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2500:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2501:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2502: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2503: 	return &repcopy_userfile($filename);
 2504:     }
 2505:     $filename=~s/[\n\r]//g;
 2506:     my $transname="$filename.in.transfer";
 2507: # FIXME: this should flock
 2508:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2509:     my $remoteurl=subscribe($filename);
 2510:     if ($remoteurl =~ /^con_lost by/) {
 2511: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2512:            return 'unavailable';
 2513:     } elsif ($remoteurl eq 'not_found') {
 2514: 	   #&logthis("Subscribe returned not_found: $filename");
 2515: 	   return 'not_found';
 2516:     } elsif ($remoteurl =~ /^rejected by/) {
 2517: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2518:            return 'forbidden';
 2519:     } elsif ($remoteurl eq 'directory') {
 2520:            return 'ok';
 2521:     } else {
 2522:         my $author=$filename;
 2523:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2524:         my ($udom,$uname)=split(/\//,$author);
 2525:         my $home=homeserver($uname,$udom);
 2526:         unless ($home eq $perlvar{'lonHostID'}) {
 2527:            my @parts=split(/\//,$filename);
 2528:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2529:            if ($path ne "$londocroot/res") {
 2530:                &logthis("Malconfiguration for replication: $filename");
 2531: 	       return 'bad_request';
 2532:            }
 2533:            my $count;
 2534:            for ($count=5;$count<$#parts;$count++) {
 2535:                $path.="/$parts[$count]";
 2536:                if ((-e $path)!=1) {
 2537: 		   mkdir($path,0777);
 2538:                }
 2539:            }
 2540:            my $ua=new LWP::UserAgent;
 2541:            my $request=new HTTP::Request('GET',"$remoteurl");
 2542:            my $response=$ua->request($request,$transname);
 2543:            if ($response->is_error()) {
 2544: 	       unlink($transname);
 2545:                my $message=$response->status_line;
 2546:                &logthis("<font color=\"blue\">WARNING:"
 2547:                        ." LWP get: $message: $filename</font>");
 2548:                return 'unavailable';
 2549:            } else {
 2550: 	       if ($remoteurl!~/\.meta$/) {
 2551:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2552:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2553:                   if ($mresponse->is_error()) {
 2554: 		      unlink($filename.'.meta');
 2555:                       &logthis(
 2556:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2557:                   }
 2558: 	       }
 2559:                rename($transname,$filename);
 2560:                return 'ok';
 2561:            }
 2562:        }
 2563:     }
 2564: }
 2565: 
 2566: # ------------------------------------------------ Get server side include body
 2567: sub ssi_body {
 2568:     my ($filelink,%form)=@_;
 2569:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2570:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2571:     }
 2572:     my $output='';
 2573:     my $response;
 2574:     if ($filelink=~/^https?\:/) {
 2575:        ($output,$response)=&externalssi($filelink);
 2576:     } else {
 2577:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2578:        $filelink .= 'inhibitmenu=yes';
 2579:        ($output,$response)=&ssi($filelink,%form);
 2580:     }
 2581:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2582:     $output=~s/^.*?\<body[^\>]*\>//si;
 2583:     $output=~s/\<\/body\s*\>.*?$//si;
 2584:     if (wantarray) {
 2585:         return ($output, $response);
 2586:     } else {
 2587:         return $output;
 2588:     }
 2589: }
 2590: 
 2591: # --------------------------------------------------------- Server Side Include
 2592: 
 2593: sub absolute_url {
 2594:     my ($host_name) = @_;
 2595:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2596:     if ($host_name eq '') {
 2597: 	$host_name = $ENV{'SERVER_NAME'};
 2598:     }
 2599:     return $protocol.$host_name;
 2600: }
 2601: 
 2602: #
 2603: #   Server side include.
 2604: # Parameters:
 2605: #  fn     Possibly encrypted resource name/id.
 2606: #  form   Hash that describes how the rendering should be done
 2607: #         and other things.
 2608: # Returns:
 2609: #   Scalar context: The content of the response.
 2610: #   Array context:  2 element list of the content and the full response object.
 2611: #     
 2612: sub ssi {
 2613: 
 2614:     my ($fn,%form)=@_;
 2615:     my $ua=new LWP::UserAgent;
 2616:     my $request;
 2617: 
 2618:     $form{'no_update_last_known'}=1;
 2619:     &Apache::lonenc::check_encrypt(\$fn);
 2620:     if (%form) {
 2621:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2622:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2623:     } else {
 2624:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2625:     }
 2626: 
 2627:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2628:     my $response= $ua->request($request);
 2629:     my $content = $response->content;
 2630: 
 2631: 
 2632:     if (wantarray) {
 2633: 	return ($content, $response);
 2634:     } else {
 2635: 	return $content;
 2636:     }
 2637: }
 2638: 
 2639: sub externalssi {
 2640:     my ($url)=@_;
 2641:     my $ua=new LWP::UserAgent;
 2642:     my $request=new HTTP::Request('GET',$url);
 2643:     my $response=$ua->request($request);
 2644:     if (wantarray) {
 2645:         return ($response->content, $response);
 2646:     } else {
 2647:         return $response->content;
 2648:     }
 2649: }
 2650: 
 2651: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2652: 
 2653: sub allowuploaded {
 2654:     my ($srcurl,$url)=@_;
 2655:     $url=&clutter(&declutter($url));
 2656:     my $dir=$url;
 2657:     $dir=~s/\/[^\/]+$//;
 2658:     my %httpref=();
 2659:     my $httpurl=&hreflocation('',$url);
 2660:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2661:     &Apache::lonnet::appenv(\%httpref);
 2662: }
 2663: 
 2664: #
 2665: # Determine if the current user should be able to edit a particular resource,
 2666: # when viewing in course context.
 2667: # (a) When viewing resource used to determine if "Edit" item is included in 
 2668: #     Functions.
 2669: # (b) When displaying folder contents in course editor, used to determine if
 2670: #     "Edit" link will be displayed alongside resource.
 2671: #
 2672: #  input: six args -- filename (decluttered), course number, course domain,
 2673: #                   url, symb (if registered) and group (if this is a group
 2674: #                   item -- e.g., bulletin board, group page etc.).
 2675: #  output: array of five scalars -- 
 2676: #          $cfile -- url for file editing if editable on current server
 2677: #          $home -- homeserver of resource (i.e., for author if published,
 2678: #                                           or course if uploaded.).
 2679: #          $switchserver --  1 if server switch will be needed.
 2680: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2681: #          $forceview -- 1 if icon/link should be to go to view mode
 2682: #
 2683: 
 2684: sub can_edit_resource {
 2685:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2686:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2687: #
 2688: # For aboutme pages user can only edit his/her own.
 2689: #
 2690:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2691:         my ($sdom,$sname) = ($1,$2);
 2692:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2693:             $home = $env{'user.home'};
 2694:             $cfile = $resurl;
 2695:             if ($env{'form.forceedit'}) {
 2696:                 $forceview = 1;
 2697:             } else {
 2698:                 $forceedit = 1;
 2699:             }
 2700:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2701:         } else {
 2702:             return;
 2703:         }
 2704:     }
 2705: 
 2706:     if ($env{'request.course.id'}) {
 2707:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2708:         if ($group ne '') {
 2709: # if this is a group homepage or group bulletin board, check group privs
 2710:             my $allowed = 0;
 2711:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2712:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2713:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2714:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2715:                     $allowed = 1;
 2716:                 }
 2717:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2718:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2719:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2720:                     $allowed = 1;
 2721:                 }
 2722:             }
 2723:             if ($allowed) {
 2724:                 $home=&homeserver($cnum,$cdom);
 2725:                 if ($env{'form.forceedit'}) {
 2726:                     $forceview = 1;
 2727:                 } else {
 2728:                     $forceedit = 1;
 2729:                 }
 2730:                 $cfile = $resurl;
 2731:             } else {
 2732:                 return;
 2733:             }
 2734:         } else {
 2735:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2736:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2737:                     return;
 2738:                 }
 2739:             } elsif (!$crsedit) {
 2740: #
 2741: # No edit allowed where CC has switched to student role.
 2742: #
 2743:                 return;
 2744:             }
 2745:         }
 2746:     }
 2747: 
 2748:     if ($file ne '') {
 2749:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2750:             if (&is_course_upload($file,$cnum,$cdom)) {
 2751:                 $uploaded = 1;
 2752:                 $incourse = 1;
 2753:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2754:                     $cfile = &hreflocation('',$file);
 2755:                     if ($env{'form.forceedit'}) {
 2756:                         $forceview = 1;
 2757:                     } else {
 2758:                         $forceedit = 1;
 2759:                     }
 2760:                 }
 2761:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2762:                 $incourse = 1;
 2763:                 if ($env{'form.forceedit'}) {
 2764:                     $forceview = 1;
 2765:                 } else {
 2766:                     $forceedit = 1;
 2767:                 }
 2768:                 $cfile = $resurl;
 2769:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2770:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2771:                     $incourse = 1;
 2772:                     if ($env{'form.forceedit'}) {
 2773:                         $forceview = 1;
 2774:                     } else {
 2775:                         $forceedit = 1;
 2776:                     }
 2777:                     $cfile = $resurl;
 2778:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2779:                     $incourse = 1;
 2780:                     $cfile = $resurl.'/smpedit';
 2781:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2782:                     $incourse = 1;
 2783:                     if ($env{'form.forceedit'}) {
 2784:                         $forceview = 1;
 2785:                     } else {
 2786:                         $forceedit = 1;
 2787:                     }
 2788:                     $cfile = $resurl;
 2789:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2790:                     $incourse = 1;
 2791:                     if ($env{'form.forceedit'}) {
 2792:                         $forceview = 1;
 2793:                     } else {
 2794:                         $forceedit = 1;
 2795:                     }
 2796:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2797:                 }
 2798:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2799:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2800:                 if (&is_on_map($template)) { 
 2801:                     $incourse = 1;
 2802:                     $forceview = 1;
 2803:                     $cfile = $template;
 2804:                 }
 2805:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2806:                     $incourse = 1;
 2807:                     if ($env{'form.forceedit'}) {
 2808:                         $forceview = 1;
 2809:                     } else {
 2810:                         $forceedit = 1;
 2811:                     }
 2812:                     $cfile = $resurl;
 2813:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2814:                 $incourse = 1;
 2815:                 $forceview = 1;
 2816:                 if ($symb) {
 2817:                     my ($map,$id,$res)=&decode_symb($symb);
 2818:                     $env{'request.symb'} = $symb;
 2819:                     $cfile = &clutter($res);
 2820:                 } else {
 2821:                     $cfile = $env{'form.suppurl'};
 2822:                     $cfile =~ s{^http://}{};
 2823:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2824:                 }
 2825:             }
 2826:         }
 2827:         if ($uploaded || $incourse) {
 2828:             $home=&homeserver($cnum,$cdom);
 2829:         } elsif ($file !~ m{/$}) {
 2830:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2831:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2832:             # Check that the user has permission to edit this resource
 2833:             my $setpriv = 1;
 2834:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2835:             if (defined($cfudom)) {
 2836:                 $home=&homeserver($cfuname,$cfudom);
 2837:                 $cfile=$file;
 2838:             }
 2839:         }
 2840:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2841:             (($home ne '') && ($home ne 'no_host'))) {
 2842:             my @ids=&current_machine_ids();
 2843:             unless (grep(/^\Q$home\E$/,@ids)) {
 2844:                 $switchserver=1;
 2845:             }
 2846:         }
 2847:     }
 2848:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2849: }
 2850: 
 2851: sub is_course_upload {
 2852:     my ($file,$cnum,$cdom) = @_;
 2853:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2854:     $uploadpath =~ s{^\/}{};
 2855:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2856:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2857:         return 1;
 2858:     }
 2859:     return;
 2860: }
 2861: 
 2862: sub in_course {
 2863:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2864:     if ($hideprivileged) {
 2865:         my $skipuser;
 2866:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2867:         my @possdoms = ($cdom);  
 2868:         if ($coursehash{'checkforpriv'}) { 
 2869:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2870:         }
 2871:         if (&privileged($uname,$udom,\@possdoms)) {
 2872:             $skipuser = 1;
 2873:             if ($coursehash{'nothideprivileged'}) {
 2874:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2875:                     my $user;
 2876:                     if ($item =~ /:/) {
 2877:                         $user = $item;
 2878:                     } else {
 2879:                         $user = join(':',split(/[\@]/,$item));
 2880:                     }
 2881:                     if ($user eq $uname.':'.$udom) {
 2882:                         undef($skipuser);
 2883:                         last;
 2884:                     }
 2885:                 }
 2886:             }
 2887:             if ($skipuser) {
 2888:                 return 0;
 2889:             }
 2890:         }
 2891:     }
 2892:     $type ||= 'any';
 2893:     if (!defined($cdom) || !defined($cnum)) {
 2894:         my $cid  = $env{'request.course.id'};
 2895:         $cdom = $env{'course.'.$cid.'.domain'};
 2896:         $cnum = $env{'course.'.$cid.'.num'};
 2897:     }
 2898:     my $typesref;
 2899:     if (($type eq 'any') || ($type eq 'all')) {
 2900:         $typesref = ['active','previous','future'];
 2901:     } elsif ($type eq 'previous' || $type eq 'future') {
 2902:         $typesref = [$type];
 2903:     }
 2904:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2905:                               $typesref,undef,[$cdom]);
 2906:     my ($tmp) = keys(%roles);
 2907:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2908:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2909:     if (@course_roles > 0) {
 2910:         return 1;
 2911:     }
 2912:     return 0;
 2913: }
 2914: 
 2915: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2916: # input: action, courseID, current domain, intended
 2917: #        path to file, source of file, instruction to parse file for objects,
 2918: #        ref to hash for embedded objects,
 2919: #        ref to hash for codebase of java objects.
 2920: #        reference to scalar to accommodate mime type determined
 2921: #          from File::MMagic if $parser = parse.
 2922: #
 2923: # output: url to file (if action was uploaddoc), 
 2924: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2925: #
 2926: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2927: # course.
 2928: #
 2929: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2930: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2931: #          course's home server.
 2932: #
 2933: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2934: #          be copied from $source (current location) to 
 2935: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2936: #         and will then be copied to
 2937: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2938: #         course's home server.
 2939: #
 2940: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2941: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2942: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2943: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2944: #         in course's home server.
 2945: #
 2946: 
 2947: sub process_coursefile {
 2948:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2949:         $mimetype)=@_;
 2950:     my $fetchresult;
 2951:     my $home=&homeserver($docuname,$docudom);
 2952:     if ($action eq 'propagate') {
 2953:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2954: 			     $home);
 2955:     } else {
 2956:         my $fpath = '';
 2957:         my $fname = $file;
 2958:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2959:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2960:         my $filepath = &build_filepath($fpath);
 2961:         if ($action eq 'copy') {
 2962:             if ($source eq '') {
 2963:                 $fetchresult = 'no source file';
 2964:                 return $fetchresult;
 2965:             } else {
 2966:                 my $destination = $filepath.'/'.$fname;
 2967:                 rename($source,$destination);
 2968:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2969:                                  $home);
 2970:             }
 2971:         } elsif ($action eq 'uploaddoc') {
 2972:             open(my $fh,'>'.$filepath.'/'.$fname);
 2973:             print $fh $env{'form.'.$source};
 2974:             close($fh);
 2975:             if ($parser eq 'parse') {
 2976:                 my $mm = new File::MMagic;
 2977:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2978:                 if ($type eq 'text/html') {
 2979:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2980:                     unless ($parse_result eq 'ok') {
 2981:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2982:                     }
 2983:                 }
 2984:                 if (ref($mimetype)) {
 2985:                     $$mimetype = $type;
 2986:                 } 
 2987:             }
 2988:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2989:                                  $home);
 2990:             if ($fetchresult eq 'ok') {
 2991:                 return '/uploaded/'.$fpath.'/'.$fname;
 2992:             } else {
 2993:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2994:                         ' to host '.$home.': '.$fetchresult);
 2995:                 return '/adm/notfound.html';
 2996:             }
 2997:         }
 2998:     }
 2999:     unless ( $fetchresult eq 'ok') {
 3000:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3001:              ' to host '.$home.': '.$fetchresult);
 3002:     }
 3003:     return $fetchresult;
 3004: }
 3005: 
 3006: sub build_filepath {
 3007:     my ($fpath) = @_;
 3008:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3009:     unless ($fpath eq '') {
 3010:         my @parts=split('/',$fpath);
 3011:         foreach my $part (@parts) {
 3012:             $filepath.= '/'.$part;
 3013:             if ((-e $filepath)!=1) {
 3014:                 mkdir($filepath,0777);
 3015:             }
 3016:         }
 3017:     }
 3018:     return $filepath;
 3019: }
 3020: 
 3021: sub store_edited_file {
 3022:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3023:     my $file = $primary_url;
 3024:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3025:     my $fpath = '';
 3026:     my $fname = $file;
 3027:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3028:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3029:     my $filepath = &build_filepath($fpath);
 3030:     open(my $fh,'>'.$filepath.'/'.$fname);
 3031:     print $fh $content;
 3032:     close($fh);
 3033:     my $home=&homeserver($docuname,$docudom);
 3034:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3035: 			  $home);
 3036:     if ($$fetchresult eq 'ok') {
 3037:         return '/uploaded/'.$fpath.'/'.$fname;
 3038:     } else {
 3039:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3040: 		 ' to host '.$home.': '.$$fetchresult);
 3041:         return '/adm/notfound.html';
 3042:     }
 3043: }
 3044: 
 3045: sub clean_filename {
 3046:     my ($fname,$args)=@_;
 3047: # Replace Windows backslashes by forward slashes
 3048:     $fname=~s/\\/\//g;
 3049:     if (!$args->{'keep_path'}) {
 3050:         # Get rid of everything but the actual filename
 3051: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3052:     }
 3053: # Replace spaces by underscores
 3054:     $fname=~s/\s+/\_/g;
 3055: # Replace all other weird characters by nothing
 3056:     $fname=~s{[^/\w\.\-]}{}g;
 3057: # Replace all .\d. sequences with _\d. so they no longer look like version
 3058: # numbers
 3059:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3060:     return $fname;
 3061: }
 3062: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3063: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3064: # image with the same aspect ratio as the original, but with dimensions which do 
 3065: # not exceed $resizewidth and $resizeheight.
 3066:  
 3067: sub resizeImage {
 3068:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3069:     my $ima = Image::Magick->new;
 3070:     my $resized;
 3071:     if (-e $img_path) {
 3072:         $ima->Read($img_path);
 3073:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3074:             my $width = $ima->Get('width');
 3075:             my $height = $ima->Get('height');
 3076:             if ($width > $resizewidth) {
 3077: 	        my $factor = $width/$resizewidth;
 3078:                 my $newheight = $height/$factor;
 3079:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3080:                 $resized = 1;
 3081:             }
 3082:         }
 3083:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3084:             my $width = $ima->Get('width');
 3085:             my $height = $ima->Get('height');
 3086:             if ($height > $resizeheight) {
 3087:                 my $factor = $height/$resizeheight;
 3088:                 my $newwidth = $width/$factor;
 3089:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3090:                 $resized = 1;
 3091:             }
 3092:         }
 3093:         if ($resized) {
 3094:             $ima->Write($img_path);
 3095:         }
 3096:     }
 3097:     return;
 3098: }
 3099: 
 3100: # --------------- Take an uploaded file and put it into the userfiles directory
 3101: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3102: #                    the desired filename is in $env{"form.$formname.filename"}
 3103: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3104: #                                    canceloverwrite, or ''. 
 3105: #                   if 'coursedoc': upload to the current course
 3106: #                   if 'existingfile': write file to tmp/overwrites directory 
 3107: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3108: #                   $context is passed as argument to &finishuserfileupload
 3109: #        $subdir - directory in userfile to store the file into
 3110: #        $parser - instruction to parse file for objects ($parser = parse)    
 3111: #        $allfiles - reference to hash for embedded objects
 3112: #        $codebase - reference to hash for codebase of java objects
 3113: #        $desuname - username for permanent storage of uploaded file
 3114: #        $dsetudom - domain for permanaent storage of uploaded file
 3115: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3116: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3117: #        $resizewidth - width (pixels) to which to resize uploaded image
 3118: #        $resizeheight - height (pixels) to which to resize uploaded image
 3119: #        $mimetype - reference to scalar to accommodate mime type determined
 3120: #                    from File::MMagic.
 3121: # 
 3122: # output: url of file in userspace, or error: <message> 
 3123: #             or /adm/notfound.html if failure to upload occurse
 3124: 
 3125: sub userfileupload {
 3126:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3127:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3128:     if (!defined($subdir)) { $subdir='unknown'; }
 3129:     my $fname=$env{'form.'.$formname.'.filename'};
 3130:     $fname=&clean_filename($fname);
 3131:     # See if there is anything left
 3132:     unless ($fname) { return 'error: no uploaded file'; }
 3133:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3134:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3135:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3136:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3137:         my $now = time;
 3138:         my $filepath;
 3139:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3140:              $filepath = 'tmp/helprequests/'.$now;
 3141:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3142:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3143:                          '_'.$env{'user.domain'}.'/pending';
 3144:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3145:             my ($docuname,$docudom);
 3146:             if ($destudom) {
 3147:                 $docudom = $destudom;
 3148:             } else {
 3149:                 $docudom = $env{'user.domain'};
 3150:             }
 3151:             if ($destuname) {
 3152:                 $docuname = $destuname;
 3153:             } else {
 3154:                 $docuname = $env{'user.name'};
 3155:             }
 3156:             if (exists($env{'form.group'})) {
 3157:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3158:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3159:             }
 3160:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3161:             if ($context eq 'canceloverwrite') {
 3162:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3163:                 if (-e  $tempfile) {
 3164:                     my @info = stat($tempfile);
 3165:                     if ($info[9] eq $env{'form.timestamp'}) {
 3166:                         unlink($tempfile);
 3167:                     }
 3168:                 }
 3169:                 return;
 3170:             }
 3171:         }
 3172:         # Create the directory if not present
 3173:         my @parts=split(/\//,$filepath);
 3174:         my $fullpath = $perlvar{'lonDaemons'};
 3175:         for (my $i=0;$i<@parts;$i++) {
 3176:             $fullpath .= '/'.$parts[$i];
 3177:             if ((-e $fullpath)!=1) {
 3178:                 mkdir($fullpath,0777);
 3179:             }
 3180:         }
 3181:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3182:         print $fh $env{'form.'.$formname};
 3183:         close($fh);
 3184:         if ($context eq 'existingfile') {
 3185:             my @info = stat($fullpath.'/'.$fname);
 3186:             return ($fullpath.'/'.$fname,$info[9]);
 3187:         } else {
 3188:             return $fullpath.'/'.$fname;
 3189:         }
 3190:     }
 3191:     if ($subdir eq 'scantron') {
 3192:         $fname = 'scantron_orig_'.$fname;
 3193:     } else {
 3194:         $fname="$subdir/$fname";
 3195:     }
 3196:     if ($context eq 'coursedoc') {
 3197: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3198: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3199:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3200:             return &finishuserfileupload($docuname,$docudom,
 3201: 					 $formname,$fname,$parser,$allfiles,
 3202: 					 $codebase,$thumbwidth,$thumbheight,
 3203:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3204:         } else {
 3205:             if ($env{'form.folder'}) {
 3206:                 $fname=$env{'form.folder'}.'/'.$fname;
 3207:             }
 3208:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3209: 				       $fname,$formname,$parser,
 3210: 				       $allfiles,$codebase,$mimetype);
 3211:         }
 3212:     } elsif (defined($destuname)) {
 3213:         my $docuname=$destuname;
 3214:         my $docudom=$destudom;
 3215: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3216: 				     $parser,$allfiles,$codebase,
 3217:                                      $thumbwidth,$thumbheight,
 3218:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3219:     } else {
 3220:         my $docuname=$env{'user.name'};
 3221:         my $docudom=$env{'user.domain'};
 3222:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3223:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3224:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3225:         }
 3226: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3227: 				     $parser,$allfiles,$codebase,
 3228:                                      $thumbwidth,$thumbheight,
 3229:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3230:     }
 3231: }
 3232: 
 3233: sub finishuserfileupload {
 3234:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3235:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3236:     my $path=$docudom.'/'.$docuname.'/';
 3237:     my $filepath=$perlvar{'lonDocRoot'};
 3238:   
 3239:     my ($fnamepath,$file,$fetchthumb);
 3240:     $file=$fname;
 3241:     if ($fname=~m|/|) {
 3242:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3243: 	$path.=$fnamepath.'/';
 3244:     }
 3245:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3246:     my $count;
 3247:     for ($count=4;$count<=$#parts;$count++) {
 3248:         $filepath.="/$parts[$count]";
 3249:         if ((-e $filepath)!=1) {
 3250: 	    mkdir($filepath,0777);
 3251:         }
 3252:     }
 3253: 
 3254: # Save the file
 3255:     {
 3256: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3257: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3258: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3259: 	    return '/adm/notfound.html';
 3260: 	}
 3261:         if ($context eq 'overwrite') {
 3262:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3263:             my $target = $filepath.'/'.$file;
 3264:             if (-e $source) {
 3265:                 my @info = stat($source);
 3266:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3267:                     unless (&File::Copy::move($source,$target)) {
 3268:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3269:                         return "Moving from $source failed";
 3270:                     }
 3271:                 } else {
 3272:                     return "Temporary file: $source had unexpected date/time for last modification";
 3273:                 }
 3274:             } else {
 3275:                 return "Temporary file: $source missing";
 3276:             }
 3277:         } elsif (!print FH ($env{'form.'.$formname})) {
 3278: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3279: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3280: 	    return '/adm/notfound.html';
 3281: 	}
 3282: 	close(FH);
 3283:         if ($resizewidth && $resizeheight) {
 3284:             my $mm = new File::MMagic;
 3285:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3286:             if ($mime_type =~ m{^image/}) {
 3287: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3288:             }  
 3289: 	}
 3290:     }
 3291:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3292:         if (ref($mimetype)) {
 3293:             if ($$mimetype eq '') {
 3294:                 my $mm = new File::MMagic;
 3295:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3296:                 $$mimetype = $type;
 3297:             }
 3298:         }
 3299:     }
 3300:     if ($parser eq 'parse') {
 3301:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3302:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3303:                                                        $allfiles,$codebase);
 3304:             unless ($parse_result eq 'ok') {
 3305:                 &logthis('Failed to parse '.$filepath.$file.
 3306: 	   	         ' for embedded media: '.$parse_result); 
 3307:             }
 3308:         }
 3309:     }
 3310:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3311:         my $input = $filepath.'/'.$file;
 3312:         my $output = $filepath.'/'.'tn-'.$file;
 3313:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3314:         system("convert -sample $thumbsize $input $output");
 3315:         if (-e $filepath.'/'.'tn-'.$file) {
 3316:             $fetchthumb  = 1; 
 3317:         }
 3318:     }
 3319:  
 3320: # Notify homeserver to grep it
 3321: #
 3322:     my $docuhome=&homeserver($docuname,$docudom);	
 3323:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3324:     if ($fetchresult eq 'ok') {
 3325:         if ($fetchthumb) {
 3326:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3327:             if ($thumbresult ne 'ok') {
 3328:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3329:                          $docuhome.': '.$thumbresult);
 3330:             }
 3331:         }
 3332: #
 3333: # Return the URL to it
 3334:         return '/uploaded/'.$path.$file;
 3335:     } else {
 3336:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3337: 		 ': '.$fetchresult);
 3338:         return '/adm/notfound.html';
 3339:     }
 3340: }
 3341: 
 3342: sub extract_embedded_items {
 3343:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3344:     my @state = ();
 3345:     my (%lastids,%related,%shockwave,%flashvars);
 3346:     my %javafiles = (
 3347:                       codebase => '',
 3348:                       code => '',
 3349:                       archive => ''
 3350:                     );
 3351:     my %mediafiles = (
 3352:                       src => '',
 3353:                       movie => '',
 3354:                      );
 3355:     my $p;
 3356:     if ($content) {
 3357:         $p = HTML::LCParser->new($content);
 3358:     } else {
 3359:         $p = HTML::LCParser->new($fullpath);
 3360:     }
 3361:     while (my $t=$p->get_token()) {
 3362: 	if ($t->[0] eq 'S') {
 3363: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3364: 	    push(@state, $tagname);
 3365:             if (lc($tagname) eq 'allow') {
 3366:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3367:             }
 3368: 	    if (lc($tagname) eq 'img') {
 3369: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3370: 	    }
 3371: 	    if (lc($tagname) eq 'a') {
 3372:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3373:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3374:                 }
 3375: 	    }
 3376:             if (lc($tagname) eq 'script') {
 3377:                 my $src;
 3378:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3379:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3380:                 } else {
 3381:                     if ($attr->{'src'} ne '') {
 3382:                         $src = $attr->{'src'};
 3383:                         &add_filetype($allfiles,$src,'src');
 3384:                     }
 3385:                 }
 3386:                 my $text = $p->get_trimmed_text();
 3387:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3388:                     my @swfargs = split(/,/,$1);
 3389:                     foreach my $item (@swfargs) {
 3390:                         $item =~ s/["']//g;
 3391:                         $item =~ s/^\s+//;
 3392:                         $item =~ s/\s+$//;
 3393:                     }
 3394:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3395:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3396:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3397:                         } else {
 3398:                             $related{$swfargs[0]} = [$swfargs[2]];
 3399:                         }
 3400:                     }
 3401:                 }
 3402:             }
 3403:             if (lc($tagname) eq 'link') {
 3404:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3405:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3406:                 }
 3407:             }
 3408: 	    if (lc($tagname) eq 'object' ||
 3409: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3410: 		foreach my $item (keys(%javafiles)) {
 3411: 		    $javafiles{$item} = '';
 3412: 		}
 3413:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3414:                     $lastids{lc($tagname)} = $attr->{'id'};
 3415:                 }
 3416: 	    }
 3417: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3418: 		my $name = lc($attr->{'name'});
 3419: 		foreach my $item (keys(%javafiles)) {
 3420: 		    if ($name eq $item) {
 3421: 			$javafiles{$item} = $attr->{'value'};
 3422: 			last;
 3423: 		    }
 3424: 		}
 3425:                 my $pathfrom;
 3426: 		foreach my $item (keys(%mediafiles)) {
 3427: 		    if ($name eq $item) {
 3428:                         $pathfrom = $attr->{'value'};
 3429:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3430: 			&add_filetype($allfiles,$pathfrom,$name);
 3431: 			last;
 3432: 		    }
 3433: 		}
 3434:                 if ($name eq 'flashvars') {
 3435:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3436:                 }
 3437:                 if ($pathfrom ne '') {
 3438:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3439:                                          $pathfrom);
 3440:                 }
 3441: 	    }
 3442: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3443: 		foreach my $item (keys(%javafiles)) {
 3444: 		    if ($attr->{$item}) {
 3445: 			$javafiles{$item} = $attr->{$item};
 3446: 			last;
 3447: 		    }
 3448: 		}
 3449: 		foreach my $item (keys(%mediafiles)) {
 3450: 		    if ($attr->{$item}) {
 3451: 			&add_filetype($allfiles,$attr->{$item},$item);
 3452: 			last;
 3453: 		    }
 3454: 		}
 3455:                 if (lc($tagname) eq 'embed') {
 3456:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3457:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3458:                                              $attr->{'src'});
 3459:                     }
 3460:                 }
 3461: 	    }
 3462:             if ($t->[4] =~ m{/>$}) {
 3463:                 pop(@state);  
 3464:             }
 3465: 	} elsif ($t->[0] eq 'E') {
 3466: 	    my ($tagname) = ($t->[1]);
 3467: 	    if ($javafiles{'codebase'} ne '') {
 3468: 		$javafiles{'codebase'} .= '/';
 3469: 	    }  
 3470: 	    if (lc($tagname) eq 'applet' ||
 3471: 		lc($tagname) eq 'object' ||
 3472: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3473: 		) {
 3474: 		foreach my $item (keys(%javafiles)) {
 3475: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3476: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3477: 			&add_filetype($allfiles,$file,$item);
 3478: 		    }
 3479: 		}
 3480: 	    } 
 3481: 	    pop @state;
 3482: 	}
 3483:     }
 3484:     foreach my $id (sort(keys(%flashvars))) {
 3485:         if ($shockwave{$id} ne '') {
 3486:             my @pairs = split(/\&/,$flashvars{$id});
 3487:             foreach my $pair (@pairs) {
 3488:                 my ($key,$value) = split(/\=/,$pair);
 3489:                 if ($key eq 'thumb') {
 3490:                     &add_filetype($allfiles,$value,$key);
 3491:                 } elsif ($key eq 'content') {
 3492:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3493:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3494:                     if ($ext ne '') {
 3495:                         &add_filetype($allfiles,$path.$value,$ext);
 3496:                     }
 3497:                 }
 3498:             }
 3499:         }
 3500:     }
 3501:     return 'ok';
 3502: }
 3503: 
 3504: sub add_filetype {
 3505:     my ($allfiles,$file,$type)=@_;
 3506:     if (exists($allfiles->{$file})) {
 3507: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3508: 	    push(@{$allfiles->{$file}}, &escape($type));
 3509: 	}
 3510:     } else {
 3511: 	@{$allfiles->{$file}} = (&escape($type));
 3512:     }
 3513: }
 3514: 
 3515: sub embedded_dependency {
 3516:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3517:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3518:         if (($identifier ne '') &&
 3519:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3520:             ($pathfrom ne '')) {
 3521:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3522:             foreach my $dep (@{$related->{$identifier}}) {
 3523:                 &add_filetype($allfiles,$path.$dep,'object');
 3524:             }
 3525:         }
 3526:     }
 3527:     return;
 3528: }
 3529: 
 3530: sub removeuploadedurl {
 3531:     my ($url)=@_;	
 3532:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3533:     return &removeuserfile($uname,$udom,$fname);
 3534: }
 3535: 
 3536: sub removeuserfile {
 3537:     my ($docuname,$docudom,$fname)=@_;
 3538:     my $home=&homeserver($docuname,$docudom);    
 3539:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3540:     if ($result eq 'ok') {	
 3541:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3542:             my $metafile = $fname.'.meta';
 3543:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3544: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3545:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3546:             my $sqlresult = 
 3547:                 &update_portfolio_table($docuname,$docudom,$file,
 3548:                                         'portfolio_metadata',$group,
 3549:                                         'delete');
 3550:         }
 3551:     }
 3552:     return $result;
 3553: }
 3554: 
 3555: sub mkdiruserfile {
 3556:     my ($docuname,$docudom,$dir)=@_;
 3557:     my $home=&homeserver($docuname,$docudom);
 3558:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3559: }
 3560: 
 3561: sub renameuserfile {
 3562:     my ($docuname,$docudom,$old,$new)=@_;
 3563:     my $home=&homeserver($docuname,$docudom);
 3564:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3565:                         &escape("$old").':'.&escape("$new"),$home);
 3566:     if ($result eq 'ok') {
 3567:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3568:             my $oldmeta = $old.'.meta';
 3569:             my $newmeta = $new.'.meta';
 3570:             my $metaresult = 
 3571:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3572: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3573:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3574:             my $sqlresult = 
 3575:                 &update_portfolio_table($docuname,$docudom,$file,
 3576:                                         'portfolio_metadata',$group,
 3577:                                         'delete');
 3578:         }
 3579:     }
 3580:     return $result;
 3581: }
 3582: 
 3583: # ------------------------------------------------------------------------- Log
 3584: 
 3585: sub log {
 3586:     my ($dom,$nam,$hom,$what)=@_;
 3587:     return critical("log:$dom:$nam:$what",$hom);
 3588: }
 3589: 
 3590: # ------------------------------------------------------------------ Course Log
 3591: #
 3592: # This routine flushes several buffers of non-mission-critical nature
 3593: #
 3594: 
 3595: sub flushcourselogs {
 3596:     &logthis('Flushing log buffers');
 3597: #
 3598: # course logs
 3599: # This is a log of all transactions in a course, which can be used
 3600: # for data mining purposes
 3601: #
 3602: # It also collects the courseid database, which lists last transaction
 3603: # times and course titles for all courseids
 3604: #
 3605:     my %courseidbuffer=();
 3606:     foreach my $crsid (keys(%courselogs)) {
 3607:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3608: 		          &escape($courselogs{$crsid}),
 3609: 		          $coursehombuf{$crsid}) eq 'ok') {
 3610: 	    delete $courselogs{$crsid};
 3611:         } else {
 3612:             &logthis('Failed to flush log buffer for '.$crsid);
 3613:             if (length($courselogs{$crsid})>40000) {
 3614:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3615:                         " exceeded maximum size, deleting.</font>");
 3616:                delete $courselogs{$crsid};
 3617:             }
 3618:         }
 3619:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3620:             'description' => $coursedescrbuf{$crsid},
 3621:             'inst_code'    => $courseinstcodebuf{$crsid},
 3622:             'type'        => $coursetypebuf{$crsid},
 3623:             'owner'       => $courseownerbuf{$crsid},
 3624:         };
 3625:     }
 3626: #
 3627: # Write course id database (reverse lookup) to homeserver of courses 
 3628: # Is used in pickcourse
 3629: #
 3630:     foreach my $crs_home (keys(%courseidbuffer)) {
 3631:         my $response = &courseidput(&host_domain($crs_home),
 3632:                                     $courseidbuffer{$crs_home},
 3633:                                     $crs_home,'timeonly');
 3634:     }
 3635: #
 3636: # File accesses
 3637: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3638: #
 3639:     foreach my $entry (keys(%accesshash)) {
 3640:         if ($entry =~ /___count$/) {
 3641:             my ($dom,$name);
 3642:             ($dom,$name,undef)=
 3643: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3644:             if (! defined($dom) || $dom eq '' || 
 3645:                 ! defined($name) || $name eq '') {
 3646:                 my $cid = $env{'request.course.id'};
 3647:                 $dom  = $env{'request.'.$cid.'.domain'};
 3648:                 $name = $env{'request.'.$cid.'.num'};
 3649:             }
 3650:             my $value = $accesshash{$entry};
 3651:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3652:             my %temphash=($url => $value);
 3653:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3654:             if ($result eq 'ok') {
 3655:                 delete $accesshash{$entry};
 3656:             }
 3657:         } else {
 3658:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3659:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3660:             my %temphash=($entry => $accesshash{$entry});
 3661:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3662:                 delete $accesshash{$entry};
 3663:             }
 3664:         }
 3665:     }
 3666: #
 3667: # Roles
 3668: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3669: #
 3670:     foreach my $entry (keys(%userrolehash)) {
 3671:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3672: 	    split(/\:/,$entry);
 3673:         if (&Apache::lonnet::put('nohist_userroles',
 3674:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3675:                 $rudom,$runame) eq 'ok') {
 3676: 	    delete $userrolehash{$entry};
 3677:         }
 3678:     }
 3679: #
 3680: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3681: #
 3682:     my %domrolebuffer = ();
 3683:     foreach my $entry (keys(%domainrolehash)) {
 3684:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3685:         if ($domrolebuffer{$rudom}) {
 3686:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3687:                       '='.&escape($domainrolehash{$entry});
 3688:         } else {
 3689:             $domrolebuffer{$rudom}.=&escape($entry).
 3690:                       '='.&escape($domainrolehash{$entry});
 3691:         }
 3692:         delete $domainrolehash{$entry};
 3693:     }
 3694:     foreach my $dom (keys(%domrolebuffer)) {
 3695: 	my %servers = &get_servers($dom,'library');
 3696: 	foreach my $tryserver (keys(%servers)) {
 3697: 	    unless (&reply('domroleput:'.$dom.':'.
 3698: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3699: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3700: 	    }
 3701:         }
 3702:     }
 3703:     $dumpcount++;
 3704: }
 3705: 
 3706: sub courselog {
 3707:     my $what=shift;
 3708:     $what=time.':'.$what;
 3709:     unless ($env{'request.course.id'}) { return ''; }
 3710:     $coursedombuf{$env{'request.course.id'}}=
 3711:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3712:     $coursenumbuf{$env{'request.course.id'}}=
 3713:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3714:     $coursehombuf{$env{'request.course.id'}}=
 3715:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3716:     $coursedescrbuf{$env{'request.course.id'}}=
 3717:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3718:     $courseinstcodebuf{$env{'request.course.id'}}=
 3719:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3720:     $courseownerbuf{$env{'request.course.id'}}=
 3721:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3722:     $coursetypebuf{$env{'request.course.id'}}=
 3723:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3724:     if (defined $courselogs{$env{'request.course.id'}}) {
 3725: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3726:     } else {
 3727: 	$courselogs{$env{'request.course.id'}}.=$what;
 3728:     }
 3729:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3730: 	&flushcourselogs();
 3731:     }
 3732: }
 3733: 
 3734: sub courseacclog {
 3735:     my $fnsymb=shift;
 3736:     unless ($env{'request.course.id'}) { return ''; }
 3737:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3738:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3739:         $what.=':POST';
 3740:         # FIXME: Probably ought to escape things....
 3741: 	foreach my $key (keys(%env)) {
 3742:             if ($key=~/^form\.(.*)/) {
 3743:                 my $formitem = $1;
 3744:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3745:                     $what.=':'.$formitem.'='.$env{$key};
 3746:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3747:                     $what.=':'.$formitem.'='.$env{$key};
 3748:                 }
 3749:             }
 3750:         }
 3751:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3752:         # FIXME: We should not be depending on a form parameter that someone
 3753:         # editing lonsearchcat.pm might change in the future.
 3754:         if ($env{'form.phase'} eq 'course_search') {
 3755:             $what.= ':POST';
 3756:             # FIXME: Probably ought to escape things....
 3757:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3758:                                  'crsdiscuss') {
 3759:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3760:             }
 3761:         }
 3762:     }
 3763:     &courselog($what);
 3764: }
 3765: 
 3766: sub countacc {
 3767:     my $url=&declutter(shift);
 3768:     return if (! defined($url) || $url eq '');
 3769:     unless ($env{'request.course.id'}) { return ''; }
 3770: #
 3771: # Mark that this url was used in this course
 3772: #
 3773:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3774: #
 3775: # Increase the access count for this resource in this child process
 3776: #
 3777:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3778:     $accesshash{$key}++;
 3779: }
 3780: 
 3781: sub linklog {
 3782:     my ($from,$to)=@_;
 3783:     $from=&declutter($from);
 3784:     $to=&declutter($to);
 3785:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3786:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3787: }
 3788: 
 3789: sub statslog {
 3790:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3791:     if ($users<2) { return; }
 3792:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3793:             'course'       => $env{'request.course.id'},
 3794:             'sections'     => '"all"',
 3795:             'num_students' => $users,
 3796:             'part'         => $part,
 3797:             'symb'         => $symb,
 3798:             'mean_tries'   => $av_attempts,
 3799:             'deg_of_diff'  => $degdiff});
 3800:     foreach my $key (keys(%dynstore)) {
 3801:         $accesshash{$key}=$dynstore{$key};
 3802:     }
 3803: }
 3804:   
 3805: sub userrolelog {
 3806:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3807:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3808:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3809:        $userrolehash
 3810:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3811:                     =$tend.':'.$tstart;
 3812:     }
 3813:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3814:        $userrolehash
 3815:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3816:                     =$tend.':'.$tstart;
 3817:     }
 3818:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3819:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3820:        $domainrolehash
 3821:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3822:                     = $tend.':'.$tstart;
 3823:     }
 3824: }
 3825: 
 3826: sub courserolelog {
 3827:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3828:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3829:         my $cdom = $1;
 3830:         my $cnum = $2;
 3831:         my $sec = $3;
 3832:         my $namespace = 'rolelog';
 3833:         my %storehash = (
 3834:                            role    => $trole,
 3835:                            start   => $tstart,
 3836:                            end     => $tend,
 3837:                            selfenroll => $selfenroll,
 3838:                            context    => $context,
 3839:                         );
 3840:         if ($trole eq 'gr') {
 3841:             $namespace = 'groupslog';
 3842:             $storehash{'group'} = $sec;
 3843:         } else {
 3844:             $storehash{'section'} = $sec;
 3845:         }
 3846:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3847:                    $domain,$cnum,$cdom);
 3848:         if (($trole ne 'st') || ($sec ne '')) {
 3849:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3850:         }
 3851:     }
 3852:     return;
 3853: }
 3854: 
 3855: sub domainrolelog {
 3856:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3857:     if ($area =~ m{^/($match_domain)/$}) {
 3858:         my $cdom = $1;
 3859:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3860:         my $namespace = 'rolelog';
 3861:         my %storehash = (
 3862:                            role    => $trole,
 3863:                            start   => $tstart,
 3864:                            end     => $tend,
 3865:                            context => $context,
 3866:                         );
 3867:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3868:                    $domain,$domconfiguser,$cdom);
 3869:     }
 3870:     return;
 3871: 
 3872: }
 3873: 
 3874: sub coauthorrolelog {
 3875:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3876:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3877:         my $audom = $1;
 3878:         my $auname = $2;
 3879:         my $namespace = 'rolelog';
 3880:         my %storehash = (
 3881:                            role    => $trole,
 3882:                            start   => $tstart,
 3883:                            end     => $tend,
 3884:                            context => $context,
 3885:                         );
 3886:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3887:                    $domain,$auname,$audom);
 3888:     }
 3889:     return;
 3890: }
 3891: 
 3892: sub get_course_adv_roles {
 3893:     my ($cid,$codes) = @_;
 3894:     $cid=$env{'request.course.id'} unless (defined($cid));
 3895:     my %coursehash=&coursedescription($cid);
 3896:     my $crstype = &Apache::loncommon::course_type($cid);
 3897:     my %nothide=();
 3898:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3899:         if ($user !~ /:/) {
 3900: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3901:         } else {
 3902:             $nothide{$user}=1;
 3903:         }
 3904:     }
 3905:     my @possdoms = ($coursehash{'domain'});
 3906:     if ($coursehash{'checkforpriv'}) {
 3907:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3908:     }
 3909:     my %returnhash=();
 3910:     my %dumphash=
 3911:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3912:     my $now=time;
 3913:     my %privileged;
 3914:     foreach my $entry (keys(%dumphash)) {
 3915: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3916:         if (($tstart) && ($tstart<0)) { next; }
 3917:         if (($tend) && ($tend<$now)) { next; }
 3918:         if (($tstart) && ($now<$tstart)) { next; }
 3919:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3920: 	if ($username eq '' || $domain eq '') { next; }
 3921:         if ((&privileged($username,$domain,\@possdoms)) &&
 3922:             (!$nothide{$username.':'.$domain})) { next; }
 3923: 	if ($role eq 'cr') { next; }
 3924:         if ($codes) {
 3925:             if ($section) { $role .= ':'.$section; }
 3926:             if ($returnhash{$role}) {
 3927:                 $returnhash{$role}.=','.$username.':'.$domain;
 3928:             } else {
 3929:                 $returnhash{$role}=$username.':'.$domain;
 3930:             }
 3931:         } else {
 3932:             my $key=&plaintext($role,$crstype);
 3933:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3934:             if ($returnhash{$key}) {
 3935: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3936:             } else {
 3937:                 $returnhash{$key}=$username.':'.$domain;
 3938:             }
 3939:         }
 3940:     }
 3941:     return %returnhash;
 3942: }
 3943: 
 3944: sub get_my_roles {
 3945:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3946:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3947:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3948:     my (%dumphash,%nothide);
 3949:     if ($context eq 'userroles') {
 3950:         %dumphash = &dump('roles',$udom,$uname);
 3951:     } else {
 3952:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 3953:         if ($hidepriv) {
 3954:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3955:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3956:                 if ($user !~ /:/) {
 3957:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3958:                 } else {
 3959:                     $nothide{$user} = 1;
 3960:                 }
 3961:             }
 3962:         }
 3963:     }
 3964:     my %returnhash=();
 3965:     my $now=time;
 3966:     my %privileged;
 3967:     foreach my $entry (keys(%dumphash)) {
 3968:         my ($role,$tend,$tstart);
 3969:         if ($context eq 'userroles') {
 3970:             next if ($entry =~ /^rolesdef/);
 3971: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3972:         } else {
 3973:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3974:         }
 3975:         if (($tstart) && ($tstart<0)) { next; }
 3976:         my $status = 'active';
 3977:         if (($tend) && ($tend<=$now)) {
 3978:             $status = 'previous';
 3979:         } 
 3980:         if (($tstart) && ($now<$tstart)) {
 3981:             $status = 'future';
 3982:         }
 3983:         if (ref($types) eq 'ARRAY') {
 3984:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3985:                 next;
 3986:             } 
 3987:         } else {
 3988:             if ($status ne 'active') {
 3989:                 next;
 3990:             }
 3991:         }
 3992:         my ($rolecode,$username,$domain,$section,$area);
 3993:         if ($context eq 'userroles') {
 3994:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3995:             (undef,$domain,$username,$section) = split(/\//,$area);
 3996:         } else {
 3997:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3998:         }
 3999:         if (ref($roledoms) eq 'ARRAY') {
 4000:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4001:                 next;
 4002:             }
 4003:         }
 4004:         if (ref($roles) eq 'ARRAY') {
 4005:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4006:                 if ($role =~ /^cr\//) {
 4007:                     if (!grep(/^cr$/,@{$roles})) {
 4008:                         next;
 4009:                     }
 4010:                 } elsif ($role =~ /^gr\//) {
 4011:                     if (!grep(/^gr$/,@{$roles})) {
 4012:                         next;
 4013:                     }
 4014:                 } else {
 4015:                     next;
 4016:                 }
 4017:             }
 4018:         }
 4019:         if ($hidepriv) {
 4020:             my @privroles = ('dc','su');
 4021:             if ($context eq 'userroles') {
 4022:                 next if (grep(/^\Q$role\E$/,@privroles));
 4023:             } else {
 4024:                 my $possdoms = [$domain];
 4025:                 if (ref($roledoms) eq 'ARRAY') {
 4026:                    push(@{$possdoms},@{$roledoms}); 
 4027:                 }
 4028:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4029:                     if (!$nothide{$username.':'.$domain}) {
 4030:                         next;
 4031:                     }
 4032:                 }
 4033:             }
 4034:         }
 4035:         if ($withsec) {
 4036:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4037:                 $tstart.':'.$tend;
 4038:         } else {
 4039:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4040:         }
 4041:     }
 4042:     return %returnhash;
 4043: }
 4044: 
 4045: # ----------------------------------------------------- Frontpage Announcements
 4046: #
 4047: #
 4048: 
 4049: sub postannounce {
 4050:     my ($server,$text)=@_;
 4051:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4052:     unless ($text=~/\w/) { $text=''; }
 4053:     return &reply('setannounce:'.&escape($text),$server);
 4054: }
 4055: 
 4056: sub getannounce {
 4057: 
 4058:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4059: 	my $announcement='';
 4060: 	while (my $line = <$fh>) { $announcement .= $line; }
 4061: 	close($fh);
 4062: 	if ($announcement=~/\w/) { 
 4063: 	    return 
 4064:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4065:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4066: 	} else {
 4067: 	    return '';
 4068: 	}
 4069:     } else {
 4070: 	return '';
 4071:     }
 4072: }
 4073: 
 4074: # ---------------------------------------------------------- Course ID routines
 4075: # Deal with domain's nohist_courseid.db files
 4076: #
 4077: 
 4078: sub courseidput {
 4079:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4080:     return unless (ref($storehash) eq 'HASH');
 4081:     my $outcome;
 4082:     if ($caller eq 'timeonly') {
 4083:         my $cids = '';
 4084:         foreach my $item (keys(%$storehash)) {
 4085:             $cids.=&escape($item).'&';
 4086:         }
 4087:         $cids=~s/\&$//;
 4088:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4089:                           $coursehome);       
 4090:     } else {
 4091:         my $items = '';
 4092:         foreach my $item (keys(%$storehash)) {
 4093:             $items.= &escape($item).'='.
 4094:                      &freeze_escape($$storehash{$item}).'&';
 4095:         }
 4096:         $items=~s/\&$//;
 4097:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4098:                           $coursehome);
 4099:     }
 4100:     if ($outcome eq 'unknown_cmd') {
 4101:         my $what;
 4102:         foreach my $cid (keys(%$storehash)) {
 4103:             $what .= &escape($cid).'=';
 4104:             foreach my $item ('description','inst_code','owner','type') {
 4105:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4106:             }
 4107:             $what =~ s/\:$/&/;
 4108:         }
 4109:         $what =~ s/\&$//;  
 4110:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4111:     } else {
 4112:         return $outcome;
 4113:     }
 4114: }
 4115: 
 4116: sub courseiddump {
 4117:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4118:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4119:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4120:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4121:     my $as_hash = 1;
 4122:     my %returnhash;
 4123:     if (!$domfilter) { $domfilter=''; }
 4124:     my %libserv = &all_library();
 4125:     foreach my $tryserver (keys(%libserv)) {
 4126:         if ( (  $hostidflag == 1 
 4127: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4128: 	     || (!defined($hostidflag)) ) {
 4129: 
 4130: 	    if (($domfilter eq '') ||
 4131: 		(&host_domain($tryserver) eq $domfilter)) {
 4132:                 my $rep;
 4133:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4134:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4135:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4136:                                 &escape($descfilter), &escape($instcodefilter), 
 4137:                                 &escape($ownerfilter), &escape($coursefilter),
 4138:                                 &escape($typefilter), &escape($regexp_ok), 
 4139:                                 $as_hash, &escape($selfenrollonly), 
 4140:                                 &escape($catfilter), $showhidden, $caller, 
 4141:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4142:                                 &escape($createdbefore), &escape($createdafter), 
 4143:                                 &escape($creationcontext), $domcloner)));
 4144:                 } else {
 4145:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4146:                              $sincefilter.':'.&escape($descfilter).':'.
 4147:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4148:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4149:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4150:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4151:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4152:                              &escape($cc_clone).':'.$cloneonly.':'.
 4153:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4154:                              &escape($creationcontext).':'.$domcloner,
 4155:                              $tryserver);
 4156:                 }
 4157:                      
 4158:                 my @pairs=split(/\&/,$rep);
 4159:                 foreach my $item (@pairs) {
 4160:                     my ($key,$value)=split(/\=/,$item,2);
 4161:                     $key = &unescape($key);
 4162:                     next if ($key =~ /^error: 2 /);
 4163:                     my $result = &thaw_unescape($value);
 4164:                     if (ref($result) eq 'HASH') {
 4165:                         $returnhash{$key}=$result;
 4166:                     } else {
 4167:                         my @responses = split(/:/,$value);
 4168:                         my @items = ('description','inst_code','owner','type');
 4169:                         for (my $i=0; $i<@responses; $i++) {
 4170:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4171:                         }
 4172:                     }
 4173:                 }
 4174:             }
 4175:         }
 4176:     }
 4177:     return %returnhash;
 4178: }
 4179: 
 4180: sub courselastaccess {
 4181:     my ($cdom,$cnum,$hostidref) = @_;
 4182:     my %returnhash;
 4183:     if ($cdom && $cnum) {
 4184:         my $chome = &homeserver($cnum,$cdom);
 4185:         if ($chome ne 'no_host') {
 4186:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4187:             &extract_lastaccess(\%returnhash,$rep);
 4188:         }
 4189:     } else {
 4190:         if (!$cdom) { $cdom=''; }
 4191:         my %libserv = &all_library();
 4192:         foreach my $tryserver (keys(%libserv)) {
 4193:             if (ref($hostidref) eq 'ARRAY') {
 4194:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4195:             } 
 4196:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4197:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4198:                 &extract_lastaccess(\%returnhash,$rep);
 4199:             }
 4200:         }
 4201:     }
 4202:     return %returnhash;
 4203: }
 4204: 
 4205: sub extract_lastaccess {
 4206:     my ($returnhash,$rep) = @_;
 4207:     if (ref($returnhash) eq 'HASH') {
 4208:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4209:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4210:                  $rep eq '') {
 4211:             my @pairs=split(/\&/,$rep);
 4212:             foreach my $item (@pairs) {
 4213:                 my ($key,$value)=split(/\=/,$item,2);
 4214:                 $key = &unescape($key);
 4215:                 next if ($key =~ /^error: 2 /);
 4216:                 $returnhash->{$key} = &thaw_unescape($value);
 4217:             }
 4218:         }
 4219:     }
 4220:     return;
 4221: }
 4222: 
 4223: # ---------------------------------------------------------- DC e-mail
 4224: 
 4225: sub dcmailput {
 4226:     my ($domain,$msgid,$message,$server)=@_;
 4227:     my $status = &Apache::lonnet::critical(
 4228:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4229:        &escape($message),$server);
 4230:     return $status;
 4231: }
 4232: 
 4233: sub dcmaildump {
 4234:     my ($dom,$startdate,$enddate,$senders) = @_;
 4235:     my %returnhash=();
 4236: 
 4237:     if (defined(&domain($dom,'primary'))) {
 4238:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4239:                                                          &escape($enddate).':';
 4240: 	my @esc_senders=map { &escape($_)} @$senders;
 4241: 	$cmd.=&escape(join('&',@esc_senders));
 4242: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4243:             my ($key,$value) = split(/\=/,$line,2);
 4244:             if (($key) && ($value)) {
 4245:                 $returnhash{&unescape($key)} = &unescape($value);
 4246:             }
 4247:         }
 4248:     }
 4249:     return %returnhash;
 4250: }
 4251: # ---------------------------------------------------------- Domain roles
 4252: 
 4253: sub get_domain_roles {
 4254:     my ($dom,$roles,$startdate,$enddate)=@_;
 4255:     if ((!defined($startdate)) || ($startdate eq '')) {
 4256:         $startdate = '.';
 4257:     }
 4258:     if ((!defined($enddate)) || ($enddate eq '')) {
 4259:         $enddate = '.';
 4260:     }
 4261:     my $rolelist;
 4262:     if (ref($roles) eq 'ARRAY') {
 4263:         $rolelist = join('&',@{$roles});
 4264:     }
 4265:     my %personnel = ();
 4266: 
 4267:     my %servers = &get_servers($dom,'library');
 4268:     foreach my $tryserver (keys(%servers)) {
 4269: 	%{$personnel{$tryserver}}=();
 4270: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4271: 					    &escape($startdate).':'.
 4272: 					    &escape($enddate).':'.
 4273: 					    &escape($rolelist), $tryserver))) {
 4274: 	    my ($key,$value) = split(/\=/,$line,2);
 4275: 	    if (($key) && ($value)) {
 4276: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4277: 	    }
 4278: 	}
 4279:     }
 4280:     return %personnel;
 4281: }
 4282: 
 4283: # ----------------------------------------------------------- Interval timing 
 4284: 
 4285: {
 4286: # Caches needed for speedup of navmaps
 4287: # We don't want to cache this for very long at all (5 seconds at most)
 4288: # 
 4289: # The user for whom we cache
 4290: my $cachedkey='';
 4291: # The cached times for this user
 4292: my %cachedtimes=();
 4293: # When this was last done
 4294: my $cachedtime=();
 4295: 
 4296: sub load_all_first_access {
 4297:     my ($uname,$udom)=@_;
 4298:     if (($cachedkey eq $uname.':'.$udom) &&
 4299:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4300:         return;
 4301:     }
 4302:     $cachedtime=time;
 4303:     $cachedkey=$uname.':'.$udom;
 4304:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4305: }
 4306: 
 4307: sub get_first_access {
 4308:     my ($type,$argsymb,$argmap)=@_;
 4309:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4310:     if ($argsymb) { $symb=$argsymb; }
 4311:     my ($map,$id,$res)=&decode_symb($symb);
 4312:     if ($argmap) { $map = $argmap; }
 4313:     if ($type eq 'course') {
 4314: 	$res='course';
 4315:     } elsif ($type eq 'map') {
 4316: 	$res=&symbread($map);
 4317:     } else {
 4318: 	$res=$symb;
 4319:     }
 4320:     &load_all_first_access($uname,$udom);
 4321:     return $cachedtimes{"$courseid\0$res"};
 4322: }
 4323: 
 4324: sub set_first_access {
 4325:     my ($type,$interval)=@_;
 4326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4327:     my ($map,$id,$res)=&decode_symb($symb);
 4328:     if ($type eq 'course') {
 4329: 	$res='course';
 4330:     } elsif ($type eq 'map') {
 4331: 	$res=&symbread($map);
 4332:     } else {
 4333: 	$res=$symb;
 4334:     }
 4335:     $cachedkey='';
 4336:     my $firstaccess=&get_first_access($type,$symb,$map);
 4337:     if (!$firstaccess) {
 4338:         my $start = time;
 4339: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4340:                           $udom,$uname);
 4341:         if ($putres eq 'ok') {
 4342:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4343:                  $udom,$uname); 
 4344:             &appenv(
 4345:                      {
 4346:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4347:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4348:                      }
 4349:                   );
 4350:         }
 4351:         return $putres;
 4352:     }
 4353:     return 'already_set';
 4354: }
 4355: }
 4356: # --------------------------------------------- Set Expire Date for Spreadsheet
 4357: 
 4358: sub expirespread {
 4359:     my ($uname,$udom,$stype,$usymb)=@_;
 4360:     my $cid=$env{'request.course.id'}; 
 4361:     if ($cid) {
 4362:        my $now=time;
 4363:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4364:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4365:                             $env{'course.'.$cid.'.num'}.
 4366: 	        	    ':nohist_expirationdates:'.
 4367:                             &escape($key).'='.$now,
 4368:                             $env{'course.'.$cid.'.home'})
 4369:     }
 4370:     return 'ok';
 4371: }
 4372: 
 4373: # ----------------------------------------------------- Devalidate Spreadsheets
 4374: 
 4375: sub devalidate {
 4376:     my ($symb,$uname,$udom)=@_;
 4377:     my $cid=$env{'request.course.id'}; 
 4378:     if ($cid) {
 4379:         # delete the stored spreadsheets for
 4380:         # - the student level sheet of this user in course's homespace
 4381:         # - the assessment level sheet for this resource 
 4382:         #   for this user in user's homespace
 4383: 	# - current conditional state info
 4384: 	my $key=$uname.':'.$udom.':';
 4385:         my $status=
 4386: 	    &del('nohist_calculatedsheets',
 4387: 		 [$key.'studentcalc:'],
 4388: 		 $env{'course.'.$cid.'.domain'},
 4389: 		 $env{'course.'.$cid.'.num'})
 4390: 		.' '.
 4391: 	    &del('nohist_calculatedsheets_'.$cid,
 4392: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4393:         unless ($status eq 'ok ok') {
 4394:            &logthis('Could not devalidate spreadsheet '.
 4395:                     $uname.' at '.$udom.' for '.
 4396: 		    $symb.': '.$status);
 4397:         }
 4398: 	&delenv('user.state.'.$cid);
 4399:     }
 4400: }
 4401: 
 4402: sub get_scalar {
 4403:     my ($string,$end) = @_;
 4404:     my $value;
 4405:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4406: 	$value = $1;
 4407:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4408: 	$value = $1;
 4409:     }
 4410:     return &unescape($value);
 4411: }
 4412: 
 4413: sub array2str {
 4414:   my (@array) = @_;
 4415:   my $result=&arrayref2str(\@array);
 4416:   $result=~s/^__ARRAY_REF__//;
 4417:   $result=~s/__END_ARRAY_REF__$//;
 4418:   return $result;
 4419: }
 4420: 
 4421: sub arrayref2str {
 4422:   my ($arrayref) = @_;
 4423:   my $result='__ARRAY_REF__';
 4424:   foreach my $elem (@$arrayref) {
 4425:     if(ref($elem) eq 'ARRAY') {
 4426:       $result.=&arrayref2str($elem).'&';
 4427:     } elsif(ref($elem) eq 'HASH') {
 4428:       $result.=&hashref2str($elem).'&';
 4429:     } elsif(ref($elem)) {
 4430:       #print("Got a ref of ".(ref($elem))." skipping.");
 4431:     } else {
 4432:       $result.=&escape($elem).'&';
 4433:     }
 4434:   }
 4435:   $result=~s/\&$//;
 4436:   $result .= '__END_ARRAY_REF__';
 4437:   return $result;
 4438: }
 4439: 
 4440: sub hash2str {
 4441:   my (%hash) = @_;
 4442:   my $result=&hashref2str(\%hash);
 4443:   $result=~s/^__HASH_REF__//;
 4444:   $result=~s/__END_HASH_REF__$//;
 4445:   return $result;
 4446: }
 4447: 
 4448: sub hashref2str {
 4449:   my ($hashref)=@_;
 4450:   my $result='__HASH_REF__';
 4451:   foreach my $key (sort(keys(%$hashref))) {
 4452:     if (ref($key) eq 'ARRAY') {
 4453:       $result.=&arrayref2str($key).'=';
 4454:     } elsif (ref($key) eq 'HASH') {
 4455:       $result.=&hashref2str($key).'=';
 4456:     } elsif (ref($key)) {
 4457:       $result.='=';
 4458:       #print("Got a ref of ".(ref($key))." skipping.");
 4459:     } else {
 4460: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4461:     }
 4462: 
 4463:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4464:       $result.=&arrayref2str($hashref->{$key}).'&';
 4465:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4466:       $result.=&hashref2str($hashref->{$key}).'&';
 4467:     } elsif(ref($hashref->{$key})) {
 4468:        $result.='&';
 4469:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4470:     } else {
 4471:       $result.=&escape($hashref->{$key}).'&';
 4472:     }
 4473:   }
 4474:   $result=~s/\&$//;
 4475:   $result .= '__END_HASH_REF__';
 4476:   return $result;
 4477: }
 4478: 
 4479: sub str2hash {
 4480:     my ($string)=@_;
 4481:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4482:     return %$hash;
 4483: }
 4484: 
 4485: sub str2hashref {
 4486:   my ($string) = @_;
 4487: 
 4488:   my %hash;
 4489: 
 4490:   if($string !~ /^__HASH_REF__/) {
 4491:       if (! ($string eq '' || !defined($string))) {
 4492: 	  $hash{'error'}='Not hash reference';
 4493:       }
 4494:       return (\%hash, $string);
 4495:   }
 4496: 
 4497:   $string =~ s/^__HASH_REF__//;
 4498: 
 4499:   while($string !~ /^__END_HASH_REF__/) {
 4500:       #key
 4501:       my $key='';
 4502:       if($string =~ /^__HASH_REF__/) {
 4503:           ($key, $string)=&str2hashref($string);
 4504:           if(defined($key->{'error'})) {
 4505:               $hash{'error'}='Bad data';
 4506:               return (\%hash, $string);
 4507:           }
 4508:       } elsif($string =~ /^__ARRAY_REF__/) {
 4509:           ($key, $string)=&str2arrayref($string);
 4510:           if($key->[0] eq 'Array reference error') {
 4511:               $hash{'error'}='Bad data';
 4512:               return (\%hash, $string);
 4513:           }
 4514:       } else {
 4515:           $string =~ s/^(.*?)=//;
 4516: 	  $key=&unescape($1);
 4517:       }
 4518:       $string =~ s/^=//;
 4519: 
 4520:       #value
 4521:       my $value='';
 4522:       if($string =~ /^__HASH_REF__/) {
 4523:           ($value, $string)=&str2hashref($string);
 4524:           if(defined($value->{'error'})) {
 4525:               $hash{'error'}='Bad data';
 4526:               return (\%hash, $string);
 4527:           }
 4528:       } elsif($string =~ /^__ARRAY_REF__/) {
 4529:           ($value, $string)=&str2arrayref($string);
 4530:           if($value->[0] eq 'Array reference error') {
 4531:               $hash{'error'}='Bad data';
 4532:               return (\%hash, $string);
 4533:           }
 4534:       } else {
 4535: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4536:       }
 4537:       $string =~ s/^&//;
 4538: 
 4539:       $hash{$key}=$value;
 4540:   }
 4541: 
 4542:   $string =~ s/^__END_HASH_REF__//;
 4543: 
 4544:   return (\%hash, $string);
 4545: }
 4546: 
 4547: sub str2array {
 4548:     my ($string)=@_;
 4549:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4550:     return @$array;
 4551: }
 4552: 
 4553: sub str2arrayref {
 4554:   my ($string) = @_;
 4555:   my @array;
 4556: 
 4557:   if($string !~ /^__ARRAY_REF__/) {
 4558:       if (! ($string eq '' || !defined($string))) {
 4559: 	  $array[0]='Array reference error';
 4560:       }
 4561:       return (\@array, $string);
 4562:   }
 4563: 
 4564:   $string =~ s/^__ARRAY_REF__//;
 4565: 
 4566:   while($string !~ /^__END_ARRAY_REF__/) {
 4567:       my $value='';
 4568:       if($string =~ /^__HASH_REF__/) {
 4569:           ($value, $string)=&str2hashref($string);
 4570:           if(defined($value->{'error'})) {
 4571:               $array[0] ='Array reference error';
 4572:               return (\@array, $string);
 4573:           }
 4574:       } elsif($string =~ /^__ARRAY_REF__/) {
 4575:           ($value, $string)=&str2arrayref($string);
 4576:           if($value->[0] eq 'Array reference error') {
 4577:               $array[0] ='Array reference error';
 4578:               return (\@array, $string);
 4579:           }
 4580:       } else {
 4581: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4582:       }
 4583:       $string =~ s/^&//;
 4584: 
 4585:       push(@array, $value);
 4586:   }
 4587: 
 4588:   $string =~ s/^__END_ARRAY_REF__//;
 4589: 
 4590:   return (\@array, $string);
 4591: }
 4592: 
 4593: # -------------------------------------------------------------------Temp Store
 4594: 
 4595: sub tmpreset {
 4596:   my ($symb,$namespace,$domain,$stuname) = @_;
 4597:   if (!$symb) {
 4598:     $symb=&symbread();
 4599:     if (!$symb) { $symb= $env{'request.url'}; }
 4600:   }
 4601:   $symb=escape($symb);
 4602: 
 4603:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4604:   $namespace=~s/\//\_/g;
 4605:   $namespace=~s/\W//g;
 4606: 
 4607:   if (!$domain) { $domain=$env{'user.domain'}; }
 4608:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4609:   if ($domain eq 'public' && $stuname eq 'public') {
 4610:       $stuname=$ENV{'REMOTE_ADDR'};
 4611:   }
 4612:   my $path=LONCAPA::tempdir();
 4613:   my %hash;
 4614:   if (tie(%hash,'GDBM_File',
 4615: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4616: 	  &GDBM_WRCREAT(),0640)) {
 4617:     foreach my $key (keys(%hash)) {
 4618:       if ($key=~ /:$symb/) {
 4619: 	delete($hash{$key});
 4620:       }
 4621:     }
 4622:   }
 4623: }
 4624: 
 4625: sub tmpstore {
 4626:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4627: 
 4628:   if (!$symb) {
 4629:     $symb=&symbread();
 4630:     if (!$symb) { $symb= $env{'request.url'}; }
 4631:   }
 4632:   $symb=escape($symb);
 4633: 
 4634:   if (!$namespace) {
 4635:     # I don't think we would ever want to store this for a course.
 4636:     # it seems this will only be used if we don't have a course.
 4637:     #$namespace=$env{'request.course.id'};
 4638:     #if (!$namespace) {
 4639:       $namespace=$env{'request.state'};
 4640:     #}
 4641:   }
 4642:   $namespace=~s/\//\_/g;
 4643:   $namespace=~s/\W//g;
 4644:   if (!$domain) { $domain=$env{'user.domain'}; }
 4645:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4646:   if ($domain eq 'public' && $stuname eq 'public') {
 4647:       $stuname=$ENV{'REMOTE_ADDR'};
 4648:   }
 4649:   my $now=time;
 4650:   my %hash;
 4651:   my $path=LONCAPA::tempdir();
 4652:   if (tie(%hash,'GDBM_File',
 4653: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4654: 	  &GDBM_WRCREAT(),0640)) {
 4655:     $hash{"version:$symb"}++;
 4656:     my $version=$hash{"version:$symb"};
 4657:     my $allkeys=''; 
 4658:     foreach my $key (keys(%$storehash)) {
 4659:       $allkeys.=$key.':';
 4660:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4661:     }
 4662:     $hash{"$version:$symb:timestamp"}=$now;
 4663:     $allkeys.='timestamp';
 4664:     $hash{"$version:keys:$symb"}=$allkeys;
 4665:     if (untie(%hash)) {
 4666:       return 'ok';
 4667:     } else {
 4668:       return "error:$!";
 4669:     }
 4670:   } else {
 4671:     return "error:$!";
 4672:   }
 4673: }
 4674: 
 4675: # -----------------------------------------------------------------Temp Restore
 4676: 
 4677: sub tmprestore {
 4678:   my ($symb,$namespace,$domain,$stuname) = @_;
 4679: 
 4680:   if (!$symb) {
 4681:     $symb=&symbread();
 4682:     if (!$symb) { $symb= $env{'request.url'}; }
 4683:   }
 4684:   $symb=escape($symb);
 4685: 
 4686:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4687: 
 4688:   if (!$domain) { $domain=$env{'user.domain'}; }
 4689:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4690:   if ($domain eq 'public' && $stuname eq 'public') {
 4691:       $stuname=$ENV{'REMOTE_ADDR'};
 4692:   }
 4693:   my %returnhash;
 4694:   $namespace=~s/\//\_/g;
 4695:   $namespace=~s/\W//g;
 4696:   my %hash;
 4697:   my $path=LONCAPA::tempdir();
 4698:   if (tie(%hash,'GDBM_File',
 4699: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4700: 	  &GDBM_READER(),0640)) {
 4701:     my $version=$hash{"version:$symb"};
 4702:     $returnhash{'version'}=$version;
 4703:     my $scope;
 4704:     for ($scope=1;$scope<=$version;$scope++) {
 4705:       my $vkeys=$hash{"$scope:keys:$symb"};
 4706:       my @keys=split(/:/,$vkeys);
 4707:       my $key;
 4708:       $returnhash{"$scope:keys"}=$vkeys;
 4709:       foreach $key (@keys) {
 4710: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4711: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4712:       }
 4713:     }
 4714:     if (!(untie(%hash))) {
 4715:       return "error:$!";
 4716:     }
 4717:   } else {
 4718:     return "error:$!";
 4719:   }
 4720:   return %returnhash;
 4721: }
 4722: 
 4723: # ----------------------------------------------------------------------- Store
 4724: 
 4725: sub store {
 4726:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4727:     my $home='';
 4728: 
 4729:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4730: 
 4731:     $symb=&symbclean($symb);
 4732:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4733: 
 4734:     if (!$domain) { $domain=$env{'user.domain'}; }
 4735:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4736: 
 4737:     &devalidate($symb,$stuname,$domain);
 4738: 
 4739:     $symb=escape($symb);
 4740:     if (!$namespace) { 
 4741:        unless ($namespace=$env{'request.course.id'}) { 
 4742:           return ''; 
 4743:        } 
 4744:     }
 4745:     if (!$home) { $home=$env{'user.home'}; }
 4746: 
 4747:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4748:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4749: 
 4750:     my $namevalue='';
 4751:     foreach my $key (keys(%$storehash)) {
 4752:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4753:     }
 4754:     $namevalue=~s/\&$//;
 4755:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4756:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4757: }
 4758: 
 4759: # -------------------------------------------------------------- Critical Store
 4760: 
 4761: sub cstore {
 4762:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4763:     my $home='';
 4764: 
 4765:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4766: 
 4767:     $symb=&symbclean($symb);
 4768:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4769: 
 4770:     if (!$domain) { $domain=$env{'user.domain'}; }
 4771:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4772: 
 4773:     &devalidate($symb,$stuname,$domain);
 4774: 
 4775:     $symb=escape($symb);
 4776:     if (!$namespace) { 
 4777:        unless ($namespace=$env{'request.course.id'}) { 
 4778:           return ''; 
 4779:        } 
 4780:     }
 4781:     if (!$home) { $home=$env{'user.home'}; }
 4782: 
 4783:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4784:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4785: 
 4786:     my $namevalue='';
 4787:     foreach my $key (keys(%$storehash)) {
 4788:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4789:     }
 4790:     $namevalue=~s/\&$//;
 4791:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4792:     return critical
 4793:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4794: }
 4795: 
 4796: # --------------------------------------------------------------------- Restore
 4797: 
 4798: sub restore {
 4799:     my ($symb,$namespace,$domain,$stuname) = @_;
 4800:     my $home='';
 4801: 
 4802:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4803: 
 4804:     if (!$symb) {
 4805:         return if ($namespace eq 'courserequests');
 4806:         unless ($symb=escape(&symbread())) { return ''; }
 4807:     } else {
 4808:         unless ($namespace eq 'courserequests') {
 4809:             $symb=&escape(&symbclean($symb));
 4810:         }
 4811:     }
 4812:     if (!$namespace) { 
 4813:        unless ($namespace=$env{'request.course.id'}) { 
 4814:           return ''; 
 4815:        } 
 4816:     }
 4817:     if (!$domain) { $domain=$env{'user.domain'}; }
 4818:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4819:     if (!$home) { $home=$env{'user.home'}; }
 4820:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4821: 
 4822:     my %returnhash=();
 4823:     foreach my $line (split(/\&/,$answer)) {
 4824: 	my ($name,$value)=split(/\=/,$line);
 4825:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4826:     }
 4827:     my $version;
 4828:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4829:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4830:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4831:        }
 4832:     }
 4833:     return %returnhash;
 4834: }
 4835: 
 4836: # ---------------------------------------------------------- Course Description
 4837: #
 4838: #  
 4839: 
 4840: sub coursedescription {
 4841:     my ($courseid,$args)=@_;
 4842:     $courseid=~s/^\///;
 4843:     $courseid=~s/\_/\//g;
 4844:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4845:     my $chome=&homeserver($cnum,$cdomain);
 4846:     my $normalid=$cdomain.'_'.$cnum;
 4847:     # need to always cache even if we get errors otherwise we keep 
 4848:     # trying and trying and trying to get the course description.
 4849:     my %envhash=();
 4850:     my %returnhash=();
 4851:     
 4852:     my $expiretime=600;
 4853:     if ($env{'request.course.id'} eq $normalid) {
 4854: 	$expiretime=120;
 4855:     }
 4856: 
 4857:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4858:     if (!$args->{'freshen_cache'}
 4859: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4860: 	foreach my $key (keys(%env)) {
 4861: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4862: 	    my ($setting) = $1;
 4863: 	    $returnhash{$setting} = $env{$key};
 4864: 	}
 4865: 	return %returnhash;
 4866:     }
 4867: 
 4868:     # get the data again
 4869: 
 4870:     if (!$args->{'one_time'}) {
 4871: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4872:     }
 4873: 
 4874:     if ($chome ne 'no_host') {
 4875:        %returnhash=&dump('environment',$cdomain,$cnum);
 4876:        if (!exists($returnhash{'con_lost'})) {
 4877: 	   my $username = $env{'user.name'}; # Defult username
 4878: 	   if(defined $args->{'user'}) {
 4879: 	       $username = $args->{'user'};
 4880: 	   }
 4881:            $returnhash{'home'}= $chome;
 4882: 	   $returnhash{'domain'} = $cdomain;
 4883: 	   $returnhash{'num'} = $cnum;
 4884:            if (!defined($returnhash{'type'})) {
 4885:                $returnhash{'type'} = 'Course';
 4886:            }
 4887:            while (my ($name,$value) = each %returnhash) {
 4888:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4889:            }
 4890:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4891:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4892: 	       $username.'_'.$cdomain.'_'.$cnum;
 4893:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4894:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4895:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4896:        }
 4897:     }
 4898:     if (!$args->{'one_time'}) {
 4899: 	&appenv(\%envhash);
 4900:     }
 4901:     return %returnhash;
 4902: }
 4903: 
 4904: sub update_released_required {
 4905:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4906:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4907:         $cid = $env{'request.course.id'};
 4908:         $cdom = $env{'course.'.$cid.'.domain'};
 4909:         $cnum = $env{'course.'.$cid.'.num'};
 4910:         $chome = $env{'course.'.$cid.'.home'};
 4911:     }
 4912:     if ($needsrelease) {
 4913:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4914:         my $needsupdate;
 4915:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4916:             $needsupdate = 1;
 4917:         } else {
 4918:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4919:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4920:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4921:                 $needsupdate = 1;
 4922:             }
 4923:         }
 4924:         if ($needsupdate) {
 4925:             my %needshash = (
 4926:                              'internal.releaserequired' => $needsrelease,
 4927:                             );
 4928:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4929:             if ($putresult eq 'ok') {
 4930:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4931:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4932:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4933:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4934:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4935:                 }
 4936:             }
 4937:         }
 4938:     }
 4939:     return;
 4940: }
 4941: 
 4942: # -------------------------------------------------See if a user is privileged
 4943: 
 4944: sub privileged {
 4945:     my ($username,$domain,$possdomains,$possroles)=@_;
 4946:     my $now = time;
 4947:     my $roles;
 4948:     if (ref($possroles) eq 'ARRAY') {
 4949:         $roles = $possroles; 
 4950:     } else {
 4951:         $roles = ['dc','su'];
 4952:     }
 4953:     if (ref($possdomains) eq 'ARRAY') {
 4954:         my %privileged = &privileged_by_domain($possdomains,$roles);
 4955:         foreach my $dom (@{$possdomains}) {
 4956:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 4957:                 (ref($privileged{$dom}) eq 'HASH')) {
 4958:                 foreach my $role (@{$roles}) {
 4959:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 4960:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 4961:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 4962:                             return 1 unless (($end && $end < $now) ||
 4963:                                              ($start && $start > $now));
 4964:                         }
 4965:                     }
 4966:                 }
 4967:             }
 4968:         }
 4969:     } else {
 4970:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4971:         my $now = time;
 4972: 
 4973:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4974:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4975:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 4976:                 return 1 unless ($tend && $tend < $now) 
 4977:                         or ($tstart && $tstart > $now);
 4978:             }
 4979:         }
 4980:     }
 4981:     return 0;
 4982: }
 4983: 
 4984: sub privileged_by_domain {
 4985:     my ($domains,$roles) = @_;
 4986:     my %privileged = ();
 4987:     my $cachetime = 60*60*24;
 4988:     my $now = time;
 4989:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 4990:         return %privileged;
 4991:     }
 4992:     foreach my $dom (@{$domains}) {
 4993:         next if (ref($privileged{$dom}) eq 'HASH');
 4994:         my $needroles;
 4995:         foreach my $role (@{$roles}) {
 4996:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 4997:             if (defined($cached)) {
 4998:                 if (ref($result) eq 'HASH') {
 4999:                     $privileged{$dom}{$role} = $result;
 5000:                 }
 5001:             } else {
 5002:                 $needroles = 1;
 5003:             }
 5004:         }
 5005:         if ($needroles) {
 5006:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5007:             $privileged{$dom} = {};
 5008:             foreach my $server (keys(%dompersonnel)) {
 5009:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5010:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5011:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5012:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5013:                         next if ($end && $end < $now);
 5014:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5015:                             $dompersonnel{$server}{$item};
 5016:                     }
 5017:                 }
 5018:             }
 5019:             if (ref($privileged{$dom}) eq 'HASH') {
 5020:                 foreach my $role (@{$roles}) {
 5021:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5022:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5023:                     } else {
 5024:                         my %hash = ();
 5025:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5026:                     }
 5027:                 }
 5028:             }
 5029:         }
 5030:     }
 5031:     return %privileged;
 5032: }
 5033: 
 5034: # -------------------------------------------------------- Get user privileges
 5035: 
 5036: sub rolesinit {
 5037:     my ($domain, $username) = @_;
 5038:     my %userroles = ('user.login.time' => time);
 5039:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5040: 
 5041:     # firstaccess and timerinterval are related to timed maps/resources. 
 5042:     # also, blocking can be triggered by an activating timer
 5043:     # it's saved in the user's %env.
 5044:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5045:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5046:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5047:         %timerintchk, %timerintenv);
 5048: 
 5049:     foreach my $key (keys(%firstaccess)) {
 5050:         my ($cid, $rest) = split(/\0/, $key);
 5051:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5052:     }
 5053: 
 5054:     foreach my $key (keys(%timerinterval)) {
 5055:         my ($cid,$rest) = split(/\0/,$key);
 5056:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5057:     }
 5058: 
 5059:     my %allroles=();
 5060:     my %allgroups=();
 5061: 
 5062:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5063:         my $role = $rolesdump{$area};
 5064:         $area =~ s/\_\w\w$//;
 5065: 
 5066:         my ($trole, $tend, $tstart, $group_privs);
 5067: 
 5068:         if ($role =~ /^cr/) {
 5069:         # Custom role, defined by a user 
 5070:         # e.g., user.role.cr/msu/smith/mynewrole
 5071:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5072:                 $trole = $1;
 5073:                 ($tend, $tstart) = split('_', $2);
 5074:             } else {
 5075:                 $trole = $role;
 5076:             }
 5077:         } elsif ($role =~ m|^gr/|) {
 5078:         # Role of member in a group, defined within a course/community
 5079:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5080:             ($trole, $tend, $tstart) = split(/_/, $role);
 5081:             next if $tstart eq '-1';
 5082:             ($trole, $group_privs) = split(/\//, $trole);
 5083:             $group_privs = &unescape($group_privs);
 5084:         } else {
 5085:         # Just a normal role, defined in roles.tab
 5086:             ($trole, $tend, $tstart) = split(/_/,$role);
 5087:         }
 5088: 
 5089:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5090:                  $username);
 5091:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5092: 
 5093:         # role expired or not available yet?
 5094:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5095:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5096: 
 5097:         next if $area eq '' or $trole eq '';
 5098: 
 5099:         my $spec = "$trole.$area";
 5100:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5101: 
 5102:         if ($trole =~ /^cr\//) {
 5103:         # Custom role, defined by a user
 5104:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5105:         } elsif ($trole eq 'gr') {
 5106:         # Role of a member in a group, defined within a course/community
 5107:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5108:             next;
 5109:         } else {
 5110:         # Normal role, defined in roles.tab
 5111:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5112:         }
 5113: 
 5114:         my $cid = $tdomain.'_'.$trest;
 5115:         unless ($firstaccchk{$cid}) {
 5116:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5117:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5118:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5119:                         $coursetimerstarts{$cid}{$item}; 
 5120:                 }
 5121:             }
 5122:             $firstaccchk{$cid} = 1;
 5123:         }
 5124:         unless ($timerintchk{$cid}) {
 5125:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5126:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5127:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5128:                        $coursetimerintervals{$cid}{$item};
 5129:                 }
 5130:             }
 5131:             $timerintchk{$cid} = 1;
 5132:         }
 5133:     }
 5134: 
 5135:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5136:         \%allroles, \%allgroups);
 5137:     $env{'user.adv'} = $userroles{'user.adv'};
 5138: 
 5139:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5140: }
 5141: 
 5142: sub set_arearole {
 5143:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5144:     unless ($nolog) {
 5145: # log the associated role with the area
 5146:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5147:     }
 5148:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5149: }
 5150: 
 5151: sub custom_roleprivs {
 5152:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5153:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5154:     my $homsvr=homeserver($rauthor,$rdomain);
 5155:     if (&hostname($homsvr) ne '') {
 5156:         my ($rdummy,$roledef)=
 5157:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5158:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5159:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5160:             if (defined($syspriv)) {
 5161:                 if ($trest =~ /^$match_community$/) {
 5162:                     $syspriv =~ s/bre\&S//; 
 5163:                 }
 5164:                 $$allroles{'cm./'}.=':'.$syspriv;
 5165:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5166:             }
 5167:             if ($tdomain ne '') {
 5168:                 if (defined($dompriv)) {
 5169:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5170:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5171:                 }
 5172:                 if (($trest ne '') && (defined($coursepriv))) {
 5173:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5174:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5175:                 }
 5176:             }
 5177:         }
 5178:     }
 5179: }
 5180: 
 5181: sub group_roleprivs {
 5182:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5183:     my $access = 1;
 5184:     my $now = time;
 5185:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5186:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5187:     if ($access) {
 5188:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5189:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5190:     }
 5191: }
 5192: 
 5193: sub standard_roleprivs {
 5194:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5195:     if (defined($pr{$trole.':s'})) {
 5196:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5197:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5198:     }
 5199:     if ($tdomain ne '') {
 5200:         if (defined($pr{$trole.':d'})) {
 5201:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5202:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5203:         }
 5204:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5205:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5206:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5207:         }
 5208:     }
 5209: }
 5210: 
 5211: sub set_userprivs {
 5212:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5213:     my $author=0;
 5214:     my $adv=0;
 5215:     my %grouproles = ();
 5216:     if (keys(%{$allgroups}) > 0) {
 5217:         my @groupkeys; 
 5218:         foreach my $role (keys(%{$allroles})) {
 5219:             push(@groupkeys,$role);
 5220:         }
 5221:         if (ref($groups_roles) eq 'HASH') {
 5222:             foreach my $key (keys(%{$groups_roles})) {
 5223:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5224:                     push(@groupkeys,$key);
 5225:                 }
 5226:             }
 5227:         }
 5228:         if (@groupkeys > 0) {
 5229:             foreach my $role (@groupkeys) {
 5230:                 my ($trole,$area,$sec,$extendedarea);
 5231:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5232:                     $trole = $1;
 5233:                     $area = $2;
 5234:                     $sec = $3;
 5235:                     $extendedarea = $area.$sec;
 5236:                     if (exists($$allgroups{$area})) {
 5237:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5238:                             my $spec = $trole.'.'.$extendedarea;
 5239:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5240:                                                 $$allgroups{$area}{$group};
 5241:                         }
 5242:                     }
 5243:                 }
 5244:             }
 5245:         }
 5246:     }
 5247:     foreach my $group (keys(%grouproles)) {
 5248:         $$allroles{$group} = $grouproles{$group};
 5249:     }
 5250:     foreach my $role (keys(%{$allroles})) {
 5251:         my %thesepriv;
 5252:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5253:         foreach my $item (split(/:/,$$allroles{$role})) {
 5254:             if ($item ne '') {
 5255:                 my ($privilege,$restrictions)=split(/&/,$item);
 5256:                 if ($restrictions eq '') {
 5257:                     $thesepriv{$privilege}='F';
 5258:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5259:                     $thesepriv{$privilege}.=$restrictions;
 5260:                 }
 5261:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5262:             }
 5263:         }
 5264:         my $thesestr='';
 5265:         foreach my $priv (sort(keys(%thesepriv))) {
 5266: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5267: 	}
 5268:         $userroles->{'user.priv.'.$role} = $thesestr;
 5269:     }
 5270:     return ($author,$adv);
 5271: }
 5272: 
 5273: sub role_status {
 5274:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5275:     my @pwhere = ();
 5276:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5277:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5278:         unless (!defined($$role) || $$role eq '') {
 5279:             $$where=join('.',@pwhere);
 5280:             $$trolecode=$$role.'.'.$$where;
 5281:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5282:             $$tstatus='is';
 5283:             if ($$tstart && $$tstart>$update) {
 5284:                 $$tstatus='future';
 5285:                 if ($$tstart<$now) {
 5286:                     if ($$tstart && $$tstart>$refresh) {
 5287:                         if (($$where ne '') && ($$role ne '')) {
 5288:                             my (%allroles,%allgroups,$group_privs,
 5289:                                 %groups_roles,@rolecodes);
 5290:                             my %userroles = (
 5291:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5292:                             );
 5293:                             @rolecodes = ('cm'); 
 5294:                             my $spec=$$role.'.'.$$where;
 5295:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5296:                             if ($$role =~ /^cr\//) {
 5297:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5298:                                 push(@rolecodes,'cr');
 5299:                             } elsif ($$role eq 'gr') {
 5300:                                 push(@rolecodes,$$role);
 5301:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5302:                                                     $env{'user.name'});
 5303:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5304:                                 (undef,my $group_privs) = split(/\//,$trole);
 5305:                                 $group_privs = &unescape($group_privs);
 5306:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5307:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5308:                                 &get_groups_roles($tdomain,$trest,
 5309:                                                   \%course_roles,\@rolecodes,
 5310:                                                   \%groups_roles);
 5311:                             } else {
 5312:                                 push(@rolecodes,$$role);
 5313:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5314:                             }
 5315:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5316:                             &appenv(\%userroles,\@rolecodes);
 5317:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5318:                         }
 5319:                     }
 5320:                     $$tstatus = 'is';
 5321:                 }
 5322:             }
 5323:             if ($$tend) {
 5324:                 if ($$tend<$update) {
 5325:                     $$tstatus='expired';
 5326:                 } elsif ($$tend<$now) {
 5327:                     $$tstatus='will_not';
 5328:                 }
 5329:             }
 5330:         }
 5331:     }
 5332: }
 5333: 
 5334: sub get_groups_roles {
 5335:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5336:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5337:                   (ref($rolecodes) eq 'ARRAY') && 
 5338:                   (ref($groups_roles) eq 'HASH')); 
 5339:     if (keys(%{$cdom_courseroles}) > 0) {
 5340:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5341:         if ($cdom ne '' && $cnum ne '') {
 5342:             foreach my $key (keys(%{$cdom_courseroles})) {
 5343:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5344:                     my $crsrole = $1;
 5345:                     my $crssec = $2;
 5346:                     if ($crsrole =~ /^cr/) {
 5347:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5348:                             push(@{$rolecodes},'cr');
 5349:                         }
 5350:                     } else {
 5351:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5352:                             push(@{$rolecodes},$crsrole);
 5353:                         }
 5354:                     }
 5355:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5356:                     if ($crssec ne '') {
 5357:                         $rolekey .= "/$crssec";
 5358:                     }
 5359:                     $rolekey .= './';
 5360:                     $groups_roles->{$rolekey} = $rolecodes;
 5361:                 }
 5362:             }
 5363:         }
 5364:     }
 5365:     return;
 5366: }
 5367: 
 5368: sub delete_env_groupprivs {
 5369:     my ($where,$courseroles,$possroles) = @_;
 5370:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5371:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5372:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5373:         %{$courseroles->{$udom}} =
 5374:             &get_my_roles('','','userroles',['active'],
 5375:                           $possroles,[$udom],1);
 5376:     }
 5377:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5378:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5379:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5380:             my $area = '/'.$cdom.'/'.$cnum;
 5381:             my $privkey = "user.priv.$crsrole.$area";
 5382:             if ($crssec ne '') {
 5383:                 $privkey .= '/'.$crssec;
 5384:             }
 5385:             $privkey .= ".$area/$group";
 5386:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5387:         }
 5388:     }
 5389:     return;
 5390: }
 5391: 
 5392: sub check_adhoc_privs {
 5393:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5394:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5395:     my $setprivs;
 5396:     if ($env{$cckey}) {
 5397:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5398:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5399:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5400:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5401:             $setprivs = 1;
 5402:         }
 5403:     } else {
 5404:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5405:         $setprivs = 1;
 5406:     }
 5407:     return $setprivs;
 5408: }
 5409: 
 5410: sub set_adhoc_privileges {
 5411: # role can be cc or ca
 5412:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5413:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5414:     my $spec = $role.'.'.$area;
 5415:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5416:                                   $env{'user.name'},1);
 5417:     my %ccrole = ();
 5418:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5419:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5420:     &appenv(\%userroles,[$role,'cm']);
 5421:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5422:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5423:         &appenv( {'request.role'        => $spec,
 5424:                   'request.role.domain' => $dcdom,
 5425:                   'request.course.sec'  => ''
 5426:                  }
 5427:                );
 5428:         my $tadv=0;
 5429:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5430:         &appenv({'request.role.adv'    => $tadv});
 5431:     }
 5432: }
 5433: 
 5434: # --------------------------------------------------------------- get interface
 5435: 
 5436: sub get {
 5437:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5438:    my $items='';
 5439:    foreach my $item (@$storearr) {
 5440:        $items.=&escape($item).'&';
 5441:    }
 5442:    $items=~s/\&$//;
 5443:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5444:    if (!$uname) { $uname=$env{'user.name'}; }
 5445:    my $uhome=&homeserver($uname,$udomain);
 5446: 
 5447:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5448:    my @pairs=split(/\&/,$rep);
 5449:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5450:      return @pairs;
 5451:    }
 5452:    my %returnhash=();
 5453:    my $i=0;
 5454:    foreach my $item (@$storearr) {
 5455:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5456:       $i++;
 5457:    }
 5458:    return %returnhash;
 5459: }
 5460: 
 5461: # --------------------------------------------------------------- del interface
 5462: 
 5463: sub del {
 5464:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5465:    my $items='';
 5466:    foreach my $item (@$storearr) {
 5467:        $items.=&escape($item).'&';
 5468:    }
 5469: 
 5470:    $items=~s/\&$//;
 5471:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5472:    if (!$uname) { $uname=$env{'user.name'}; }
 5473:    my $uhome=&homeserver($uname,$udomain);
 5474:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5475: }
 5476: 
 5477: # -------------------------------------------------------------- dump interface
 5478: 
 5479: sub unserialize {
 5480:     my ($rep, $escapedkeys) = @_;
 5481: 
 5482:     return {} if $rep =~ /^error/;
 5483: 
 5484:     my %returnhash=();
 5485: 	foreach my $item (split /\&/, $rep) {
 5486: 	    my ($key, $value) = split(/=/, $item, 2);
 5487: 	    $key = unescape($key) unless $escapedkeys;
 5488: 	    next if $key =~ /^error: 2 /;
 5489: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5490: 	}
 5491:     #return %returnhash;
 5492:     return \%returnhash;
 5493: }        
 5494: 
 5495: # see Lond::dump_with_regexp
 5496: # if $escapedkeys hash keys won't get unescaped.
 5497: sub dump {
 5498:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5499:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5500:     if (!$uname) { $uname=$env{'user.name'}; }
 5501:     my $uhome=&homeserver($uname,$udomain);
 5502: 
 5503:     my $reply;
 5504:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5505:         # user is hosted on this machine
 5506:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5507:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5508:         return %{unserialize($reply, $escapedkeys)};
 5509:     }
 5510:     if ($regexp) {
 5511: 	$regexp=&escape($regexp);
 5512:     } else {
 5513: 	$regexp='.';
 5514:     }
 5515:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5516:     my @pairs=split(/\&/,$rep);
 5517:     my %returnhash=();
 5518:     if (!($rep =~ /^error/ )) {
 5519: 	foreach my $item (@pairs) {
 5520: 	    my ($key,$value)=split(/=/,$item,2);
 5521:         $key = unescape($key) unless $escapedkeys;
 5522:         #$key = &unescape($key);
 5523: 	    next if ($key =~ /^error: 2 /);
 5524: 	    $returnhash{$key}=&thaw_unescape($value);
 5525: 	}
 5526:     }
 5527:     return %returnhash;
 5528: }
 5529: 
 5530: 
 5531: # --------------------------------------------------------- dumpstore interface
 5532: 
 5533: sub dumpstore {
 5534:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5535:    # same as dump but keys must be escaped. They may contain colon separated
 5536:    # lists of values that may themself contain colons (e.g. symbs).
 5537:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5538: }
 5539: 
 5540: # -------------------------------------------------------------- keys interface
 5541: 
 5542: sub getkeys {
 5543:    my ($namespace,$udomain,$uname)=@_;
 5544:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5545:    if (!$uname) { $uname=$env{'user.name'}; }
 5546:    my $uhome=&homeserver($uname,$udomain);
 5547:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5548:    my @keyarray=();
 5549:    foreach my $key (split(/\&/,$rep)) {
 5550:       next if ($key =~ /^error: 2 /);
 5551:       push(@keyarray,&unescape($key));
 5552:    }
 5553:    return @keyarray;
 5554: }
 5555: 
 5556: # --------------------------------------------------------------- currentdump
 5557: sub currentdump {
 5558:    my ($courseid,$sdom,$sname)=@_;
 5559:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5560:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5561:    $sname    = $env{'user.name'}         if (! defined($sname));
 5562:    my $uhome = &homeserver($sname,$sdom);
 5563:    my $rep;
 5564: 
 5565:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5566:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5567:                    $courseid)));
 5568:    } else {
 5569:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5570:    }
 5571: 
 5572:    return if ($rep =~ /^(error:|no_such_host)/);
 5573:    #
 5574:    my %returnhash=();
 5575:    #
 5576:    if ($rep eq "unknown_cmd") { 
 5577:        # an old lond will not know currentdump
 5578:        # Do a dump and make it look like a currentdump
 5579:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5580:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5581:        my %hash = @tmp;
 5582:        @tmp=();
 5583:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5584:    } else {
 5585:        my @pairs=split(/\&/,$rep);
 5586:        foreach my $pair (@pairs) {
 5587:            my ($key,$value)=split(/=/,$pair,2);
 5588:            my ($symb,$param) = split(/:/,$key);
 5589:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5590:                                                         &thaw_unescape($value);
 5591:        }
 5592:    }
 5593:    return %returnhash;
 5594: }
 5595: 
 5596: sub convert_dump_to_currentdump{
 5597:     my %hash = %{shift()};
 5598:     my %returnhash;
 5599:     # Code ripped from lond, essentially.  The only difference
 5600:     # here is the unescaping done by lonnet::dump().  Conceivably
 5601:     # we might run in to problems with parameter names =~ /^v\./
 5602:     while (my ($key,$value) = each(%hash)) {
 5603:         my ($v,$symb,$param) = split(/:/,$key);
 5604: 	$symb  = &unescape($symb);
 5605: 	$param = &unescape($param);
 5606:         next if ($v eq 'version' || $symb eq 'keys');
 5607:         next if (exists($returnhash{$symb}) &&
 5608:                  exists($returnhash{$symb}->{$param}) &&
 5609:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5610:         $returnhash{$symb}->{$param}=$value;
 5611:         $returnhash{$symb}->{'v.'.$param}=$v;
 5612:     }
 5613:     #
 5614:     # Remove all of the keys in the hashes which keep track of
 5615:     # the version of the parameter.
 5616:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5617:         # use a foreach because we are going to delete from the hash.
 5618:         foreach my $key (keys(%$param_hash)) {
 5619:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5620:         }
 5621:     }
 5622:     return \%returnhash;
 5623: }
 5624: 
 5625: # ------------------------------------------------------ critical inc interface
 5626: 
 5627: sub cinc {
 5628:     return &inc(@_,'critical');
 5629: }
 5630: 
 5631: # --------------------------------------------------------------- inc interface
 5632: 
 5633: sub inc {
 5634:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5635:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5636:     if (!$uname) { $uname=$env{'user.name'}; }
 5637:     my $uhome=&homeserver($uname,$udomain);
 5638:     my $items='';
 5639:     if (! ref($store)) {
 5640:         # got a single value, so use that instead
 5641:         $items = &escape($store).'=&';
 5642:     } elsif (ref($store) eq 'SCALAR') {
 5643:         $items = &escape($$store).'=&';        
 5644:     } elsif (ref($store) eq 'ARRAY') {
 5645:         $items = join('=&',map {&escape($_);} @{$store});
 5646:     } elsif (ref($store) eq 'HASH') {
 5647:         while (my($key,$value) = each(%{$store})) {
 5648:             $items.= &escape($key).'='.&escape($value).'&';
 5649:         }
 5650:     }
 5651:     $items=~s/\&$//;
 5652:     if ($critical) {
 5653: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5654:     } else {
 5655: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5656:     }
 5657: }
 5658: 
 5659: # --------------------------------------------------------------- put interface
 5660: 
 5661: sub put {
 5662:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5663:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5664:    if (!$uname) { $uname=$env{'user.name'}; }
 5665:    my $uhome=&homeserver($uname,$udomain);
 5666:    my $items='';
 5667:    foreach my $item (keys(%$storehash)) {
 5668:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5669:    }
 5670:    $items=~s/\&$//;
 5671:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5672: }
 5673: 
 5674: # ------------------------------------------------------------ newput interface
 5675: 
 5676: sub newput {
 5677:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5678:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5679:    if (!$uname) { $uname=$env{'user.name'}; }
 5680:    my $uhome=&homeserver($uname,$udomain);
 5681:    my $items='';
 5682:    foreach my $key (keys(%$storehash)) {
 5683:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5684:    }
 5685:    $items=~s/\&$//;
 5686:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5687: }
 5688: 
 5689: # ---------------------------------------------------------  putstore interface
 5690: 
 5691: sub putstore {
 5692:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5693:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5694:    if (!$uname) { $uname=$env{'user.name'}; }
 5695:    my $uhome=&homeserver($uname,$udomain);
 5696:    my $items='';
 5697:    foreach my $key (keys(%$storehash)) {
 5698:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5699:    }
 5700:    $items=~s/\&$//;
 5701:    my $esc_symb=&escape($symb);
 5702:    my $esc_v=&escape($version);
 5703:    my $reply =
 5704:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5705: 	      $uhome);
 5706:    if ($reply eq 'unknown_cmd') {
 5707:        # gfall back to way things use to be done
 5708:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5709: 			    $uname);
 5710:    }
 5711:    return $reply;
 5712: }
 5713: 
 5714: sub old_putstore {
 5715:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5716:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5717:     if (!$uname) { $uname=$env{'user.name'}; }
 5718:     my $uhome=&homeserver($uname,$udomain);
 5719:     my %newstorehash;
 5720:     foreach my $item (keys(%$storehash)) {
 5721: 	my $key = $version.':'.&escape($symb).':'.$item;
 5722: 	$newstorehash{$key} = $storehash->{$item};
 5723:     }
 5724:     my $items='';
 5725:     my %allitems = ();
 5726:     foreach my $item (keys(%newstorehash)) {
 5727: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5728: 	    my $key = $1.':keys:'.$2;
 5729: 	    $allitems{$key} .= $3.':';
 5730: 	}
 5731: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5732:     }
 5733:     foreach my $item (keys(%allitems)) {
 5734: 	$allitems{$item} =~ s/\:$//;
 5735: 	$items.= $item.'='.$allitems{$item}.'&';
 5736:     }
 5737:     $items=~s/\&$//;
 5738:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5739: }
 5740: 
 5741: # ------------------------------------------------------ critical put interface
 5742: 
 5743: sub cput {
 5744:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5745:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5746:    if (!$uname) { $uname=$env{'user.name'}; }
 5747:    my $uhome=&homeserver($uname,$udomain);
 5748:    my $items='';
 5749:    foreach my $item (keys(%$storehash)) {
 5750:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5751:    }
 5752:    $items=~s/\&$//;
 5753:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5754: }
 5755: 
 5756: # -------------------------------------------------------------- eget interface
 5757: 
 5758: sub eget {
 5759:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5760:    my $items='';
 5761:    foreach my $item (@$storearr) {
 5762:        $items.=&escape($item).'&';
 5763:    }
 5764:    $items=~s/\&$//;
 5765:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5766:    if (!$uname) { $uname=$env{'user.name'}; }
 5767:    my $uhome=&homeserver($uname,$udomain);
 5768:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5769:    my @pairs=split(/\&/,$rep);
 5770:    my %returnhash=();
 5771:    my $i=0;
 5772:    foreach my $item (@$storearr) {
 5773:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5774:       $i++;
 5775:    }
 5776:    return %returnhash;
 5777: }
 5778: 
 5779: # ------------------------------------------------------------ tmpput interface
 5780: sub tmpput {
 5781:     my ($storehash,$server,$context)=@_;
 5782:     my $items='';
 5783:     foreach my $item (keys(%$storehash)) {
 5784: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5785:     }
 5786:     $items=~s/\&$//;
 5787:     if (defined($context)) {
 5788:         $items .= ':'.&escape($context);
 5789:     }
 5790:     return &reply("tmpput:$items",$server);
 5791: }
 5792: 
 5793: # ------------------------------------------------------------ tmpget interface
 5794: sub tmpget {
 5795:     my ($token,$server)=@_;
 5796:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5797:     my $rep=&reply("tmpget:$token",$server);
 5798:     my %returnhash;
 5799:     foreach my $item (split(/\&/,$rep)) {
 5800: 	my ($key,$value)=split(/=/,$item);
 5801:         next if ($key =~ /^error: 2 /);
 5802: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5803:     }
 5804:     return %returnhash;
 5805: }
 5806: 
 5807: # ------------------------------------------------------------ tmpdel interface
 5808: sub tmpdel {
 5809:     my ($token,$server)=@_;
 5810:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5811:     return &reply("tmpdel:$token",$server);
 5812: }
 5813: 
 5814: # ------------------------------------------------------------ get_timebased_id 
 5815: 
 5816: sub get_timebased_id {
 5817:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5818:         $maxtries) = @_;
 5819:     my ($newid,$error,$dellock);
 5820:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5821:         return ('','ok','invalid call to get suffix');
 5822:     }
 5823: 
 5824: # set defaults for any optional args for which values were not supplied
 5825:     if ($who eq '') {
 5826:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5827:     }
 5828:     if (!$locktries) {
 5829:         $locktries = 3;
 5830:     }
 5831:     if (!$maxtries) {
 5832:         $maxtries = 10;
 5833:     }
 5834:     
 5835:     if (($cdom eq '') || ($cnum eq '')) {
 5836:         if ($env{'request.course.id'}) {
 5837:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5838:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5839:         }
 5840:         if (($cdom eq '') || ($cnum eq '')) {
 5841:             return ('','ok','call to get suffix not in course context');
 5842:         }
 5843:     }
 5844: 
 5845: # construct locking item
 5846:     my $lockhash = {
 5847:                       $prefix."\0".'locked_'.$keyid => $who,
 5848:                    };
 5849:     my $tries = 0;
 5850: 
 5851: # attempt to get lock on nohist_$namespace file
 5852:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5853:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5854:         $tries ++;
 5855:         sleep 1;
 5856:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5857:     }
 5858: 
 5859: # attempt to get unique identifier, based on current timestamp
 5860:     if ($gotlock eq 'ok') {
 5861:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5862:         my $id = time;
 5863:         $newid = $id;
 5864:         my $idtries = 0;
 5865:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5866:             if ($idtype eq 'concat') {
 5867:                 $newid = $id.$idtries;
 5868:             } else {
 5869:                 $newid ++;
 5870:             }
 5871:             $idtries ++;
 5872:         }
 5873:         if (!exists($inuse{$prefix."\0".$newid})) {
 5874:             my %new_item =  (
 5875:                               $prefix."\0".$newid => $who,
 5876:                             );
 5877:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5878:                                                  $cdom,$cnum);
 5879:             if ($putresult ne 'ok') {
 5880:                 undef($newid);
 5881:                 $error = 'error saving new item: '.$putresult;
 5882:             }
 5883:         } else {
 5884:              $error = ('error: no unique suffix available for the new item ');
 5885:         }
 5886: #  remove lock
 5887:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5888:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5889:     } else {
 5890:         $error = "error: could not obtain lockfile\n";
 5891:         $dellock = 'ok';
 5892:     }
 5893:     return ($newid,$dellock,$error);
 5894: }
 5895: 
 5896: # -------------------------------------------------- portfolio access checking
 5897: 
 5898: sub portfolio_access {
 5899:     my ($requrl) = @_;
 5900:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5901:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5902:     if ($result) {
 5903:         my %setters;
 5904:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5905:             my ($startblock,$endblock) =
 5906:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5907:             if ($startblock && $endblock) {
 5908:                 return 'B';
 5909:             }
 5910:         } else {
 5911:             my ($startblock,$endblock) =
 5912:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5913:             if ($startblock && $endblock) {
 5914:                 return 'B';
 5915:             }
 5916:         }
 5917:     }
 5918:     if ($result eq 'ok') {
 5919:        return 'F';
 5920:     } elsif ($result =~ /^[^:]+:guest_/) {
 5921:        return 'A';
 5922:     }
 5923:     return '';
 5924: }
 5925: 
 5926: sub get_portfolio_access {
 5927:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5928: 
 5929:     if (!ref($access_hash)) {
 5930: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5931: 	my %access_controls = &get_access_controls($current_perms,$group,
 5932: 						   $file_name);
 5933: 	$access_hash = $access_controls{$file_name};
 5934:     }
 5935: 
 5936:     my ($public,$guest,@domains,@users,@courses,@groups);
 5937:     my $now = time;
 5938:     if (ref($access_hash) eq 'HASH') {
 5939:         foreach my $key (keys(%{$access_hash})) {
 5940:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5941:             if ($start > $now) {
 5942:                 next;
 5943:             }
 5944:             if ($end && $end<$now) {
 5945:                 next;
 5946:             }
 5947:             if ($scope eq 'public') {
 5948:                 $public = $key;
 5949:                 last;
 5950:             } elsif ($scope eq 'guest') {
 5951:                 $guest = $key;
 5952:             } elsif ($scope eq 'domains') {
 5953:                 push(@domains,$key);
 5954:             } elsif ($scope eq 'users') {
 5955:                 push(@users,$key);
 5956:             } elsif ($scope eq 'course') {
 5957:                 push(@courses,$key);
 5958:             } elsif ($scope eq 'group') {
 5959:                 push(@groups,$key);
 5960:             }
 5961:         }
 5962:         if ($public) {
 5963:             return 'ok';
 5964:         }
 5965:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5966:             if ($guest) {
 5967:                 return $guest;
 5968:             }
 5969:         } else {
 5970:             if (@domains > 0) {
 5971:                 foreach my $domkey (@domains) {
 5972:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5973:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5974:                             return 'ok';
 5975:                         }
 5976:                     }
 5977:                 }
 5978:             }
 5979:             if (@users > 0) {
 5980:                 foreach my $userkey (@users) {
 5981:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5982:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5983:                             if (ref($item) eq 'HASH') {
 5984:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5985:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5986:                                     return 'ok';
 5987:                                 }
 5988:                             }
 5989:                         }
 5990:                     } 
 5991:                 }
 5992:             }
 5993:             my %roleshash;
 5994:             my @courses_and_groups = @courses;
 5995:             push(@courses_and_groups,@groups); 
 5996:             if (@courses_and_groups > 0) {
 5997:                 my (%allgroups,%allroles); 
 5998:                 my ($start,$end,$role,$sec,$group);
 5999:                 foreach my $envkey (%env) {
 6000:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6001:                         my $cid = $2.'_'.$3; 
 6002:                         if ($1 eq 'gr') {
 6003:                             $group = $4;
 6004:                             $allgroups{$cid}{$group} = $env{$envkey};
 6005:                         } else {
 6006:                             if ($4 eq '') {
 6007:                                 $sec = 'none';
 6008:                             } else {
 6009:                                 $sec = $4;
 6010:                             }
 6011:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6012:                         }
 6013:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6014:                         my $cid = $2.'_'.$3;
 6015:                         if ($4 eq '') {
 6016:                             $sec = 'none';
 6017:                         } else {
 6018:                             $sec = $4;
 6019:                         }
 6020:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6021:                     }
 6022:                 }
 6023:                 if (keys(%allroles) == 0) {
 6024:                     return;
 6025:                 }
 6026:                 foreach my $key (@courses_and_groups) {
 6027:                     my %content = %{$$access_hash{$key}};
 6028:                     my $cnum = $content{'number'};
 6029:                     my $cdom = $content{'domain'};
 6030:                     my $cid = $cdom.'_'.$cnum;
 6031:                     if (!exists($allroles{$cid})) {
 6032:                         next;
 6033:                     }    
 6034:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6035:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6036:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6037:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6038:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6039:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6040:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6041:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6042:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6043:                                         if (grep/^all$/,@sections) {
 6044:                                             return 'ok';
 6045:                                         } else {
 6046:                                             if (grep/^$sec$/,@sections) {
 6047:                                                 return 'ok';
 6048:                                             }
 6049:                                         }
 6050:                                     }
 6051:                                 }
 6052:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6053:                                     if (grep/^none$/,@groups) {
 6054:                                         return 'ok';
 6055:                                     }
 6056:                                 } else {
 6057:                                     if (grep/^all$/,@groups) {
 6058:                                         return 'ok';
 6059:                                     } 
 6060:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6061:                                         if (grep/^$group$/,@groups) {
 6062:                                             return 'ok';
 6063:                                         }
 6064:                                     }
 6065:                                 } 
 6066:                             }
 6067:                         }
 6068:                     }
 6069:                 }
 6070:             }
 6071:             if ($guest) {
 6072:                 return $guest;
 6073:             }
 6074:         }
 6075:     }
 6076:     return;
 6077: }
 6078: 
 6079: sub course_group_datechecker {
 6080:     my ($dates,$now,$status) = @_;
 6081:     my ($start,$end) = split(/\./,$dates);
 6082:     if (!$start && !$end) {
 6083:         return 'ok';
 6084:     }
 6085:     if (grep/^active$/,@{$status}) {
 6086:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6087:             return 'ok';
 6088:         }
 6089:     }
 6090:     if (grep/^previous$/,@{$status}) {
 6091:         if ($end > $now ) {
 6092:             return 'ok';
 6093:         }
 6094:     }
 6095:     if (grep/^future$/,@{$status}) {
 6096:         if ($start > $now) {
 6097:             return 'ok';
 6098:         }
 6099:     }
 6100:     return; 
 6101: }
 6102: 
 6103: sub parse_portfolio_url {
 6104:     my ($url) = @_;
 6105: 
 6106:     my ($type,$udom,$unum,$group,$file_name);
 6107:     
 6108:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6109: 	$type = 1;
 6110:         $udom = $1;
 6111:         $unum = $2;
 6112:         $file_name = $3;
 6113:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6114: 	$type = 2;
 6115:         $udom = $1;
 6116:         $unum = $2;
 6117:         $group = $3;
 6118:         $file_name = $3.'/'.$4;
 6119:     }
 6120:     if (wantarray) {
 6121: 	return ($type,$udom,$unum,$file_name,$group);
 6122:     }
 6123:     return $type;
 6124: }
 6125: 
 6126: sub is_portfolio_url {
 6127:     my ($url) = @_;
 6128:     return scalar(&parse_portfolio_url($url));
 6129: }
 6130: 
 6131: sub is_portfolio_file {
 6132:     my ($file) = @_;
 6133:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6134:         return 1;
 6135:     }
 6136:     return;
 6137: }
 6138: 
 6139: sub usertools_access {
 6140:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6141:     my ($access,%tools);
 6142:     if ($context eq '') {
 6143:         $context = 'tools';
 6144:     }
 6145:     if ($context eq 'requestcourses') {
 6146:         %tools = (
 6147:                       official   => 1,
 6148:                       unofficial => 1,
 6149:                       community  => 1,
 6150:                  );
 6151:     } elsif ($context eq 'requestauthor') {
 6152:         %tools = (
 6153:                       requestauthor => 1,
 6154:                  );
 6155:     } else {
 6156:         %tools = (
 6157:                       aboutme   => 1,
 6158:                       blog      => 1,
 6159:                       webdav    => 1,
 6160:                       portfolio => 1,
 6161:                  );
 6162:     }
 6163:     return if (!defined($tools{$tool}));
 6164: 
 6165:     if ((!defined($udom)) || (!defined($uname))) {
 6166:         $udom = $env{'user.domain'};
 6167:         $uname = $env{'user.name'};
 6168:     }
 6169: 
 6170:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6171:         if ($action ne 'reload') {
 6172:             if ($context eq 'requestcourses') {
 6173:                 return $env{'environment.canrequest.'.$tool};
 6174:             } elsif ($context eq 'requestauthor') {
 6175:                 return $env{'environment.canrequest.author'};
 6176:             } else {
 6177:                 return $env{'environment.availabletools.'.$tool};
 6178:             }
 6179:         }
 6180:     }
 6181: 
 6182:     my ($toolstatus,$inststatus,$envkey);
 6183:     if ($context eq 'requestauthor') {
 6184:         $envkey = $context; 
 6185:     } else {
 6186:         $envkey = $context.'.'.$tool;
 6187:     }
 6188: 
 6189:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6190:          ($action ne 'reload')) {
 6191:         $toolstatus = $env{'environment.'.$envkey};
 6192:         $inststatus = $env{'environment.inststatus'};
 6193:     } else {
 6194:         if (ref($userenvref) eq 'HASH') {
 6195:             $toolstatus = $userenvref->{$envkey};
 6196:             $inststatus = $userenvref->{'inststatus'};
 6197:         } else {
 6198:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6199:             $toolstatus = $userenv{$envkey};
 6200:             $inststatus = $userenv{'inststatus'};
 6201:         }
 6202:     }
 6203: 
 6204:     if ($toolstatus ne '') {
 6205:         if ($toolstatus) {
 6206:             $access = 1;
 6207:         } else {
 6208:             $access = 0;
 6209:         }
 6210:         return $access;
 6211:     }
 6212: 
 6213:     my ($is_adv,%domdef);
 6214:     if (ref($is_advref) eq 'HASH') {
 6215:         $is_adv = $is_advref->{'is_adv'};
 6216:     } else {
 6217:         $is_adv = &is_advanced_user($udom,$uname);
 6218:     }
 6219:     if (ref($domdefref) eq 'HASH') {
 6220:         %domdef = %{$domdefref};
 6221:     } else {
 6222:         %domdef = &get_domain_defaults($udom);
 6223:     }
 6224:     if (ref($domdef{$tool}) eq 'HASH') {
 6225:         if ($is_adv) {
 6226:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6227:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6228:                     $access = 1;
 6229:                 } else {
 6230:                     $access = 0;
 6231:                 }
 6232:                 return $access;
 6233:             }
 6234:         }
 6235:         if ($inststatus ne '') {
 6236:             my ($hasaccess,$hasnoaccess);
 6237:             foreach my $affiliation (split(/:/,$inststatus)) {
 6238:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6239:                     if ($domdef{$tool}{$affiliation}) {
 6240:                         $hasaccess = 1;
 6241:                     } else {
 6242:                         $hasnoaccess = 1;
 6243:                     }
 6244:                 }
 6245:             }
 6246:             if ($hasaccess || $hasnoaccess) {
 6247:                 if ($hasaccess) {
 6248:                     $access = 1;
 6249:                 } elsif ($hasnoaccess) {
 6250:                     $access = 0; 
 6251:                 }
 6252:                 return $access;
 6253:             }
 6254:         } else {
 6255:             if ($domdef{$tool}{'default'} ne '') {
 6256:                 if ($domdef{$tool}{'default'}) {
 6257:                     $access = 1;
 6258:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6259:                     $access = 0;
 6260:                 }
 6261:                 return $access;
 6262:             }
 6263:         }
 6264:     } else {
 6265:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6266:             $access = 1;
 6267:         } else {
 6268:             $access = 0;
 6269:         }
 6270:         return $access;
 6271:     }
 6272: }
 6273: 
 6274: sub is_course_owner {
 6275:     my ($cdom,$cnum,$udom,$uname) = @_;
 6276:     if (($udom eq '') || ($uname eq '')) {
 6277:         $udom = $env{'user.domain'};
 6278:         $uname = $env{'user.name'};
 6279:     }
 6280:     unless (($udom eq '') || ($uname eq '')) {
 6281:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6282:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6283:                 return 1;
 6284:             } else {
 6285:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6286:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6287:                     return 1;
 6288:                 }
 6289:             }
 6290:         }
 6291:     }
 6292:     return;
 6293: }
 6294: 
 6295: sub is_advanced_user {
 6296:     my ($udom,$uname) = @_;
 6297:     if ($udom ne '' && $uname ne '') {
 6298:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6299:             if (wantarray) {
 6300:                 return ($env{'user.adv'},$env{'user.author'});
 6301:             } else {
 6302:                 return $env{'user.adv'};
 6303:             }
 6304:         }
 6305:     }
 6306:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6307:     my %allroles;
 6308:     my ($is_adv,$is_author);
 6309:     foreach my $role (keys(%roleshash)) {
 6310:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6311:         my $area = '/'.$tdomain.'/'.$trest;
 6312:         if ($sec ne '') {
 6313:             $area .= '/'.$sec;
 6314:         }
 6315:         if (($area ne '') && ($trole ne '')) {
 6316:             my $spec=$trole.'.'.$area;
 6317:             if ($trole =~ /^cr\//) {
 6318:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6319:             } elsif ($trole ne 'gr') {
 6320:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6321:             }
 6322:             if ($trole eq 'au') {
 6323:                 $is_author = 1;
 6324:             }
 6325:         }
 6326:     }
 6327:     foreach my $role (keys(%allroles)) {
 6328:         last if ($is_adv);
 6329:         foreach my $item (split(/:/,$allroles{$role})) {
 6330:             if ($item ne '') {
 6331:                 my ($privilege,$restrictions)=split(/&/,$item);
 6332:                 if ($privilege eq 'adv') {
 6333:                     $is_adv = 1;
 6334:                     last;
 6335:                 }
 6336:             }
 6337:         }
 6338:     }
 6339:     if (wantarray) {
 6340:         return ($is_adv,$is_author);
 6341:     }
 6342:     return $is_adv;
 6343: }
 6344: 
 6345: sub check_can_request {
 6346:     my ($dom,$can_request,$request_domains) = @_;
 6347:     my $canreq = 0;
 6348:     my ($types,$typename) = &Apache::loncommon::course_types();
 6349:     my @options = ('approval','validate','autolimit');
 6350:     my $optregex = join('|',@options);
 6351:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6352:         foreach my $type (@{$types}) {
 6353:             if (&usertools_access($env{'user.name'},
 6354:                                   $env{'user.domain'},
 6355:                                   $type,undef,'requestcourses')) {
 6356:                 $canreq ++;
 6357:                 if (ref($request_domains) eq 'HASH') {
 6358:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6359:                 }
 6360:                 if ($dom eq $env{'user.domain'}) {
 6361:                     $can_request->{$type} = 1;
 6362:                 }
 6363:             }
 6364:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6365:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6366:                 if (@curr > 0) {
 6367:                     foreach my $item (@curr) {
 6368:                         if (ref($request_domains) eq 'HASH') {
 6369:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6370:                             if ($otherdom ne '') {
 6371:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6372:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6373:                                         push(@{$request_domains->{$type}},$otherdom);
 6374:                                     }
 6375:                                 } else {
 6376:                                     push(@{$request_domains->{$type}},$otherdom);
 6377:                                 }
 6378:                             }
 6379:                         }
 6380:                     }
 6381:                     unless($dom eq $env{'user.domain'}) {
 6382:                         $canreq ++;
 6383:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6384:                             $can_request->{$type} = 1;
 6385:                         }
 6386:                     }
 6387:                 }
 6388:             }
 6389:         }
 6390:     }
 6391:     return $canreq;
 6392: }
 6393: 
 6394: # ---------------------------------------------- Custom access rule evaluation
 6395: 
 6396: sub customaccess {
 6397:     my ($priv,$uri)=@_;
 6398:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6399:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6400:     $udom = &LONCAPA::clean_domain($udom);
 6401:     $ucrs = &LONCAPA::clean_username($ucrs);
 6402:     my $access=0;
 6403:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6404: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6405: 	if ($type eq 'user') {
 6406: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6407: 		my ($tdom,$tuname)=split(m{/},$scope);
 6408: 		if ($tdom) {
 6409: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6410: 		}
 6411: 		if ($tuname) {
 6412: 		    if ($tuname ne $env{'user.name'}) { next; }
 6413: 		}
 6414: 		$access=($effect eq 'allow');
 6415: 		last;
 6416: 	    }
 6417: 	} else {
 6418: 	    if ($role) {
 6419: 		if ($role ne $urole) { next; }
 6420: 	    }
 6421: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6422: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6423: 		if ($tdom) {
 6424: 		    if ($tdom ne $udom) { next; }
 6425: 		}
 6426: 		if ($tcrs) {
 6427: 		    if ($tcrs ne $ucrs) { next; }
 6428: 		}
 6429: 		if ($tsec) {
 6430: 		    if ($tsec ne $usec) { next; }
 6431: 		}
 6432: 		$access=($effect eq 'allow');
 6433: 		last;
 6434: 	    }
 6435: 	    if ($realm eq '' && $role eq '') {
 6436: 		$access=($effect eq 'allow');
 6437: 	    }
 6438: 	}
 6439:     }
 6440:     return $access;
 6441: }
 6442: 
 6443: # ------------------------------------------------- Check for a user privilege
 6444: 
 6445: sub allowed {
 6446:     my ($priv,$uri,$symb,$role)=@_;
 6447:     my $ver_orguri=$uri;
 6448:     $uri=&deversion($uri);
 6449:     my $orguri=$uri;
 6450:     $uri=&declutter($uri);
 6451: 
 6452:     if ($priv eq 'evb') {
 6453: # Evade communication block restrictions for specified role in a course
 6454:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6455:             return $1;
 6456:         } else {
 6457:             return;
 6458:         }
 6459:     }
 6460: 
 6461:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6462: # Free bre access to adm and meta resources
 6463:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6464: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6465: 	&& ($priv eq 'bre')) {
 6466: 	return 'F';
 6467:     }
 6468: 
 6469: # Free bre access to user's own portfolio contents
 6470:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6471:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6472: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6473:         my %setters;
 6474:         my ($startblock,$endblock) = 
 6475:             &Apache::loncommon::blockcheck(\%setters,'port');
 6476:         if ($startblock && $endblock) {
 6477:             return 'B';
 6478:         } else {
 6479:             return 'F';
 6480:         }
 6481:     }
 6482: 
 6483: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6484:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6485:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6486:         if (exists($env{'request.course.id'})) {
 6487:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6488:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6489:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6490:                 my $courseprivid=$env{'request.course.id'};
 6491:                 $courseprivid=~s/\_/\//;
 6492:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6493:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6494:                     return $1; 
 6495:                 } else {
 6496:                     if ($env{'request.course.sec'}) {
 6497:                         $courseprivid.='/'.$env{'request.course.sec'};
 6498:                     }
 6499:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6500:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6501:                         return $2;
 6502:                     }
 6503:                 }
 6504:             }
 6505:         }
 6506:     }
 6507: 
 6508: # Free bre to public access
 6509: 
 6510:     if ($priv eq 'bre') {
 6511:         my $copyright=&metadata($uri,'copyright');
 6512: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6513:            return 'F'; 
 6514:         }
 6515:         if ($copyright eq 'priv') {
 6516:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6517: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6518: 		return '';
 6519:             }
 6520:         }
 6521:         if ($copyright eq 'domain') {
 6522:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6523: 	    unless (($env{'user.domain'} eq $1) ||
 6524:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6525: 		return '';
 6526:             }
 6527:         }
 6528:         if ($env{'request.role'}=~ /li\.\//) {
 6529:             # Library role, so allow browsing of resources in this domain.
 6530:             return 'F';
 6531:         }
 6532:         if ($copyright eq 'custom') {
 6533: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6534:         }
 6535:     }
 6536:     # Domain coordinator is trying to create a course
 6537:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6538:         # uri is the requested domain in this case.
 6539:         # comparison to 'request.role.domain' shows if the user has selected
 6540:         # a role of dc for the domain in question.
 6541:         return 'F' if ($uri eq $env{'request.role.domain'});
 6542:     }
 6543: 
 6544:     my $thisallowed='';
 6545:     my $statecond=0;
 6546:     my $courseprivid='';
 6547: 
 6548:     my $ownaccess;
 6549:     # Community Coordinator or Assistant Co-author browsing resource space.
 6550:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6551:         if ($uri eq '') {
 6552:             $ownaccess = 1;
 6553:         } else {
 6554:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6555:                 my $udom = $env{'user.domain'};
 6556:                 my $uname = $env{'user.name'};
 6557:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6558:                     $ownaccess = 1;
 6559:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6560:                     unless ($uri =~ m{\.\./}) {
 6561:                         $ownaccess = 1;
 6562:                     }
 6563:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6564:                     my $now = time;
 6565:                     if ($uri =~ m{^([^/]+)/?$}) {
 6566:                         my $adom = $1;
 6567:                         foreach my $key (keys(%env)) {
 6568:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6569:                                 my ($start,$end) = split('.',$env{$key});
 6570:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6571:                                     $ownaccess = 1;
 6572:                                     last;
 6573:                                 }
 6574:                             }
 6575:                         }
 6576:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6577:                         my $adom = $1;
 6578:                         my $aname = $2;
 6579:                         foreach my $role ('ca','aa') { 
 6580:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6581:                                 my ($start,$end) =
 6582:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6583:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6584:                                     $ownaccess = 1;
 6585:                                     last;
 6586:                                 }
 6587:                             }
 6588:                         }
 6589:                     }
 6590:                 }
 6591:             }
 6592:         }
 6593:     }
 6594: 
 6595: # Course
 6596: 
 6597:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6598:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6599:             $thisallowed.=$1;
 6600:         }
 6601:     }
 6602: 
 6603: # Domain
 6604: 
 6605:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6606:        =~/\Q$priv\E\&([^\:]*)/) {
 6607:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6608:             $thisallowed.=$1;
 6609:         }
 6610:     }
 6611: 
 6612: # User who is not author or co-author might still be able to edit
 6613: # resource of an author in the domain (e.g., if Domain Coordinator).
 6614:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6615:         (&allowed('mdc',$env{'request.course.id'}))) {
 6616:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6617:             $thisallowed.=$1;
 6618:         }
 6619:     }
 6620: 
 6621: # Course: uri itself is a course
 6622:     my $courseuri=$uri;
 6623:     $courseuri=~s/\_(\d)/\/$1/;
 6624:     $courseuri=~s/^([^\/])/\/$1/;
 6625: 
 6626:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6627:        =~/\Q$priv\E\&([^\:]*)/) {
 6628:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6629:             $thisallowed.=$1;
 6630:         }
 6631:     }
 6632: 
 6633: # URI is an uploaded document for this course, default permissions don't matter
 6634: # not allowing 'edit' access (editupload) to uploaded course docs
 6635:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6636: 	$thisallowed='';
 6637:         my ($match)=&is_on_map($uri);
 6638:         if ($match) {
 6639:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6640:                   =~/\Q$priv\E\&([^\:]*)/) {
 6641:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6642:                 if (@blockers > 0) {
 6643:                     $thisallowed = 'B';
 6644:                 } else {
 6645:                     $thisallowed.=$1;
 6646:                 }
 6647:             }
 6648:         } else {
 6649:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6650:             if ($refuri) {
 6651:                 if ($refuri =~ m|^/adm/|) {
 6652:                     $thisallowed='F';
 6653:                 } else {
 6654:                     $refuri=&declutter($refuri);
 6655:                     my ($match) = &is_on_map($refuri);
 6656:                     if ($match) {
 6657:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6658:                         if (@blockers > 0) {
 6659:                             $thisallowed = 'B';
 6660:                         } else {
 6661:                             $thisallowed='F';
 6662:                         }
 6663:                     }
 6664:                 }
 6665:             }
 6666:         }
 6667:     }
 6668: 
 6669:     if ($priv eq 'bre'
 6670: 	&& $thisallowed ne 'F' 
 6671: 	&& $thisallowed ne '2'
 6672: 	&& &is_portfolio_url($uri)) {
 6673: 	$thisallowed = &portfolio_access($uri);
 6674:     }
 6675:     
 6676: # Full access at system, domain or course-wide level? Exit.
 6677:     if ($thisallowed=~/F/) {
 6678: 	return 'F';
 6679:     }
 6680: 
 6681: # If this is generating or modifying users, exit with special codes
 6682: 
 6683:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6684: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6685: 	    my ($audom,$auname)=split('/',$uri);
 6686: # no author name given, so this just checks on the general right to make a co-author in this domain
 6687: 	    unless ($auname) { return $thisallowed; }
 6688: # an author name is given, so we are about to actually make a co-author for a certain account
 6689: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6690: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6691: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6692: 	}
 6693: 	return $thisallowed;
 6694:     }
 6695: #
 6696: # Gathered so far: system, domain and course wide privileges
 6697: #
 6698: # Course: See if uri or referer is an individual resource that is part of 
 6699: # the course
 6700: 
 6701:     if ($env{'request.course.id'}) {
 6702: 
 6703:        $courseprivid=$env{'request.course.id'};
 6704:        if ($env{'request.course.sec'}) {
 6705:           $courseprivid.='/'.$env{'request.course.sec'};
 6706:        }
 6707:        $courseprivid=~s/\_/\//;
 6708:        my $checkreferer=1;
 6709:        my ($match,$cond)=&is_on_map($uri);
 6710:        if ($match) {
 6711:            $statecond=$cond;
 6712:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6713:                =~/\Q$priv\E\&([^\:]*)/) {
 6714:                my $value = $1;
 6715:                if ($priv eq 'bre') {
 6716:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6717:                    if (@blockers > 0) {
 6718:                        $thisallowed = 'B';
 6719:                    } else {
 6720:                        $thisallowed.=$value;
 6721:                    }
 6722:                } else {
 6723:                    $thisallowed.=$value;
 6724:                }
 6725:                $checkreferer=0;
 6726:            }
 6727:        }
 6728:        
 6729:        if ($checkreferer) {
 6730: 	  my $refuri=$env{'httpref.'.$orguri};
 6731:             unless ($refuri) {
 6732:                 foreach my $key (keys(%env)) {
 6733: 		    if ($key=~/^httpref\..*\*/) {
 6734: 			my $pattern=$key;
 6735:                         $pattern=~s/^httpref\.\/res\///;
 6736:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6737:                         $pattern=~s/\//\\\//g;
 6738:                         if ($orguri=~/$pattern/) {
 6739: 			    $refuri=$env{$key};
 6740:                         }
 6741:                     }
 6742:                 }
 6743:             }
 6744: 
 6745:          if ($refuri) { 
 6746: 	  $refuri=&declutter($refuri);
 6747:           my ($match,$cond)=&is_on_map($refuri);
 6748:             if ($match) {
 6749:               my $refstatecond=$cond;
 6750:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6751:                   =~/\Q$priv\E\&([^\:]*)/) {
 6752:                   my $value = $1;
 6753:                   if ($priv eq 'bre') {
 6754:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6755:                       if (@blockers > 0) {
 6756:                           $thisallowed = 'B';
 6757:                       } else {
 6758:                           $thisallowed.=$value;
 6759:                       }
 6760:                   } else {
 6761:                       $thisallowed.=$value;
 6762:                   }
 6763:                   $uri=$refuri;
 6764:                   $statecond=$refstatecond;
 6765:               }
 6766:           }
 6767:         }
 6768:        }
 6769:    }
 6770: 
 6771: #
 6772: # Gathered now: all privileges that could apply, and condition number
 6773: # 
 6774: #
 6775: # Full or no access?
 6776: #
 6777: 
 6778:     if ($thisallowed=~/F/) {
 6779: 	return 'F';
 6780:     }
 6781: 
 6782:     unless ($thisallowed) {
 6783:         return '';
 6784:     }
 6785: 
 6786: # Restrictions exist, deal with them
 6787: #
 6788: #   C:according to course preferences
 6789: #   R:according to resource settings
 6790: #   L:unless locked
 6791: #   X:according to user session state
 6792: #
 6793: 
 6794: # Possibly locked functionality, check all courses
 6795: # Locks might take effect only after 10 minutes cache expiration for other
 6796: # courses, and 2 minutes for current course
 6797: 
 6798:     my $envkey;
 6799:     if ($thisallowed=~/L/) {
 6800:         foreach $envkey (keys(%env)) {
 6801:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6802:                my $courseid=$2;
 6803:                my $roleid=$1.'.'.$2;
 6804:                $courseid=~s/^\///;
 6805:                my $expiretime=600;
 6806:                if ($env{'request.role'} eq $roleid) {
 6807: 		  $expiretime=120;
 6808:                }
 6809: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6810:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6811:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6812: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6813:                }
 6814:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6815:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6816: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6817:                        &log($env{'user.domain'},$env{'user.name'},
 6818:                             $env{'user.home'},
 6819:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6820:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6821:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6822: 		       return '';
 6823:                    }
 6824:                }
 6825:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6826:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6827: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6828:                        &log($env{'user.domain'},$env{'user.name'},
 6829:                             $env{'user.home'},
 6830:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6831:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6832:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6833: 		       return '';
 6834:                    }
 6835:                }
 6836: 	   }
 6837:        }
 6838:     }
 6839:    
 6840: #
 6841: # Rest of the restrictions depend on selected course
 6842: #
 6843: 
 6844:     unless ($env{'request.course.id'}) {
 6845: 	if ($thisallowed eq 'A') {
 6846: 	    return 'A';
 6847:         } elsif ($thisallowed eq 'B') {
 6848:             return 'B';
 6849: 	} else {
 6850: 	    return '1';
 6851: 	}
 6852:     }
 6853: 
 6854: #
 6855: # Now user is definitely in a course
 6856: #
 6857: 
 6858: 
 6859: # Course preferences
 6860: 
 6861:    if ($thisallowed=~/C/) {
 6862:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6863:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6864:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6865: 	   =~/\Q$rolecode\E/) {
 6866: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6867: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6868: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6869: 			$env{'request.course.id'});
 6870: 	   }
 6871:            return '';
 6872:        }
 6873: 
 6874:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6875: 	   =~/\Q$unamedom\E/) {
 6876: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6877: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6878: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6879: 			$env{'request.course.id'});
 6880: 	   }
 6881:            return '';
 6882:        }
 6883:    }
 6884: 
 6885: # Resource preferences
 6886: 
 6887:    if ($thisallowed=~/R/) {
 6888:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6889:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6890: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6891: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6892: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6893: 	   }
 6894: 	   return '';
 6895:        }
 6896:    }
 6897: 
 6898: # Restricted by state or randomout?
 6899: 
 6900:    if ($thisallowed=~/X/) {
 6901:       if ($env{'acc.randomout'}) {
 6902: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6903:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6904:             return ''; 
 6905:          }
 6906:       }
 6907:       if (&condval($statecond)) {
 6908: 	 return '2';
 6909:       } else {
 6910:          return '';
 6911:       }
 6912:    }
 6913: 
 6914:     if ($thisallowed eq 'A') {
 6915: 	return 'A';
 6916:     } elsif ($thisallowed eq 'B') {
 6917:         return 'B';
 6918:     }
 6919:    return 'F';
 6920: }
 6921: 
 6922: # ------------------------------------------- Check construction space access
 6923: 
 6924: sub constructaccess {
 6925:     my ($url,$setpriv)=@_;
 6926: 
 6927: # We do not allow editing of previous versions of files
 6928:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6929: 
 6930: # Get username and domain from URL
 6931:     my ($ownername,$ownerdomain,$ownerhome);
 6932: 
 6933:     ($ownerdomain,$ownername) =
 6934:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6935: 
 6936: # The URL does not really point to any authorspace, forget it
 6937:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6938: 
 6939: # Now we need to see if the user has access to the authorspace of
 6940: # $ownername at $ownerdomain
 6941: 
 6942:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6943: # Real author for this?
 6944:        $ownerhome = $env{'user.home'};
 6945:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6946:           return ($ownername,$ownerdomain,$ownerhome);
 6947:        }
 6948:     } else {
 6949: # Co-author for this?
 6950:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6951:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6952:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6953:             return ($ownername,$ownerdomain,$ownerhome);
 6954:         }
 6955:     }
 6956: 
 6957: # We don't have any access right now. If we are not possibly going to do anything about this,
 6958: # we might as well leave
 6959:    unless ($setpriv) { return ''; }
 6960: 
 6961: # Backdoor access?
 6962:     my $allowed=&allowed('eco',$ownerdomain);
 6963: # Nope
 6964:     unless ($allowed) { return ''; }
 6965: # Looks like we may have access, but could be locked by the owner of the construction space
 6966:     if ($allowed eq 'U') {
 6967:         my %blocked=&get('environment',['domcoord.author'],
 6968:                          $ownerdomain,$ownername);
 6969: # Is blocked by owner
 6970:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6971:     }
 6972:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6973: # Grant temporary access
 6974:         my $then=$env{'user.login.time'};
 6975:         my $update=$env{'user.update.time'};
 6976:         if (!$update) { $update = $then; }
 6977:         my $refresh=$env{'user.refresh.time'};
 6978:         if (!$refresh) { $refresh = $update; }
 6979:         my $now = time;
 6980:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6981:                            $now,'ca','constructaccess');
 6982:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6983:         return($ownername,$ownerdomain,$ownerhome);
 6984:     }
 6985: # No business here
 6986:     return '';
 6987: }
 6988: 
 6989: sub get_comm_blocks {
 6990:     my ($cdom,$cnum) = @_;
 6991:     if ($cdom eq '' || $cnum eq '') {
 6992:         return unless ($env{'request.course.id'});
 6993:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6994:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6995:     }
 6996:     my %commblocks;
 6997:     my $hashid=$cdom.'_'.$cnum;
 6998:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6999:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7000:         %commblocks = %{$blocksref};
 7001:     } else {
 7002:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7003:         my $cachetime = 600;
 7004:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7005:     }
 7006:     return %commblocks;
 7007: }
 7008: 
 7009: sub has_comm_blocking {
 7010:     my ($priv,$symb,$uri,$blocks) = @_;
 7011:     return unless ($env{'request.course.id'});
 7012:     return unless ($priv eq 'bre');
 7013:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7014:     my %commblocks;
 7015:     if (ref($blocks) eq 'HASH') {
 7016:         %commblocks = %{$blocks};
 7017:     } else {
 7018:         %commblocks = &get_comm_blocks();
 7019:     }
 7020:     return unless (keys(%commblocks) > 0);
 7021:     if (!$symb) { $symb=&symbread($uri,1); }
 7022:     my ($map,$resid,undef)=&decode_symb($symb);
 7023:     my %tocheck = (
 7024:                     maps      => $map,
 7025:                     resources => $symb,
 7026:                   );
 7027:     my @blockers;
 7028:     my $now = time;
 7029:     my $navmap = Apache::lonnavmaps::navmap->new();
 7030:     foreach my $block (keys(%commblocks)) {
 7031:         if ($block =~ /^(\d+)____(\d+)$/) {
 7032:             my ($start,$end) = ($1,$2);
 7033:             if ($start <= $now && $end >= $now) {
 7034:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7035:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7036:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7037:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7038:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7039:                                     push(@blockers,$block);
 7040:                                 }
 7041:                             }
 7042:                         }
 7043:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7044:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7045:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7046:                                     push(@blockers,$block);
 7047:                                 }
 7048:                             }
 7049:                         }
 7050:                     }
 7051:                 }
 7052:             }
 7053:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7054:             my $item = $1;
 7055:             my @to_test;
 7056:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7057:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7058:                     my $check_interval;
 7059:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7060:                         my @interval;
 7061:                         my $type = 'map';
 7062:                         if ($item eq 'course') {
 7063:                             $type = 'course';
 7064:                             @interval=&EXT("resource.0.interval");
 7065:                         } else {
 7066:                             if ($item =~ /___\d+___/) {
 7067:                                 $type = 'resource';
 7068:                                 @interval=&EXT("resource.0.interval",$item);
 7069:                                 if (ref($navmap)) {                        
 7070:                                     my $res = $navmap->getBySymb($item); 
 7071:                                     push(@to_test,$res);
 7072:                                 }
 7073:                             } else {
 7074:                                 my $mapsymb = &symbread($item,1);
 7075:                                 if ($mapsymb) {
 7076:                                     if (ref($navmap)) {
 7077:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7078:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7079:                                         foreach my $res (@to_test) {
 7080:                                             my $symb = $res->symb();
 7081:                                             next if ($symb eq $mapsymb);
 7082:                                             if ($symb ne '') {
 7083:                                                 @interval=&EXT("resource.0.interval",$symb);
 7084:                                                 last;
 7085:                                             }
 7086:                                         }
 7087:                                     }
 7088:                                 }
 7089:                             }
 7090:                         }
 7091:                         if ($interval[0] =~ /\d+/) {
 7092:                             my $first_access;
 7093:                             if ($type eq 'resource') {
 7094:                                 $first_access=&get_first_access($interval[1],$item);
 7095:                             } elsif ($type eq 'map') {
 7096:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7097:                             } else {
 7098:                                 $first_access=&get_first_access($interval[1]);
 7099:                             }
 7100:                             if ($first_access) {
 7101:                                 my $timesup = $first_access+$interval[0];
 7102:                                 if ($timesup > $now) {
 7103:                                     foreach my $res (@to_test) {
 7104:                                         if ($res->is_problem()) {
 7105:                                             if ($res->completable()) {
 7106:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7107:                                                     push(@blockers,$block);
 7108:                                                 }
 7109:                                                 last;
 7110:                                             }
 7111:                                         }
 7112:                                     }
 7113:                                 }
 7114:                             }
 7115:                         }
 7116:                     }
 7117:                 }
 7118:             }
 7119:         }
 7120:     }
 7121:     return @blockers;
 7122: }
 7123: 
 7124: sub check_docs_block {
 7125:     my ($docsblock,$tocheck) =@_;
 7126:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7127:         return;
 7128:     }
 7129:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7130:         if ($tocheck->{'maps'}) {
 7131:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7132:                 return 1;
 7133:             }
 7134:         }
 7135:     }
 7136:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7137:         if ($tocheck->{'resources'}) {
 7138:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7139:                 return 1;
 7140:             }
 7141:         }
 7142:     }
 7143:     return;
 7144: }
 7145: 
 7146: #
 7147: #   Removes the versino from a URI and
 7148: #   splits it in to its filename and path to the filename.
 7149: #   Seems like File::Basename could have done this more clearly.
 7150: #   Parameters:
 7151: #      $uri   - input URI
 7152: #   Returns:
 7153: #     Two element list consisting of 
 7154: #     $pathname  - the URI up to and excluding the trailing /
 7155: #     $filename  - The part of the URI following the last /
 7156: #  NOTE:
 7157: #    Another realization of this is simply:
 7158: #    use File::Basename;
 7159: #    ...
 7160: #    $uri = shift;
 7161: #    $filename = basename($uri);
 7162: #    $path     = dirname($uri);
 7163: #    return ($filename, $path);
 7164: #
 7165: #     The implementation below is probably faster however.
 7166: #
 7167: sub split_uri_for_cond {
 7168:     my $uri=&deversion(&declutter(shift));
 7169:     my @uriparts=split(/\//,$uri);
 7170:     my $filename=pop(@uriparts);
 7171:     my $pathname=join('/',@uriparts);
 7172:     return ($pathname,$filename);
 7173: }
 7174: # --------------------------------------------------- Is a resource on the map?
 7175: 
 7176: sub is_on_map {
 7177:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7178:     #Trying to find the conditional for the file
 7179:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7180: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7181:     if ($match) {
 7182: 	return (1,$1);
 7183:     } else {
 7184: 	return (0,0);
 7185:     }
 7186: }
 7187: 
 7188: # --------------------------------------------------------- Get symb from alias
 7189: 
 7190: sub get_symb_from_alias {
 7191:     my $symb=shift;
 7192:     my ($map,$resid,$url)=&decode_symb($symb);
 7193: # Already is a symb
 7194:     if ($url) { return $symb; }
 7195: # Must be an alias
 7196:     my $aliassymb='';
 7197:     my %bighash;
 7198:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7199:                             &GDBM_READER(),0640)) {
 7200:         my $rid=$bighash{'mapalias_'.$symb};
 7201: 	if ($rid) {
 7202: 	    my ($mapid,$resid)=split(/\./,$rid);
 7203: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7204: 				    $resid,$bighash{'src_'.$rid});
 7205: 	}
 7206:         untie %bighash;
 7207:     }
 7208:     return $aliassymb;
 7209: }
 7210: 
 7211: # ----------------------------------------------------------------- Define Role
 7212: 
 7213: sub definerole {
 7214:   if (allowed('mcr','/')) {
 7215:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7216:     foreach my $role (split(':',$sysrole)) {
 7217: 	my ($crole,$cqual)=split(/\&/,$role);
 7218:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7219:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7220: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7221:                return "refused:s:$crole&$cqual"; 
 7222:             }
 7223:         }
 7224:     }
 7225:     foreach my $role (split(':',$domrole)) {
 7226: 	my ($crole,$cqual)=split(/\&/,$role);
 7227:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7228:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7229: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7230:                return "refused:d:$crole&$cqual"; 
 7231:             }
 7232:         }
 7233:     }
 7234:     foreach my $role (split(':',$courole)) {
 7235: 	my ($crole,$cqual)=split(/\&/,$role);
 7236:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7237:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7238: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7239:                return "refused:c:$crole&$cqual"; 
 7240:             }
 7241:         }
 7242:     }
 7243:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7244:                 "$env{'user.domain'}:$env{'user.name'}:".
 7245: 	        "rolesdef_$rolename=".
 7246:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7247:     return reply($command,$env{'user.home'});
 7248:   } else {
 7249:     return 'refused';
 7250:   }
 7251: }
 7252: 
 7253: # ---------------- Make a metadata query against the network of library servers
 7254: 
 7255: sub metadata_query {
 7256:     my ($query,$custom,$customshow,$server_array)=@_;
 7257:     my %rhash;
 7258:     my %libserv = &all_library();
 7259:     my @server_list = (defined($server_array) ? @$server_array
 7260:                                               : keys(%libserv) );
 7261:     for my $server (@server_list) {
 7262: 	unless ($custom or $customshow) {
 7263: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7264: 	    $rhash{$server}=$reply;
 7265: 	}
 7266: 	else {
 7267: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7268: 			     &escape($custom).':'.&escape($customshow),
 7269: 			     $server);
 7270: 	    $rhash{$server}=$reply;
 7271: 	}
 7272:     }
 7273:     return \%rhash;
 7274: }
 7275: 
 7276: # ----------------------------------------- Send log queries and wait for reply
 7277: 
 7278: sub log_query {
 7279:     my ($uname,$udom,$query,%filters)=@_;
 7280:     my $uhome=&homeserver($uname,$udom);
 7281:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7282:     my $uhost=&hostname($uhome);
 7283:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7284:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7285:                        $uhome);
 7286:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7287:     return get_query_reply($queryid);
 7288: }
 7289: 
 7290: # -------------------------- Update MySQL table for portfolio file
 7291: 
 7292: sub update_portfolio_table {
 7293:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7294:     if ($group ne '') {
 7295:         $file_name =~s /^\Q$group\E//;
 7296:     }
 7297:     my $homeserver = &homeserver($uname,$udom);
 7298:     my $queryid=
 7299:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7300:                ':'.&escape($file_name).':'.$action,$homeserver);
 7301:     my $reply = &get_query_reply($queryid);
 7302:     return $reply;
 7303: }
 7304: 
 7305: # -------------------------- Update MySQL allusers table
 7306: 
 7307: sub update_allusers_table {
 7308:     my ($uname,$udom,$names) = @_;
 7309:     my $homeserver = &homeserver($uname,$udom);
 7310:     my $queryid=
 7311:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7312:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7313:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7314:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7315:                'generation='.&escape($names->{'generation'}).'%%'.
 7316:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7317:                'id='.&escape($names->{'id'}),$homeserver);
 7318:     return;
 7319: }
 7320: 
 7321: # ------- Request retrieval of institutional classlists for course(s)
 7322: 
 7323: sub fetch_enrollment_query {
 7324:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7325:     my $homeserver;
 7326:     my $maxtries = 1;
 7327:     if ($context eq 'automated') {
 7328:         $homeserver = $perlvar{'lonHostID'};
 7329:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7330:     } else {
 7331:         $homeserver = &homeserver($cnum,$dom);
 7332:     }
 7333:     my $host=&hostname($homeserver);
 7334:     my $cmd = '';
 7335:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7336:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7337:     }
 7338:     $cmd =~ s/%%$//;
 7339:     $cmd = &escape($cmd);
 7340:     my $query = 'fetchenrollment';
 7341:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7342:     unless ($queryid=~/^\Q$host\E\_/) { 
 7343:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7344:         return 'error: '.$queryid;
 7345:     }
 7346:     my $reply = &get_query_reply($queryid);
 7347:     my $tries = 1;
 7348:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7349:         $reply = &get_query_reply($queryid);
 7350:         $tries ++;
 7351:     }
 7352:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7353:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7354:     } else {
 7355:         my @responses = split(/:/,$reply);
 7356:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7357:             foreach my $line (@responses) {
 7358:                 my ($key,$value) = split(/=/,$line,2);
 7359:                 $$replyref{$key} = $value;
 7360:             }
 7361:         } else {
 7362:             my $pathname = LONCAPA::tempdir();
 7363:             foreach my $line (@responses) {
 7364:                 my ($key,$value) = split(/=/,$line);
 7365:                 $$replyref{$key} = $value;
 7366:                 if ($value > 0) {
 7367:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7368:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7369:                         my $destname = $pathname.'/'.$filename;
 7370:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7371:                         if ($xml_classlist =~ /^error/) {
 7372:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7373:                         } else {
 7374:                             if ( open(FILE,">$destname") ) {
 7375:                                 print FILE &unescape($xml_classlist);
 7376:                                 close(FILE);
 7377:                             } else {
 7378:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7379:                             }
 7380:                         }
 7381:                     }
 7382:                 }
 7383:             }
 7384:         }
 7385:         return 'ok';
 7386:     }
 7387:     return 'error';
 7388: }
 7389: 
 7390: sub get_query_reply {
 7391:     my $queryid=shift;
 7392:     my $replyfile=LONCAPA::tempdir().$queryid;
 7393:     my $reply='';
 7394:     for (1..100) {
 7395: 	sleep 2;
 7396:         if (-e $replyfile.'.end') {
 7397: 	    if (open(my $fh,$replyfile)) {
 7398: 		$reply = join('',<$fh>);
 7399: 		close($fh);
 7400: 	   } else { return 'error: reply_file_error'; }
 7401:            return &unescape($reply);
 7402: 	}
 7403:     }
 7404:     return 'timeout:'.$queryid;
 7405: }
 7406: 
 7407: sub courselog_query {
 7408: #
 7409: # possible filters:
 7410: # url: url or symb
 7411: # username
 7412: # domain
 7413: # action: view, submit, grade
 7414: # start: timestamp
 7415: # end: timestamp
 7416: #
 7417:     my (%filters)=@_;
 7418:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7419:     if ($filters{'url'}) {
 7420: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7421:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7422:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7423:     }
 7424:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7425:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7426:     return &log_query($cname,$cdom,'courselog',%filters);
 7427: }
 7428: 
 7429: sub userlog_query {
 7430: #
 7431: # possible filters:
 7432: # action: log check role
 7433: # start: timestamp
 7434: # end: timestamp
 7435: #
 7436:     my ($uname,$udom,%filters)=@_;
 7437:     return &log_query($uname,$udom,'userlog',%filters);
 7438: }
 7439: 
 7440: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7441: 
 7442: sub auto_run {
 7443:     my ($cnum,$cdom) = @_;
 7444:     my $response = 0;
 7445:     my $settings;
 7446:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7447:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7448:         $settings = $domconfig{'autoenroll'};
 7449:         if ($settings->{'run'} eq '1') {
 7450:             $response = 1;
 7451:         }
 7452:     } else {
 7453:         my $homeserver;
 7454:         if (&is_course($cdom,$cnum)) {
 7455:             $homeserver = &homeserver($cnum,$cdom);
 7456:         } else {
 7457:             $homeserver = &domain($cdom,'primary');
 7458:         }
 7459:         if ($homeserver ne 'no_host') {
 7460:             $response = &reply('autorun:'.$cdom,$homeserver);
 7461:         }
 7462:     }
 7463:     return $response;
 7464: }
 7465: 
 7466: sub auto_get_sections {
 7467:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7468:     my $homeserver;
 7469:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7470:         $homeserver = &homeserver($cnum,$cdom);
 7471:     }
 7472:     if (!defined($homeserver)) { 
 7473:         if ($cdom =~ /^$match_domain$/) {
 7474:             $homeserver = &domain($cdom,'primary');
 7475:         }
 7476:     }
 7477:     my @secs;
 7478:     if (defined($homeserver)) {
 7479:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7480:         unless ($response eq 'refused') {
 7481:             @secs = split(/:/,$response);
 7482:         }
 7483:     }
 7484:     return @secs;
 7485: }
 7486: 
 7487: sub auto_new_course {
 7488:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7489:     my $homeserver = &homeserver($cnum,$cdom);
 7490:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7491:     return $response;
 7492: }
 7493: 
 7494: sub auto_validate_courseID {
 7495:     my ($cnum,$cdom,$inst_course_id) = @_;
 7496:     my $homeserver = &homeserver($cnum,$cdom);
 7497:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7498:     return $response;
 7499: }
 7500: 
 7501: sub auto_validate_instcode {
 7502:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7503:     my ($homeserver,$response);
 7504:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7505:         $homeserver = &homeserver($cnum,$cdom);
 7506:     }
 7507:     if (!defined($homeserver)) {
 7508:         if ($cdom =~ /^$match_domain$/) {
 7509:             $homeserver = &domain($cdom,'primary');
 7510:         }
 7511:     }
 7512:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7513:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7514:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7515:     return ($outcome,$description,$defaultcredits);
 7516: }
 7517: 
 7518: sub auto_create_password {
 7519:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7520:     my ($homeserver,$response);
 7521:     my $create_passwd = 0;
 7522:     my $authchk = '';
 7523:     if ($udom =~ /^$match_domain$/) {
 7524:         $homeserver = &domain($udom,'primary');
 7525:     }
 7526:     if ($homeserver eq '') {
 7527:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7528:             $homeserver = &homeserver($cnum,$cdom);
 7529:         }
 7530:     }
 7531:     if ($homeserver eq '') {
 7532:         $authchk = 'nodomain';
 7533:     } else {
 7534:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7535:         if ($response eq 'refused') {
 7536:             $authchk = 'refused';
 7537:         } else {
 7538:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7539:         }
 7540:     }
 7541:     return ($authparam,$create_passwd,$authchk);
 7542: }
 7543: 
 7544: sub auto_photo_permission {
 7545:     my ($cnum,$cdom,$students) = @_;
 7546:     my $homeserver = &homeserver($cnum,$cdom);
 7547:     my ($outcome,$perm_reqd,$conditions) = 
 7548: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7549:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7550: 	return (undef,undef);
 7551:     }
 7552:     return ($outcome,$perm_reqd,$conditions);
 7553: }
 7554: 
 7555: sub auto_checkphotos {
 7556:     my ($uname,$udom,$pid) = @_;
 7557:     my $homeserver = &homeserver($uname,$udom);
 7558:     my ($result,$resulttype);
 7559:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7560: 				   &escape($uname).':'.&escape($pid),
 7561: 				   $homeserver));
 7562:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7563: 	return (undef,undef);
 7564:     }
 7565:     if ($outcome) {
 7566:         ($result,$resulttype) = split(/:/,$outcome);
 7567:     } 
 7568:     return ($result,$resulttype);
 7569: }
 7570: 
 7571: sub auto_photochoice {
 7572:     my ($cnum,$cdom) = @_;
 7573:     my $homeserver = &homeserver($cnum,$cdom);
 7574:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7575: 						       &escape($cdom),
 7576: 						       $homeserver)));
 7577:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7578: 	return (undef,undef);
 7579:     }
 7580:     return ($update,$comment);
 7581: }
 7582: 
 7583: sub auto_photoupdate {
 7584:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7585:     my $homeserver = &homeserver($cnum,$dom);
 7586:     my $host=&hostname($homeserver);
 7587:     my $cmd = '';
 7588:     my $maxtries = 1;
 7589:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7590:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7591:     }
 7592:     $cmd =~ s/%%$//;
 7593:     $cmd = &escape($cmd);
 7594:     my $query = 'institutionalphotos';
 7595:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7596:     unless ($queryid=~/^\Q$host\E\_/) {
 7597:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7598:         return 'error: '.$queryid;
 7599:     }
 7600:     my $reply = &get_query_reply($queryid);
 7601:     my $tries = 1;
 7602:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7603:         $reply = &get_query_reply($queryid);
 7604:         $tries ++;
 7605:     }
 7606:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7607:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7608:     } else {
 7609:         my @responses = split(/:/,$reply);
 7610:         my $outcome = shift(@responses); 
 7611:         foreach my $item (@responses) {
 7612:             my ($key,$value) = split(/=/,$item);
 7613:             $$photo{$key} = $value;
 7614:         }
 7615:         return $outcome;
 7616:     }
 7617:     return 'error';
 7618: }
 7619: 
 7620: sub auto_instcode_format {
 7621:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7622: 	$cat_order) = @_;
 7623:     my $courses = '';
 7624:     my @homeservers;
 7625:     if ($caller eq 'global') {
 7626: 	my %servers = &get_servers($codedom,'library');
 7627: 	foreach my $tryserver (keys(%servers)) {
 7628: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7629: 		push(@homeservers,$tryserver);
 7630: 	    }
 7631:         }
 7632:     } elsif ($caller eq 'requests') {
 7633:         if ($codedom =~ /^$match_domain$/) {
 7634:             my $chome = &domain($codedom,'primary');
 7635:             unless ($chome eq 'no_host') {
 7636:                 push(@homeservers,$chome);
 7637:             }
 7638:         }
 7639:     } else {
 7640:         push(@homeservers,&homeserver($caller,$codedom));
 7641:     }
 7642:     foreach my $code (keys(%{$instcodes})) {
 7643:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7644:     }
 7645:     chop($courses);
 7646:     my $ok_response = 0;
 7647:     my $response;
 7648:     while (@homeservers > 0 && $ok_response == 0) {
 7649:         my $server = shift(@homeservers); 
 7650:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7651:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7652:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7653: 		split(/:/,$response);
 7654:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7655:             push(@{$codetitles},&str2array($codetitles_str));
 7656:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7657:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7658:             $ok_response = 1;
 7659:         }
 7660:     }
 7661:     if ($ok_response) {
 7662:         return 'ok';
 7663:     } else {
 7664:         return $response;
 7665:     }
 7666: }
 7667: 
 7668: sub auto_instcode_defaults {
 7669:     my ($domain,$returnhash,$code_order) = @_;
 7670:     my @homeservers;
 7671: 
 7672:     my %servers = &get_servers($domain,'library');
 7673:     foreach my $tryserver (keys(%servers)) {
 7674: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7675: 	    push(@homeservers,$tryserver);
 7676: 	}
 7677:     }
 7678: 
 7679:     my $response;
 7680:     foreach my $server (@homeservers) {
 7681:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7682:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7683: 	
 7684: 	foreach my $pair (split(/\&/,$response)) {
 7685: 	    my ($name,$value)=split(/\=/,$pair);
 7686: 	    if ($name eq 'code_order') {
 7687: 		@{$code_order} = split(/\&/,&unescape($value));
 7688: 	    } else {
 7689: 		$returnhash->{&unescape($name)}=&unescape($value);
 7690: 	    }
 7691: 	}
 7692: 	return 'ok';
 7693:     }
 7694: 
 7695:     return $response;
 7696: }
 7697: 
 7698: sub auto_possible_instcodes {
 7699:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7700:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7701:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7702:         return;
 7703:     }
 7704:     my (@homeservers,$uhome);
 7705:     if (defined(&domain($domain,'primary'))) {
 7706:         $uhome=&domain($domain,'primary');
 7707:         push(@homeservers,&domain($domain,'primary'));
 7708:     } else {
 7709:         my %servers = &get_servers($domain,'library');
 7710:         foreach my $tryserver (keys(%servers)) {
 7711:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7712:                 push(@homeservers,$tryserver);
 7713:             }
 7714:         }
 7715:     }
 7716:     my $response;
 7717:     foreach my $server (@homeservers) {
 7718:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7719:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7720:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7721:             split(':',$response);
 7722:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7723:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7724:         foreach my $item (split('&',$cat_title)) {   
 7725:             my ($name,$value)=split('=',$item);
 7726:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7727:         }
 7728:         foreach my $item (split('&',$cat_order)) {
 7729:             my ($name,$value)=split('=',$item);
 7730:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7731:         }
 7732:         return 'ok';
 7733:     }
 7734:     return $response;
 7735: }
 7736: 
 7737: sub auto_courserequest_checks {
 7738:     my ($dom) = @_;
 7739:     my ($homeserver,%validations);
 7740:     if ($dom =~ /^$match_domain$/) {
 7741:         $homeserver = &domain($dom,'primary');
 7742:     }
 7743:     unless ($homeserver eq 'no_host') {
 7744:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7745:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7746:             my @items = split(/&/,$response);
 7747:             foreach my $item (@items) {
 7748:                 my ($key,$value) = split('=',$item);
 7749:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7750:             }
 7751:         }
 7752:     }
 7753:     return %validations; 
 7754: }
 7755: 
 7756: sub auto_courserequest_validation {
 7757:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7758:     my ($homeserver,$response);
 7759:     if ($dom =~ /^$match_domain$/) {
 7760:         $homeserver = &domain($dom,'primary');
 7761:     }
 7762:     unless ($homeserver eq 'no_host') {  
 7763:           
 7764:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7765:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7766:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7767:                                     $homeserver));
 7768:     }
 7769:     return $response;
 7770: }
 7771: 
 7772: sub auto_validate_class_sec {
 7773:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7774:     my $homeserver = &homeserver($cnum,$cdom);
 7775:     my $ownerlist;
 7776:     if (ref($owners) eq 'ARRAY') {
 7777:         $ownerlist = join(',',@{$owners});
 7778:     } else {
 7779:         $ownerlist = $owners;
 7780:     }
 7781:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7782:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7783:     return $response;
 7784: }
 7785: 
 7786: # ------------------------------------------------------- Course Group routines
 7787: 
 7788: sub get_coursegroups {
 7789:     my ($cdom,$cnum,$group,$namespace) = @_;
 7790:     return(&dump($namespace,$cdom,$cnum,$group));
 7791: }
 7792: 
 7793: sub modify_coursegroup {
 7794:     my ($cdom,$cnum,$groupsettings) = @_;
 7795:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7796: }
 7797: 
 7798: sub toggle_coursegroup_status {
 7799:     my ($cdom,$cnum,$group,$action) = @_;
 7800:     my ($from_namespace,$to_namespace);
 7801:     if ($action eq 'delete') {
 7802:         $from_namespace = 'coursegroups';
 7803:         $to_namespace = 'deleted_groups';
 7804:     } else {
 7805:         $from_namespace = 'deleted_groups';
 7806:         $to_namespace = 'coursegroups';
 7807:     }
 7808:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7809:     if (my $tmp = &error(%curr_group)) {
 7810:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7811:         return ('read error',$tmp);
 7812:     } else {
 7813:         my %savedsettings = %curr_group; 
 7814:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7815:         my $deloutcome;
 7816:         if ($result eq 'ok') {
 7817:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7818:         } else {
 7819:             return ('write error',$result);
 7820:         }
 7821:         if ($deloutcome eq 'ok') {
 7822:             return 'ok';
 7823:         } else {
 7824:             return ('delete error',$deloutcome);
 7825:         }
 7826:     }
 7827: }
 7828: 
 7829: sub modify_group_roles {
 7830:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7831:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7832:     my $role = 'gr/'.&escape($userprivs);
 7833:     my ($uname,$udom) = split(/:/,$user);
 7834:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7835:     if ($result eq 'ok') {
 7836:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7837:     }
 7838:     return $result;
 7839: }
 7840: 
 7841: sub modify_coursegroup_membership {
 7842:     my ($cdom,$cnum,$membership) = @_;
 7843:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7844:     return $result;
 7845: }
 7846: 
 7847: sub get_active_groups {
 7848:     my ($udom,$uname,$cdom,$cnum) = @_;
 7849:     my $now = time;
 7850:     my %groups = ();
 7851:     foreach my $key (keys(%env)) {
 7852:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7853:             my ($start,$end) = split(/\./,$env{$key});
 7854:             if (($end!=0) && ($end<$now)) { next; }
 7855:             if (($start!=0) && ($start>$now)) { next; }
 7856:             if ($1 eq $cdom && $2 eq $cnum) {
 7857:                 $groups{$3} = $env{$key} ;
 7858:             }
 7859:         }
 7860:     }
 7861:     return %groups;
 7862: }
 7863: 
 7864: sub get_group_membership {
 7865:     my ($cdom,$cnum,$group) = @_;
 7866:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7867: }
 7868: 
 7869: sub get_users_groups {
 7870:     my ($udom,$uname,$courseid) = @_;
 7871:     my @usersgroups;
 7872:     my $cachetime=1800;
 7873: 
 7874:     my $hashid="$udom:$uname:$courseid";
 7875:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7876:     if (defined($cached)) {
 7877:         @usersgroups = split(/:/,$grouplist);
 7878:     } else {  
 7879:         $grouplist = '';
 7880:         my $courseurl = &courseid_to_courseurl($courseid);
 7881:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7882:         my $access_end = $env{'course.'.$courseid.
 7883:                               '.default_enrollment_end_date'};
 7884:         my $now = time;
 7885:         foreach my $key (keys(%roleshash)) {
 7886:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7887:                 my $group = $1;
 7888:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7889:                     my $start = $2;
 7890:                     my $end = $1;
 7891:                     if ($start == -1) { next; } # deleted from group
 7892:                     if (($start!=0) && ($start>$now)) { next; }
 7893:                     if (($end!=0) && ($end<$now)) {
 7894:                         if ($access_end && $access_end < $now) {
 7895:                             if ($access_end - $end < 86400) {
 7896:                                 push(@usersgroups,$group);
 7897:                             }
 7898:                         }
 7899:                         next;
 7900:                     }
 7901:                     push(@usersgroups,$group);
 7902:                 }
 7903:             }
 7904:         }
 7905:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7906:         $grouplist = join(':',@usersgroups);
 7907:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7908:     }
 7909:     return @usersgroups;
 7910: }
 7911: 
 7912: sub devalidate_getgroups_cache {
 7913:     my ($udom,$uname,$cdom,$cnum)=@_;
 7914:     my $courseid = $cdom.'_'.$cnum;
 7915: 
 7916:     my $hashid="$udom:$uname:$courseid";
 7917:     &devalidate_cache_new('getgroups',$hashid);
 7918: }
 7919: 
 7920: # ------------------------------------------------------------------ Plain Text
 7921: 
 7922: sub plaintext {
 7923:     my ($short,$type,$cid,$forcedefault) = @_;
 7924:     if ($short =~ m{^cr/}) {
 7925: 	return (split('/',$short))[-1];
 7926:     }
 7927:     if (!defined($cid)) {
 7928:         $cid = $env{'request.course.id'};
 7929:     }
 7930:     my %rolenames = (
 7931:                       Course    => 'std',
 7932:                       Community => 'alt1',
 7933:                     );
 7934:     if ($cid ne '') {
 7935:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7936:             unless ($forcedefault) {
 7937:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7938:                 &Apache::lonlocal::mt_escape(\$roletext);
 7939:                 return &Apache::lonlocal::mt($roletext);
 7940:             }
 7941:         }
 7942:     }
 7943:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7944:         (defined($rolenames{$type})) && 
 7945:         (defined($prp{$short}{$rolenames{$type}}))) {
 7946:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7947:     } elsif ($cid ne '') {
 7948:         my $crstype = $env{'course.'.$cid.'.type'};
 7949:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7950:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7951:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7952:         }
 7953:     }
 7954:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7955: }
 7956: 
 7957: # ----------------------------------------------------------------- Assign Role
 7958: 
 7959: sub assignrole {
 7960:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7961:         $context)=@_;
 7962:     my $mrole;
 7963:     if ($role =~ /^cr\//) {
 7964:         my $cwosec=$url;
 7965:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7966: 	unless (&allowed('ccr',$cwosec)) {
 7967:            my $refused = 1;
 7968:            if ($context eq 'requestcourses') {
 7969:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7970:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7971:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7972:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7973:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7974:                            if ($crsenv{'internal.courseowner'} eq
 7975:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7976:                                $refused = '';
 7977:                            }
 7978:                        }
 7979:                    }
 7980:                }
 7981:            }
 7982:            if ($refused) {
 7983:                &logthis('Refused custom assignrole: '.
 7984:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7985:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7986:                return 'refused';
 7987:            }
 7988:         }
 7989:         $mrole='cr';
 7990:     } elsif ($role =~ /^gr\//) {
 7991:         my $cwogrp=$url;
 7992:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7993:         unless (&allowed('mdg',$cwogrp)) {
 7994:             &logthis('Refused group assignrole: '.
 7995:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7996:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7997:             return 'refused';
 7998:         }
 7999:         $mrole='gr';
 8000:     } else {
 8001:         my $cwosec=$url;
 8002:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8003:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8004:             my $refused;
 8005:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8006:                 if (!(&allowed('c'.$role,$url))) {
 8007:                     $refused = 1;
 8008:                 }
 8009:             } else {
 8010:                 $refused = 1;
 8011:             }
 8012:             if ($refused) {
 8013:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8014:                 if (!$selfenroll && $context eq 'course') {
 8015:                     my %crsenv;
 8016:                     if ($role eq 'cc' || $role eq 'co') {
 8017:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8018:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8019:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8020:                                 if ($crsenv{'internal.courseowner'} eq 
 8021:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8022:                                     $refused = '';
 8023:                                 }
 8024:                             }
 8025:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8026:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8027:                                 if ($crsenv{'internal.courseowner'} eq 
 8028:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8029:                                     $refused = '';
 8030:                                 }
 8031:                             }
 8032:                         }
 8033:                     }
 8034:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8035:                     $refused = '';
 8036:                 } elsif ($context eq 'requestcourses') {
 8037:                     my @possroles = ('st','ta','ep','in','cc','co');
 8038:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8039:                         my $wrongcc;
 8040:                         if ($cnum =~ /^$match_community$/) {
 8041:                             $wrongcc = 1 if ($role eq 'cc');
 8042:                         } else {
 8043:                             $wrongcc = 1 if ($role eq 'co');
 8044:                         }
 8045:                         unless ($wrongcc) {
 8046:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8047:                             if ($crsenv{'internal.courseowner'} eq 
 8048:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8049:                                 $refused = '';
 8050:                             }
 8051:                         }
 8052:                     }
 8053:                 } elsif ($context eq 'requestauthor') {
 8054:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8055:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8056:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8057:                             $refused = '';
 8058:                         } else {
 8059:                             my %domdefaults = &get_domain_defaults($udom);
 8060:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8061:                                 my $checkbystatus;
 8062:                                 if ($env{'user.adv'}) { 
 8063:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8064:                                     if ($disposition eq 'automatic') {
 8065:                                         $refused = '';
 8066:                                     } elsif ($disposition eq '') {
 8067:                                         $checkbystatus = 1;
 8068:                                     } 
 8069:                                 } else {
 8070:                                     $checkbystatus = 1;
 8071:                                 }
 8072:                                 if ($checkbystatus) {
 8073:                                     if ($env{'environment.inststatus'}) {
 8074:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8075:                                         foreach my $type (@inststatuses) {
 8076:                                             if (($type ne '') &&
 8077:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8078:                                                 $refused = '';
 8079:                                             }
 8080:                                         }
 8081:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8082:                                         $refused = '';
 8083:                                     }
 8084:                                 }
 8085:                             }
 8086:                         }
 8087:                     }
 8088:                 }
 8089:                 if ($refused) {
 8090:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8091:                              ' '.$role.' '.$end.' '.$start.' by '.
 8092: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8093:                     return 'refused';
 8094:                 }
 8095:             }
 8096:         } elsif ($role eq 'au') {
 8097:             if ($url ne '/'.$udom.'/') {
 8098:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8099:                          ' to assign author role for '.$uname.':'.$udom.
 8100:                          ' in domain: '.$url.' refused (wrong domain).');
 8101:                 return 'refused';
 8102:             }
 8103:         }
 8104:         $mrole=$role;
 8105:     }
 8106:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8107:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8108:     if ($end) { $command.='_'.$end; }
 8109:     if ($start) {
 8110: 	if ($end) { 
 8111:            $command.='_'.$start; 
 8112:         } else {
 8113:            $command.='_0_'.$start;
 8114:         }
 8115:     }
 8116:     my $origstart = $start;
 8117:     my $origend = $end;
 8118:     my $delflag;
 8119: # actually delete
 8120:     if ($deleteflag) {
 8121: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8122: # modify command to delete the role
 8123:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8124:                 "$udom:$uname:$url".'_'."$mrole";
 8125: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8126: # set start and finish to negative values for userrolelog
 8127:            $start=-1;
 8128:            $end=-1;
 8129:            $delflag = 1;
 8130:         }
 8131:     }
 8132: # send command
 8133:     my $answer=&reply($command,&homeserver($uname,$udom));
 8134: # log new user role if status is ok
 8135:     if ($answer eq 'ok') {
 8136: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8137:         if (($role eq 'cc') || ($role eq 'in') ||
 8138:             ($role eq 'ep') || ($role eq 'ad') ||
 8139:             ($role eq 'ta') || ($role eq 'st') ||
 8140:             ($role=~/^cr/) || ($role eq 'gr') ||
 8141:             ($role eq 'co')) {
 8142: # for course roles, perform group memberships changes triggered by role change.
 8143:             unless ($role =~ /^gr/) {
 8144:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8145:                                                  $origstart,$selfenroll,$context);
 8146:             }
 8147:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8148:                            $selfenroll,$context);
 8149:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8150:                  ($role eq 'au') || ($role eq 'dc')) {
 8151:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8152:                            $context);
 8153:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8154:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8155:                              $context); 
 8156:         }
 8157:         if ($role eq 'cc') {
 8158:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8159:         }
 8160:     }
 8161:     return $answer;
 8162: }
 8163: 
 8164: sub autoupdate_coowners {
 8165:     my ($url,$end,$start,$uname,$udom) = @_;
 8166:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8167:     if (($cdom ne '') && ($cnum ne '')) {
 8168:         my $now = time;
 8169:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8170:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8171:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8172:             my $instcode = $coursehash{'internal.coursecode'};
 8173:             if ($instcode ne '') {
 8174:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8175:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8176:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8177:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8178:                         if ($result eq 'valid') {
 8179:                             if ($coursehash{'internal.co-owners'}) {
 8180:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8181:                                     push(@newcoowners,$coowner);
 8182:                                 }
 8183:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8184:                                     push(@newcoowners,$uname.':'.$udom);
 8185:                                 }
 8186:                                 @newcoowners = sort(@newcoowners);
 8187:                             } else {
 8188:                                 push(@newcoowners,$uname.':'.$udom);
 8189:                             }
 8190:                         } else {
 8191:                             if ($coursehash{'internal.co-owners'}) {
 8192:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8193:                                     unless ($coowner eq $uname.':'.$udom) {
 8194:                                         push(@newcoowners,$coowner);
 8195:                                     }
 8196:                                 }
 8197:                                 unless (@newcoowners > 0) {
 8198:                                     $delcoowners = 1;
 8199:                                     $coowners = '';
 8200:                                 }
 8201:                             }
 8202:                         }
 8203:                         if (@newcoowners || $delcoowners) {
 8204:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8205:                                             $delcoowners,@newcoowners);
 8206:                         }
 8207:                     }
 8208:                 }
 8209:             }
 8210:         }
 8211:     }
 8212: }
 8213: 
 8214: sub store_coowners {
 8215:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8216:     my $cid = $cdom.'_'.$cnum;
 8217:     my ($coowners,$delresult,$putresult);
 8218:     if (@newcoowners) {
 8219:         $coowners = join(',',@newcoowners);
 8220:         my %coownershash = (
 8221:                             'internal.co-owners' => $coowners,
 8222:                            );
 8223:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8224:         if ($putresult eq 'ok') {
 8225:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8226:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8227:             }
 8228:         }
 8229:     }
 8230:     if ($delcoowners) {
 8231:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8232:         if ($delresult eq 'ok') {
 8233:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8234:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8235:             }
 8236:         }
 8237:     }
 8238:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8239:         my %crsinfo =
 8240:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8241:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8242:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8243:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8244:         }
 8245:     }
 8246: }
 8247: 
 8248: # -------------------------------------------------- Modify user authentication
 8249: # Overrides without validation
 8250: 
 8251: sub modifyuserauth {
 8252:     my ($udom,$uname,$umode,$upass)=@_;
 8253:     my $uhome=&homeserver($uname,$udom);
 8254:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8255:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8256:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8257:              ' in domain '.$env{'request.role.domain'});  
 8258:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8259: 		     &escape($upass),$uhome);
 8260:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8261:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8262:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8263:     &log($udom,,$uname,$uhome,
 8264:         'Authentication changed by '.$env{'user.domain'}.', '.
 8265:                                      $env{'user.name'}.', '.$umode.
 8266:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8267:     unless ($reply eq 'ok') {
 8268:         &logthis('Authentication mode error: '.$reply);
 8269: 	return 'error: '.$reply;
 8270:     }   
 8271:     return 'ok';
 8272: }
 8273: 
 8274: # --------------------------------------------------------------- Modify a user
 8275: 
 8276: sub modifyuser {
 8277:     my ($udom,    $uname, $uid,
 8278:         $umode,   $upass, $first,
 8279:         $middle,  $last,  $gene,
 8280:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8281:     $udom= &LONCAPA::clean_domain($udom);
 8282:     $uname=&LONCAPA::clean_username($uname);
 8283:     my $showcandelete = 'none';
 8284:     if (ref($candelete) eq 'ARRAY') {
 8285:         if (@{$candelete} > 0) {
 8286:             $showcandelete = join(', ',@{$candelete});
 8287:         }
 8288:     }
 8289:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8290:              $umode.', '.$first.', '.$middle.', '.
 8291: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8292:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8293:                                      ' desiredhome not specified'). 
 8294:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8295:              ' in domain '.$env{'request.role.domain'});
 8296:     my $uhome=&homeserver($uname,$udom,'true');
 8297:     my $newuser;
 8298:     if ($uhome eq 'no_host') {
 8299:         $newuser = 1;
 8300:     }
 8301: # ----------------------------------------------------------------- Create User
 8302:     if (($uhome eq 'no_host') && 
 8303: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8304:         my $unhome='';
 8305:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8306:             $unhome = $desiredhome;
 8307: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8308: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8309:         } else { # load balancing routine for determining $unhome
 8310:             my $loadm=10000000;
 8311: 	    my %servers = &get_servers($udom,'library');
 8312: 	    foreach my $tryserver (keys(%servers)) {
 8313: 		my $answer=reply('load',$tryserver);
 8314: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8315: 		    $loadm=$answer;
 8316: 		    $unhome=$tryserver;
 8317: 		}
 8318: 	    }
 8319:         }
 8320:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8321: 	    return 'error: unable to find a home server for '.$uname.
 8322:                    ' in domain '.$udom;
 8323:         }
 8324:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8325:                          &escape($upass),$unhome);
 8326: 	unless ($reply eq 'ok') {
 8327:             return 'error: '.$reply;
 8328:         }   
 8329:         $uhome=&homeserver($uname,$udom,'true');
 8330:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8331: 	    return 'error: unable verify users home machine.';
 8332:         }
 8333:     }   # End of creation of new user
 8334: # ---------------------------------------------------------------------- Add ID
 8335:     if ($uid) {
 8336:        $uid=~tr/A-Z/a-z/;
 8337:        my %uidhash=&idrget($udom,$uname);
 8338:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8339:          && (!$forceid)) {
 8340: 	  unless ($uid eq $uidhash{$uname}) {
 8341: 	      return 'error: user id "'.$uid.'" does not match '.
 8342:                   'current user id "'.$uidhash{$uname}.'".';
 8343:           }
 8344:        } else {
 8345: 	  &idput($udom,($uname => $uid));
 8346:        }
 8347:     }
 8348: # -------------------------------------------------------------- Add names, etc
 8349:     my @tmp=&get('environment',
 8350: 		   ['firstname','middlename','lastname','generation','id',
 8351:                     'permanentemail','inststatus'],
 8352: 		   $udom,$uname);
 8353:     my (%names,%oldnames);
 8354:     if ($tmp[0] =~ m/^error:.*/) { 
 8355:         %names=(); 
 8356:     } else {
 8357:         %names = @tmp;
 8358:         %oldnames = %names;
 8359:     }
 8360: #
 8361: # If name, email and/or uid are blank (e.g., because an uploaded file
 8362: # of users did not contain them), do not overwrite existing values
 8363: # unless field is in $candelete array ref.  
 8364: #
 8365: 
 8366:     my @fields = ('firstname','middlename','lastname','generation',
 8367:                   'permanentemail','id');
 8368:     my %newvalues;
 8369:     if (ref($candelete) eq 'ARRAY') {
 8370:         foreach my $field (@fields) {
 8371:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8372:                 if ($field eq 'firstname') {
 8373:                     $names{$field} = $first;
 8374:                 } elsif ($field eq 'middlename') {
 8375:                     $names{$field} = $middle;
 8376:                 } elsif ($field eq 'lastname') {
 8377:                     $names{$field} = $last;
 8378:                 } elsif ($field eq 'generation') { 
 8379:                     $names{$field} = $gene;
 8380:                 } elsif ($field eq 'permanentemail') {
 8381:                     $names{$field} = $email;
 8382:                 } elsif ($field eq 'id') {
 8383:                     $names{$field}  = $uid;
 8384:                 }
 8385:             }
 8386:         }
 8387:     }
 8388:     if ($first)  { $names{'firstname'}  = $first; }
 8389:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8390:     if ($last)   { $names{'lastname'}   = $last; }
 8391:     if (defined($gene))   { $names{'generation'} = $gene; }
 8392:     if ($email) {
 8393:        $email=~s/[^\w\@\.\-\,]//gs;
 8394:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8395:     }
 8396:     if ($uid) { $names{'id'}  = $uid; }
 8397:     if (defined($inststatus)) {
 8398:         $names{'inststatus'} = '';
 8399:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8400:         if (ref($usertypes) eq 'HASH') {
 8401:             my @okstatuses; 
 8402:             foreach my $item (split(/:/,$inststatus)) {
 8403:                 if (defined($usertypes->{$item})) {
 8404:                     push(@okstatuses,$item);  
 8405:                 }
 8406:             }
 8407:             if (@okstatuses) {
 8408:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8409:             }
 8410:         }
 8411:     }
 8412:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8413:                  $umode.', '.$first.', '.$middle.', '.
 8414:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8415:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8416:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8417:     } else {
 8418:         $logmsg .= ' during self creation';
 8419:     }
 8420:     my $changed;
 8421:     if ($newuser) {
 8422:         $changed = 1;
 8423:     } else {
 8424:         foreach my $field (@fields) {
 8425:             if ($names{$field} ne $oldnames{$field}) {
 8426:                 $changed = 1;
 8427:                 last;
 8428:             }
 8429:         }
 8430:     }
 8431:     unless ($changed) {
 8432:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8433:         &logthis($logmsg);
 8434:         return 'ok';
 8435:     }
 8436:     my $reply = &put('environment', \%names, $udom,$uname);
 8437:     if ($reply ne 'ok') { 
 8438:         return 'error: '.$reply;
 8439:     }
 8440:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8441:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8442:     }
 8443:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8444:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8445:     $logmsg = 'Success modifying user '.$logmsg;
 8446:     &logthis($logmsg);
 8447:     return 'ok';
 8448: }
 8449: 
 8450: # -------------------------------------------------------------- Modify student
 8451: 
 8452: sub modifystudent {
 8453:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8454:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8455:         $selfenroll,$context,$inststatus,$credits)=@_;
 8456:     if (!$cid) {
 8457: 	unless ($cid=$env{'request.course.id'}) {
 8458: 	    return 'not_in_class';
 8459: 	}
 8460:     }
 8461: # --------------------------------------------------------------- Make the user
 8462:     my $reply=&modifyuser
 8463: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8464:          $desiredhome,$email,$inststatus);
 8465:     unless ($reply eq 'ok') { return $reply; }
 8466:     # This will cause &modify_student_enrollment to get the uid from the
 8467:     # students environment
 8468:     $uid = undef if (!$forceid);
 8469:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8470:                                         $gene,$usec,$end,$start,$type,$locktype,
 8471:                                         $cid,$selfenroll,$context,$credits);
 8472:     return $reply;
 8473: }
 8474: 
 8475: sub modify_student_enrollment {
 8476:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8477:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8478:     my ($cdom,$cnum,$chome);
 8479:     if (!$cid) {
 8480: 	unless ($cid=$env{'request.course.id'}) {
 8481: 	    return 'not_in_class';
 8482: 	}
 8483: 	$cdom=$env{'course.'.$cid.'.domain'};
 8484: 	$cnum=$env{'course.'.$cid.'.num'};
 8485:     } else {
 8486: 	($cdom,$cnum)=split(/_/,$cid);
 8487:     }
 8488:     $chome=$env{'course.'.$cid.'.home'};
 8489:     if (!$chome) {
 8490: 	$chome=&homeserver($cnum,$cdom);
 8491:     }
 8492:     if (!$chome) { return 'unknown_course'; }
 8493:     # Make sure the user exists
 8494:     my $uhome=&homeserver($uname,$udom);
 8495:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8496: 	return 'error: no such user';
 8497:     }
 8498:     # Get student data if we were not given enough information
 8499:     if (!defined($first)  || $first  eq '' || 
 8500:         !defined($last)   || $last   eq '' || 
 8501:         !defined($uid)    || $uid    eq '' || 
 8502:         !defined($middle) || $middle eq '' || 
 8503:         !defined($gene)   || $gene   eq '') {
 8504:         # They did not supply us with enough data to enroll the student, so
 8505:         # we need to pick up more information.
 8506:         my %tmp = &get('environment',
 8507:                        ['firstname','middlename','lastname', 'generation','id']
 8508:                        ,$udom,$uname);
 8509: 
 8510:         #foreach my $key (keys(%tmp)) {
 8511:         #    &logthis("key $key = ".$tmp{$key});
 8512:         #}
 8513:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8514:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8515:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8516:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8517:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8518:     }
 8519:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8520:     my $user = "$uname:$udom";
 8521:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8522:     my $reply=cput('classlist',
 8523: 		   {$user => 
 8524: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8525: 		   $cdom,$cnum);
 8526:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8527:         &devalidate_getsection_cache($udom,$uname,$cid);
 8528:     } else { 
 8529: 	return 'error: '.$reply;
 8530:     }
 8531:     # Add student role to user
 8532:     my $uurl='/'.$cid;
 8533:     $uurl=~s/\_/\//g;
 8534:     if ($usec) {
 8535: 	$uurl.='/'.$usec;
 8536:     }
 8537:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8538:                              $selfenroll,$context);
 8539:     if ($result ne 'ok') {
 8540:         if ($old_entry{$user} ne '') {
 8541:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8542:         } else {
 8543:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8544:         }
 8545:     }
 8546:     return $result; 
 8547: }
 8548: 
 8549: sub format_name {
 8550:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8551:     my $name;
 8552:     if ($first ne 'lastname') {
 8553: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8554:     } else {
 8555: 	if ($lastname=~/\S/) {
 8556: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8557: 	    $name=~s/\s+,/,/;
 8558: 	} else {
 8559: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8560: 	}
 8561:     }
 8562:     $name=~s/^\s+//;
 8563:     $name=~s/\s+$//;
 8564:     $name=~s/\s+/ /g;
 8565:     return $name;
 8566: }
 8567: 
 8568: # ------------------------------------------------- Write to course preferences
 8569: 
 8570: sub writecoursepref {
 8571:     my ($courseid,%prefs)=@_;
 8572:     $courseid=~s/^\///;
 8573:     $courseid=~s/\_/\//g;
 8574:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8575:     my $chome=homeserver($cnum,$cdomain);
 8576:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8577: 	return 'error: no such course';
 8578:     }
 8579:     my $cstring='';
 8580:     foreach my $pref (keys(%prefs)) {
 8581: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8582:     }
 8583:     $cstring=~s/\&$//;
 8584:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8585: }
 8586: 
 8587: # ---------------------------------------------------------- Make/modify course
 8588: 
 8589: sub createcourse {
 8590:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8591:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8592:     $url=&declutter($url);
 8593:     my $cid='';
 8594:     if ($context eq 'requestcourses') {
 8595:         my $can_create = 0;
 8596:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8597:         if ($udom eq $ownerdom) {
 8598:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8599:                                   $context)) {
 8600:                 $can_create = 1;
 8601:             }
 8602:         } else {
 8603:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8604:                                            $category);
 8605:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8606:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8607:                 if (@curr > 0) {
 8608:                     my @options = qw(approval validate autolimit);
 8609:                     my $optregex = join('|',@options);
 8610:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8611:                         $can_create = 1;
 8612:                     }
 8613:                 }
 8614:             }
 8615:         }
 8616:         if ($can_create) {
 8617:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8618:                 unless (&allowed('ccc',$udom)) {
 8619:                     return 'refused'; 
 8620:                 }
 8621:             }
 8622:         } else {
 8623:             return 'refused';
 8624:         }
 8625:     } elsif (!&allowed('ccc',$udom)) {
 8626:         return 'refused';
 8627:     }
 8628: # --------------------------------------------------------------- Get Unique ID
 8629:     my $uname;
 8630:     if ($cnum =~ /^$match_courseid$/) {
 8631:         my $chome=&homeserver($cnum,$udom,'true');
 8632:         if (($chome eq '') || ($chome eq 'no_host')) {
 8633:             $uname = $cnum;
 8634:         } else {
 8635:             $uname = &generate_coursenum($udom,$crstype);
 8636:         }
 8637:     } else {
 8638:         $uname = &generate_coursenum($udom,$crstype);
 8639:     }
 8640:     return $uname if ($uname =~ /^error/);
 8641: # -------------------------------------------------- Check supplied server name
 8642:     if (!defined($course_server)) {
 8643:         if (defined(&domain($udom,'primary'))) {
 8644:             $course_server = &domain($udom,'primary');
 8645:         } else {
 8646:             $course_server = $env{'user.home'}; 
 8647:         }
 8648:     }
 8649:     my %host_servers =
 8650:         &Apache::lonnet::get_servers($udom,'library');
 8651:     unless ($host_servers{$course_server}) {
 8652:         return 'error: invalid home server for course: '.$course_server;
 8653:     }
 8654: # ------------------------------------------------------------- Make the course
 8655:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8656:                       $course_server);
 8657:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8658:     my $uhome=&homeserver($uname,$udom,'true');
 8659:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8660: 	return 'error: no such course';
 8661:     }
 8662: # ----------------------------------------------------------------- Course made
 8663: # log existence
 8664:     my $now = time;
 8665:     my $newcourse = {
 8666:                     $udom.'_'.$uname => {
 8667:                                      description => $description,
 8668:                                      inst_code   => $inst_code,
 8669:                                      owner       => $course_owner,
 8670:                                      type        => $crstype,
 8671:                                      creator     => $env{'user.name'}.':'.
 8672:                                                     $env{'user.domain'},
 8673:                                      created     => $now,
 8674:                                      context     => $context,
 8675:                                                 },
 8676:                     };
 8677:     &courseidput($udom,$newcourse,$uhome,'notime');
 8678: # set toplevel url
 8679:     my $topurl=$url;
 8680:     unless ($nonstandard) {
 8681: # ------------------------------------------ For standard courses, make top url
 8682:         my $mapurl=&clutter($url);
 8683:         if ($mapurl eq '/res/') { $mapurl=''; }
 8684:         $env{'form.initmap'}=(<<ENDINITMAP);
 8685: <map>
 8686: <resource id="1" type="start"></resource>
 8687: <resource id="2" src="$mapurl"></resource>
 8688: <resource id="3" type="finish"></resource>
 8689: <link index="1" from="1" to="2"></link>
 8690: <link index="2" from="2" to="3"></link>
 8691: </map>
 8692: ENDINITMAP
 8693:         $topurl=&declutter(
 8694:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8695:                           );
 8696:     }
 8697: # ----------------------------------------------------------- Write preferences
 8698:     &writecoursepref($udom.'_'.$uname,
 8699:                      ('description'              => $description,
 8700:                       'url'                      => $topurl,
 8701:                       'internal.creator'         => $env{'user.name'}.':'.
 8702:                                                     $env{'user.domain'},
 8703:                       'internal.created'         => $now,
 8704:                       'internal.creationcontext' => $context)
 8705:                     );
 8706:     return '/'.$udom.'/'.$uname;
 8707: }
 8708: 
 8709: # ------------------------------------------------------------------- Create ID
 8710: sub generate_coursenum {
 8711:     my ($udom,$crstype) = @_;
 8712:     my $domdesc = &domain($udom);
 8713:     return 'error: invalid domain' if ($domdesc eq '');
 8714:     my $first;
 8715:     if ($crstype eq 'Community') {
 8716:         $first = '0';
 8717:     } else {
 8718:         $first = int(1+rand(9)); 
 8719:     } 
 8720:     my $uname=$first.
 8721:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8722:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8723:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8724: # ----------------------------------------------- Make sure that does not exist
 8725:     my $uhome=&homeserver($uname,$udom,'true');
 8726:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8727:         if ($crstype eq 'Community') {
 8728:             $first = '0';
 8729:         } else {
 8730:             $first = int(1+rand(9));
 8731:         }
 8732:         $uname=$first.
 8733:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8734:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8735:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8736:         $uhome=&homeserver($uname,$udom,'true');
 8737:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8738:             return 'error: unable to generate unique course-ID';
 8739:         }
 8740:     }
 8741:     return $uname;
 8742: }
 8743: 
 8744: sub is_course {
 8745:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8746:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8747: 
 8748:     return unless $cdom and $cnum;
 8749: 
 8750:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8751:         '.');
 8752: 
 8753:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8754:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8755: }
 8756: 
 8757: sub store_userdata {
 8758:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8759:     my $result;
 8760:     if ($datakey ne '') {
 8761:         if (ref($storehash) eq 'HASH') {
 8762:             if ($udom eq '' || $uname eq '') {
 8763:                 $udom = $env{'user.domain'};
 8764:                 $uname = $env{'user.name'};
 8765:             }
 8766:             my $uhome=&homeserver($uname,$udom);
 8767:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8768:                 $result = 'error: no_host';
 8769:             } else {
 8770:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8771:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8772: 
 8773:                 my $namevalue='';
 8774:                 foreach my $key (keys(%{$storehash})) {
 8775:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8776:                 }
 8777:                 $namevalue=~s/\&$//;
 8778:                 unless ($namespace eq 'courserequests') {
 8779:                     $datakey = &escape($datakey);
 8780:                 }
 8781:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8782:                                   $namevalue,$uhome);
 8783:             }
 8784:         } else {
 8785:             $result = 'error: data to store was not a hash reference'; 
 8786:         }
 8787:     } else {
 8788:         $result= 'error: invalid requestkey'; 
 8789:     }
 8790:     return $result;
 8791: }
 8792: 
 8793: # ---------------------------------------------------------- Assign Custom Role
 8794: 
 8795: sub assigncustomrole {
 8796:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8797:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8798:                        $end,$start,$deleteflag,$selfenroll,$context);
 8799: }
 8800: 
 8801: # ----------------------------------------------------------------- Revoke Role
 8802: 
 8803: sub revokerole {
 8804:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8805:     my $now=time;
 8806:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8807: }
 8808: 
 8809: # ---------------------------------------------------------- Revoke Custom Role
 8810: 
 8811: sub revokecustomrole {
 8812:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8813:     my $now=time;
 8814:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8815:            $deleteflag,$selfenroll,$context);
 8816: }
 8817: 
 8818: # ------------------------------------------------------------ Disk usage
 8819: sub diskusage {
 8820:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8821:     $directorypath =~ s/\/$//;
 8822:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8823:                        .&escape($getpropath).':'.&escape($uname).':'
 8824:                        .&escape($udom),homeserver($uname,$udom));
 8825:     if ($listing eq 'unknown_cmd') {
 8826:         if ($getpropath) {
 8827:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8828:         }
 8829:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8830:     }
 8831:     return $listing;
 8832: }
 8833: 
 8834: sub is_locked {
 8835:     my ($file_name, $domain, $user, $which) = @_;
 8836:     my @check;
 8837:     my $is_locked;
 8838:     push (@check,$file_name);
 8839:     my %locked = &get('file_permissions',\@check,
 8840: 		      $env{'user.domain'},$env{'user.name'});
 8841:     my ($tmp)=keys(%locked);
 8842:     if ($tmp=~/^error:/) { undef(%locked); }
 8843:     
 8844:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8845:         $is_locked = 'false';
 8846:         foreach my $entry (@{$locked{$file_name}}) {
 8847:            if (ref($entry) eq 'ARRAY') {
 8848:                $is_locked = 'true';
 8849:                if (ref($which) eq 'ARRAY') {
 8850:                    push(@{$which},$entry);
 8851:                } else {
 8852:                    last;
 8853:                }
 8854:            }
 8855:        }
 8856:     } else {
 8857:         $is_locked = 'false';
 8858:     }
 8859:     return $is_locked;
 8860: }
 8861: 
 8862: sub declutter_portfile {
 8863:     my ($file) = @_;
 8864:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8865:     return $file;
 8866: }
 8867: 
 8868: # ------------------------------------------------------------- Mark as Read Only
 8869: 
 8870: sub mark_as_readonly {
 8871:     my ($domain,$user,$files,$what) = @_;
 8872:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8873:     my ($tmp)=keys(%current_permissions);
 8874:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8875:     foreach my $file (@{$files}) {
 8876: 	$file = &declutter_portfile($file);
 8877:         push(@{$current_permissions{$file}},$what);
 8878:     }
 8879:     &put('file_permissions',\%current_permissions,$domain,$user);
 8880:     return;
 8881: }
 8882: 
 8883: # ------------------------------------------------------------Save Selected Files
 8884: 
 8885: sub save_selected_files {
 8886:     my ($user, $path, @files) = @_;
 8887:     my $filename = $user."savedfiles";
 8888:     my @other_files = &files_not_in_path($user, $path);
 8889:     open (OUT, '>'.$tmpdir.$filename);
 8890:     foreach my $file (@files) {
 8891:         print (OUT $env{'form.currentpath'}.$file."\n");
 8892:     }
 8893:     foreach my $file (@other_files) {
 8894:         print (OUT $file."\n");
 8895:     }
 8896:     close (OUT);
 8897:     return 'ok';
 8898: }
 8899: 
 8900: sub clear_selected_files {
 8901:     my ($user) = @_;
 8902:     my $filename = $user."savedfiles";
 8903:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8904:     print (OUT undef);
 8905:     close (OUT);
 8906:     return ("ok");    
 8907: }
 8908: 
 8909: sub files_in_path {
 8910:     my ($user, $path) = @_;
 8911:     my $filename = $user."savedfiles";
 8912:     my %return_files;
 8913:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8914:     while (my $line_in = <IN>) {
 8915:         chomp ($line_in);
 8916:         my @paths_and_file = split (m!/!, $line_in);
 8917:         my $file_part = pop (@paths_and_file);
 8918:         my $path_part = join ('/', @paths_and_file);
 8919:         $path_part.='/';
 8920:         my $path_and_file = $path_part.$file_part;
 8921:         if ($path_part eq $path) {
 8922:             $return_files{$file_part}= 'selected';
 8923:         }
 8924:     }
 8925:     close (IN);
 8926:     return (\%return_files);
 8927: }
 8928: 
 8929: # called in portfolio select mode, to show files selected NOT in current directory
 8930: sub files_not_in_path {
 8931:     my ($user, $path) = @_;
 8932:     my $filename = $user."savedfiles";
 8933:     my @return_files;
 8934:     my $path_part;
 8935:     open(IN, '<'.LONCAPA::.$filename);
 8936:     while (my $line = <IN>) {
 8937:         #ok, I know it's clunky, but I want it to work
 8938:         my @paths_and_file = split(m|/|, $line);
 8939:         my $file_part = pop(@paths_and_file);
 8940:         chomp($file_part);
 8941:         my $path_part = join('/', @paths_and_file);
 8942:         $path_part .= '/';
 8943:         my $path_and_file = $path_part.$file_part;
 8944:         if ($path_part ne $path) {
 8945:             push(@return_files, ($path_and_file));
 8946:         }
 8947:     }
 8948:     close(OUT);
 8949:     return (@return_files);
 8950: }
 8951: 
 8952: #----------------------------------------------Get portfolio file permissions
 8953: 
 8954: sub get_portfile_permissions {
 8955:     my ($domain,$user) = @_;
 8956:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8957:     my ($tmp)=keys(%current_permissions);
 8958:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8959:     return \%current_permissions;
 8960: }
 8961: 
 8962: #---------------------------------------------Get portfolio file access controls
 8963: 
 8964: sub get_access_controls {
 8965:     my ($current_permissions,$group,$file) = @_;
 8966:     my %access;
 8967:     my $real_file = $file;
 8968:     $file =~ s/\.meta$//;
 8969:     if (defined($file)) {
 8970:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8971:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8972:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8973:             }
 8974:         }
 8975:     } else {
 8976:         foreach my $key (keys(%{$current_permissions})) {
 8977:             if ($key =~ /\0accesscontrol$/) {
 8978:                 if (defined($group)) {
 8979:                     if ($key !~ m-^\Q$group\E/-) {
 8980:                         next;
 8981:                     }
 8982:                 }
 8983:                 my ($fullpath) = split(/\0/,$key);
 8984:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8985:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8986:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8987:                     }
 8988:                 }
 8989:             }
 8990:         }
 8991:     }
 8992:     return %access;
 8993: }
 8994: 
 8995: sub modify_access_controls {
 8996:     my ($file_name,$changes,$domain,$user)=@_;
 8997:     my ($outcome,$deloutcome);
 8998:     my %store_permissions;
 8999:     my %new_values;
 9000:     my %new_control;
 9001:     my %translation;
 9002:     my @deletions = ();
 9003:     my $now = time;
 9004:     if (exists($$changes{'activate'})) {
 9005:         if (ref($$changes{'activate'}) eq 'HASH') {
 9006:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9007:             my $numnew = scalar(@newitems);
 9008:             for (my $i=0; $i<$numnew; $i++) {
 9009:                 my $newkey = $newitems[$i];
 9010:                 my $newid = &Apache::loncommon::get_cgi_id();
 9011:                 if ($newkey =~ /^\d+:/) { 
 9012:                     $newkey =~ s/^(\d+)/$newid/;
 9013:                     $translation{$1} = $newid;
 9014:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9015:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9016:                     $translation{$1} = $newid;
 9017:                 }
 9018:                 $new_values{$file_name."\0".$newkey} = 
 9019:                                           $$changes{'activate'}{$newitems[$i]};
 9020:                 $new_control{$newkey} = $now;
 9021:             }
 9022:         }
 9023:     }
 9024:     my %todelete;
 9025:     my %changed_items;
 9026:     foreach my $action ('delete','update') {
 9027:         if (exists($$changes{$action})) {
 9028:             if (ref($$changes{$action}) eq 'HASH') {
 9029:                 foreach my $key (keys(%{$$changes{$action}})) {
 9030:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9031:                     if ($action eq 'delete') { 
 9032:                         $todelete{$itemnum} = 1;
 9033:                     } else {
 9034:                         $changed_items{$itemnum} = $key;
 9035:                     }
 9036:                 }
 9037:             }
 9038:         }
 9039:     }
 9040:     # get lock on access controls for file.
 9041:     my $lockhash = {
 9042:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9043:                                                        ':'.$env{'user.domain'},
 9044:                    }; 
 9045:     my $tries = 0;
 9046:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9047:    
 9048:     while (($gotlock ne 'ok') && $tries <3) {
 9049:         $tries ++;
 9050:         sleep 1;
 9051:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9052:     }
 9053:     if ($gotlock eq 'ok') {
 9054:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9055:         my ($tmp)=keys(%curr_permissions);
 9056:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9057:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9058:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9059:             if (ref($curr_controls) eq 'HASH') {
 9060:                 foreach my $control_item (keys(%{$curr_controls})) {
 9061:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9062:                     if (defined($todelete{$itemnum})) {
 9063:                         push(@deletions,$file_name."\0".$control_item);
 9064:                     } else {
 9065:                         if (defined($changed_items{$itemnum})) {
 9066:                             $new_control{$changed_items{$itemnum}} = $now;
 9067:                             push(@deletions,$file_name."\0".$control_item);
 9068:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9069:                         } else {
 9070:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9071:                         }
 9072:                     }
 9073:                 }
 9074:             }
 9075:         }
 9076:         my ($group);
 9077:         if (&is_course($domain,$user)) {
 9078:             ($group,my $file) = split(/\//,$file_name,2);
 9079:         }
 9080:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9081:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9082:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9083:         #  remove lock
 9084:         my @del_lock = ($file_name."\0".'locked_access_records');
 9085:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9086:         my $sqlresult =
 9087:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9088:                                     $group);
 9089:     } else {
 9090:         $outcome = "error: could not obtain lockfile\n";  
 9091:     }
 9092:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9093: }
 9094: 
 9095: sub make_public_indefinitely {
 9096:     my ($requrl) = @_;
 9097:     my $now = time;
 9098:     my $action = 'activate';
 9099:     my $aclnum = 0;
 9100:     if (&is_portfolio_url($requrl)) {
 9101:         my (undef,$udom,$unum,$file_name,$group) =
 9102:             &parse_portfolio_url($requrl);
 9103:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9104:         my %access_controls = &get_access_controls($current_perms,
 9105:                                                    $group,$file_name);
 9106:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9107:             my ($num,$scope,$end,$start) = 
 9108:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9109:             if ($scope eq 'public') {
 9110:                 if ($start <= $now && $end == 0) {
 9111:                     $action = 'none';
 9112:                 } else {
 9113:                     $action = 'update';
 9114:                     $aclnum = $num;
 9115:                 }
 9116:                 last;
 9117:             }
 9118:         }
 9119:         if ($action eq 'none') {
 9120:              return 'ok';
 9121:         } else {
 9122:             my %changes;
 9123:             my $newend = 0;
 9124:             my $newstart = $now;
 9125:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9126:             $changes{$action}{$newkey} = {
 9127:                 type => 'public',
 9128:                 time => {
 9129:                     start => $newstart,
 9130:                     end   => $newend,
 9131:                 },
 9132:             };
 9133:             my ($outcome,$deloutcome,$new_values,$translation) =
 9134:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9135:             return $outcome;
 9136:         }
 9137:     } else {
 9138:         return 'invalid';
 9139:     }
 9140: }
 9141: 
 9142: #------------------------------------------------------Get Marked as Read Only
 9143: 
 9144: sub get_marked_as_readonly {
 9145:     my ($domain,$user,$what,$group) = @_;
 9146:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9147:     my @readonly_files;
 9148:     my $cmp1=$what;
 9149:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9150:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9151:         if (defined($group)) {
 9152:             if ($file_name !~ m-^\Q$group\E/-) {
 9153:                 next;
 9154:             }
 9155:         }
 9156:         if (ref($value) eq "ARRAY"){
 9157:             foreach my $stored_what (@{$value}) {
 9158:                 my $cmp2=$stored_what;
 9159:                 if (ref($stored_what) eq 'ARRAY') {
 9160:                     $cmp2=join('',@{$stored_what});
 9161:                 }
 9162:                 if ($cmp1 eq $cmp2) {
 9163:                     push(@readonly_files, $file_name);
 9164:                     last;
 9165:                 } elsif (!defined($what)) {
 9166:                     push(@readonly_files, $file_name);
 9167:                     last;
 9168:                 }
 9169:             }
 9170:         }
 9171:     }
 9172:     return @readonly_files;
 9173: }
 9174: #-----------------------------------------------------------Get Marked as Read Only Hash
 9175: 
 9176: sub get_marked_as_readonly_hash {
 9177:     my ($current_permissions,$group,$what) = @_;
 9178:     my %readonly_files;
 9179:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9180:         if (defined($group)) {
 9181:             if ($file_name !~ m-^\Q$group\E/-) {
 9182:                 next;
 9183:             }
 9184:         }
 9185:         if (ref($value) eq "ARRAY"){
 9186:             foreach my $stored_what (@{$value}) {
 9187:                 if (ref($stored_what) eq 'ARRAY') {
 9188:                     foreach my $lock_descriptor(@{$stored_what}) {
 9189:                         if ($lock_descriptor eq 'graded') {
 9190:                             $readonly_files{$file_name} = 'graded';
 9191:                         } elsif ($lock_descriptor eq 'handback') {
 9192:                             $readonly_files{$file_name} = 'handback';
 9193:                         } else {
 9194:                             if (!exists($readonly_files{$file_name})) {
 9195:                                 $readonly_files{$file_name} = 'locked';
 9196:                             }
 9197:                         }
 9198:                     }
 9199:                 } 
 9200:             }
 9201:         } 
 9202:     }
 9203:     return %readonly_files;
 9204: }
 9205: # ------------------------------------------------------------ Unmark as Read Only
 9206: 
 9207: sub unmark_as_readonly {
 9208:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9209:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9210:     my ($domain,$user,$what,$file_name,$group) = @_;
 9211:     $file_name = &declutter_portfile($file_name);
 9212:     my $symb_crs = $what;
 9213:     if (ref($what)) { $symb_crs=join('',@$what); }
 9214:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9215:     my ($tmp)=keys(%current_permissions);
 9216:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9217:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9218:     foreach my $file (@readonly_files) {
 9219: 	my $clean_file = &declutter_portfile($file);
 9220: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9221: 	my $current_locks = $current_permissions{$file};
 9222:         my @new_locks;
 9223:         my @del_keys;
 9224:         if (ref($current_locks) eq "ARRAY"){
 9225:             foreach my $locker (@{$current_locks}) {
 9226:                 my $compare=$locker;
 9227:                 if (ref($locker) eq 'ARRAY') {
 9228:                     $compare=join('',@{$locker});
 9229:                     if ($compare ne $symb_crs) {
 9230:                         push(@new_locks, $locker);
 9231:                     }
 9232:                 }
 9233:             }
 9234:             if (scalar(@new_locks) > 0) {
 9235:                 $current_permissions{$file} = \@new_locks;
 9236:             } else {
 9237:                 push(@del_keys, $file);
 9238:                 &del('file_permissions',\@del_keys, $domain, $user);
 9239:                 delete($current_permissions{$file});
 9240:             }
 9241:         }
 9242:     }
 9243:     &put('file_permissions',\%current_permissions,$domain,$user);
 9244:     return;
 9245: }
 9246: 
 9247: # ------------------------------------------------------------ Directory lister
 9248: 
 9249: sub dirlist {
 9250:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9251:     $uri=~s/^\///;
 9252:     $uri=~s/\/$//;
 9253:     my ($udom, $uname);
 9254:     if ($getuserdir) {
 9255:         $udom = $userdomain;
 9256:         $uname = $username;
 9257:     } else {
 9258:         (undef,$udom,$uname)=split(/\//,$uri);
 9259:         if(defined($userdomain)) {
 9260:             $udom = $userdomain;
 9261:         }
 9262:         if(defined($username)) {
 9263:             $uname = $username;
 9264:         }
 9265:     }
 9266:     my ($dirRoot,$listing,@listing_results);
 9267: 
 9268:     $dirRoot = $perlvar{'lonDocRoot'};
 9269:     if (defined($getpropath)) {
 9270:         $dirRoot = &propath($udom,$uname);
 9271:         $dirRoot =~ s/\/$//;
 9272:     } elsif (defined($getuserdir)) {
 9273:         my $subdir=$uname.'__';
 9274:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9275:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9276:                    ."/$udom/$subdir/$uname";
 9277:     } elsif (defined($alternateRoot)) {
 9278:         $dirRoot = $alternateRoot;
 9279:     }
 9280: 
 9281:     if($udom) {
 9282:         if($uname) {
 9283:             my $uhome = &homeserver($uname,$udom);
 9284:             if ($uhome eq 'no_host') {
 9285:                 return ([],'no_host');
 9286:             }
 9287:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9288:                               .$getuserdir.':'.&escape($dirRoot)
 9289:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9290:             if ($listing eq 'unknown_cmd') {
 9291:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9292:             } else {
 9293:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9294:             }
 9295:             if ($listing eq 'unknown_cmd') {
 9296:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9297:                 @listing_results = split(/:/,$listing);
 9298:             } else {
 9299:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9300:             }
 9301:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9302:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9303:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9304:                 return ([],$listing);
 9305:             } else {
 9306:                 return (\@listing_results);
 9307:             }
 9308:         } elsif(!$alternateRoot) {
 9309:             my (%allusers,%listerror);
 9310: 	    my %servers = &get_servers($udom,'library');
 9311:  	    foreach my $tryserver (keys(%servers)) {
 9312:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9313:                                   &escape($udom),$tryserver);
 9314:                 if ($listing eq 'unknown_cmd') {
 9315: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9316: 				      $udom, $tryserver);
 9317:                 } else {
 9318:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9319:                 }
 9320: 		if ($listing eq 'unknown_cmd') {
 9321: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9322: 				      $udom, $tryserver);
 9323: 		    @listing_results = split(/:/,$listing);
 9324: 		} else {
 9325: 		    @listing_results =
 9326: 			map { &unescape($_); } split(/:/,$listing);
 9327: 		}
 9328:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9329:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9330:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9331:                     $listerror{$tryserver} = $listing;
 9332:                 } else {
 9333: 		    foreach my $line (@listing_results) {
 9334: 			my ($entry) = split(/&/,$line,2);
 9335: 			$allusers{$entry} = 1;
 9336: 		    }
 9337: 		}
 9338:             }
 9339:             my @alluserslist=();
 9340:             foreach my $user (sort(keys(%allusers))) {
 9341:                 push(@alluserslist,$user.'&user');
 9342:             }
 9343:             return (\@alluserslist);
 9344:         } else {
 9345:             return ([],'missing username');
 9346:         }
 9347:     } elsif(!defined($getpropath)) {
 9348:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9349:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9350:         return (\@all_domains);
 9351:     } else {
 9352:         return ([],'missing domain');
 9353:     }
 9354: }
 9355: 
 9356: # --------------------------------------------- GetFileTimestamp
 9357: # This function utilizes dirlist and returns the date stamp for
 9358: # when it was last modified.  It will also return an error of -1
 9359: # if an error occurs
 9360: 
 9361: sub GetFileTimestamp {
 9362:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9363:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9364:     $studentName   = &LONCAPA::clean_username($studentName);
 9365:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9366:                                     undef,$getuserdir);
 9367:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9368:         return -1;
 9369:     }
 9370:     if (ref($fileref) eq 'ARRAY') {
 9371:         my @stats = split('&',$fileref->[0]);
 9372:         # @stats contains first the filename, then the stat output
 9373:         return $stats[10]; # so this is 10 instead of 9.
 9374:     } else {
 9375:         return -1;
 9376:     }
 9377: }
 9378: 
 9379: sub stat_file {
 9380:     my ($uri) = @_;
 9381:     $uri = &clutter_with_no_wrapper($uri);
 9382: 
 9383:     my ($udom,$uname,$file);
 9384:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9385: 	($udom,$uname,$file) =
 9386: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9387: 	$file = 'userfiles/'.$file;
 9388:     }
 9389:     if ($uri =~ m-^/res/-) {
 9390: 	($udom,$uname) = 
 9391: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9392: 	$file = $uri;
 9393:     }
 9394: 
 9395:     if (!$udom || !$uname || !$file) {
 9396: 	# unable to handle the uri
 9397: 	return ();
 9398:     }
 9399:     my $getpropath;
 9400:     if ($file =~ /^userfiles\//) {
 9401:         $getpropath = 1;
 9402:     }
 9403:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9404:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9405:         return ();
 9406:     } else {
 9407:         if (ref($listref) eq 'ARRAY') {
 9408:             my @stats = split('&',$listref->[0]);
 9409: 	    shift(@stats); #filename is first
 9410: 	    return @stats;
 9411:         }
 9412:     }
 9413:     return ();
 9414: }
 9415: 
 9416: # -------------------------------------------------------- Value of a Condition
 9417: 
 9418: # gets the value of a specific preevaluated condition
 9419: #    stored in the string  $env{user.state.<cid>}
 9420: # or looks up a condition reference in the bighash and if if hasn't
 9421: # already been evaluated recurses into docondval to get the value of
 9422: # the condition, then memoizing it to 
 9423: #   $env{user.state.<cid>.<condition>}
 9424: sub directcondval {
 9425:     my $number=shift;
 9426:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9427: 	&Apache::lonuserstate::evalstate();
 9428:     }
 9429:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9430: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9431:     } elsif ($number =~ /^_/) {
 9432: 	my $sub_condition;
 9433: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9434: 		&GDBM_READER(),0640)) {
 9435: 	    $sub_condition=$bighash{'conditions'.$number};
 9436: 	    untie(%bighash);
 9437: 	}
 9438: 	my $value = &docondval($sub_condition);
 9439: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9440: 	return $value;
 9441:     }
 9442:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9443:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9444:     } else {
 9445:        return 2;
 9446:     }
 9447: }
 9448: 
 9449: # get the collection of conditions for this resource
 9450: sub condval {
 9451:     my $condidx=shift;
 9452:     my $allpathcond='';
 9453:     foreach my $cond (split(/\|/,$condidx)) {
 9454: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9455: 	    $allpathcond.=
 9456: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9457: 	}
 9458:     }
 9459:     $allpathcond=~s/\|$//;
 9460:     return &docondval($allpathcond);
 9461: }
 9462: 
 9463: #evaluates an expression of conditions
 9464: sub docondval {
 9465:     my ($allpathcond) = @_;
 9466:     my $result=0;
 9467:     if ($env{'request.course.id'}
 9468: 	&& defined($allpathcond)) {
 9469: 	my $operand='|';
 9470: 	my @stack;
 9471: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9472: 	    if ($chunk eq '(') {
 9473: 		push @stack,($operand,$result);
 9474: 	    } elsif ($chunk eq ')') {
 9475: 		my $before=pop @stack;
 9476: 		if (pop @stack eq '&') {
 9477: 		    $result=$result>$before?$before:$result;
 9478: 		} else {
 9479: 		    $result=$result>$before?$result:$before;
 9480: 		}
 9481: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9482: 		$operand=$chunk;
 9483: 	    } else {
 9484: 		my $new=directcondval($chunk);
 9485: 		if ($operand eq '&') {
 9486: 		    $result=$result>$new?$new:$result;
 9487: 		} else {
 9488: 		    $result=$result>$new?$result:$new;
 9489: 		}
 9490: 	    }
 9491: 	}
 9492:     }
 9493:     return $result;
 9494: }
 9495: 
 9496: # ---------------------------------------------------- Devalidate courseresdata
 9497: 
 9498: sub devalidatecourseresdata {
 9499:     my ($coursenum,$coursedomain)=@_;
 9500:     my $hashid=$coursenum.':'.$coursedomain;
 9501:     &devalidate_cache_new('courseres',$hashid);
 9502: }
 9503: 
 9504: 
 9505: # --------------------------------------------------- Course Resourcedata Query
 9506: #
 9507: #  Parameters:
 9508: #      $coursenum    - Number of the course.
 9509: #      $coursedomain - Domain at which the course was created.
 9510: #  Returns:
 9511: #     A hash of the course parameters along (I think) with timestamps
 9512: #     and version info.
 9513: 
 9514: sub get_courseresdata {
 9515:     my ($coursenum,$coursedomain)=@_;
 9516:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9517:     my $hashid=$coursenum.':'.$coursedomain;
 9518:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9519:     my %dumpreply;
 9520:     unless (defined($cached)) {
 9521: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9522: 	$result=\%dumpreply;
 9523: 	my ($tmp) = keys(%dumpreply);
 9524: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9525: 	    &do_cache_new('courseres',$hashid,$result,600);
 9526: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9527: 	    return $tmp;
 9528: 	} elsif ($tmp =~ /^(error)/) {
 9529: 	    $result=undef;
 9530: 	    &do_cache_new('courseres',$hashid,$result,600);
 9531: 	}
 9532:     }
 9533:     return $result;
 9534: }
 9535: 
 9536: sub devalidateuserresdata {
 9537:     my ($uname,$udom)=@_;
 9538:     my $hashid="$udom:$uname";
 9539:     &devalidate_cache_new('userres',$hashid);
 9540: }
 9541: 
 9542: sub get_userresdata {
 9543:     my ($uname,$udom)=@_;
 9544:     #most student don\'t have any data set, check if there is some data
 9545:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9546: 
 9547:     my $hashid="$udom:$uname";
 9548:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9549:     if (!defined($cached)) {
 9550: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9551: 	$result=\%resourcedata;
 9552: 	&do_cache_new('userres',$hashid,$result,600);
 9553:     }
 9554:     my ($tmp)=keys(%$result);
 9555:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9556: 	return $result;
 9557:     }
 9558:     #error 2 occurs when the .db doesn't exist
 9559:     if ($tmp!~/error: 2 /) {
 9560: 	&logthis("<font color=\"blue\">WARNING:".
 9561: 		 " Trying to get resource data for ".
 9562: 		 $uname." at ".$udom.": ".
 9563: 		 $tmp."</font>");
 9564:     } elsif ($tmp=~/error: 2 /) {
 9565: 	#&EXT_cache_set($udom,$uname);
 9566: 	&do_cache_new('userres',$hashid,undef,600);
 9567: 	undef($tmp); # not really an error so don't send it back
 9568:     }
 9569:     return $tmp;
 9570: }
 9571: #----------------------------------------------- resdata - return resource data
 9572: #  Purpose:
 9573: #    Return resource data for either users or for a course.
 9574: #  Parameters:
 9575: #     $name      - Course/user name.
 9576: #     $domain    - Name of the domain the user/course is registered on.
 9577: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9578: #     @which     - Array of names of resources desired.
 9579: #  Returns:
 9580: #     The value of the first reasource in @which that is found in the
 9581: #     resource hash.
 9582: #  Exceptional Conditions:
 9583: #     If the $type passed in is not valid (not the string 'course' or 
 9584: #     'user', an undefined  reference is returned.
 9585: #     If none of the resources are found, an undef is returned
 9586: sub resdata {
 9587:     my ($name,$domain,$type,@which)=@_;
 9588:     my $result;
 9589:     if ($type eq 'course') {
 9590: 	$result=&get_courseresdata($name,$domain);
 9591:     } elsif ($type eq 'user') {
 9592: 	$result=&get_userresdata($name,$domain);
 9593:     }
 9594:     if (!ref($result)) { return $result; }    
 9595:     foreach my $item (@which) {
 9596: 	if (defined($result->{$item->[0]})) {
 9597: 	    return [$result->{$item->[0]},$item->[1]];
 9598: 	}
 9599:     }
 9600:     return undef;
 9601: }
 9602: 
 9603: #
 9604: # EXT resource caching routines
 9605: #
 9606: 
 9607: sub clear_EXT_cache_status {
 9608:     &delenv('cache.EXT.');
 9609: }
 9610: 
 9611: sub EXT_cache_status {
 9612:     my ($target_domain,$target_user) = @_;
 9613:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9614:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9615:         # We know already the user has no data
 9616:         return 1;
 9617:     } else {
 9618:         return 0;
 9619:     }
 9620: }
 9621: 
 9622: sub EXT_cache_set {
 9623:     my ($target_domain,$target_user) = @_;
 9624:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9625:     #&appenv({$cachename => time});
 9626: }
 9627: 
 9628: # --------------------------------------------------------- Value of a Variable
 9629: sub EXT {
 9630: 
 9631:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9632:     unless ($varname) { return ''; }
 9633:     #get real user name/domain, courseid and symb
 9634:     my $courseid;
 9635:     my $publicuser;
 9636:     if ($symbparm) {
 9637: 	$symbparm=&get_symb_from_alias($symbparm);
 9638:     }
 9639:     if (!($uname && $udom)) {
 9640:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9641:       if (!$symbparm) {	$symbparm=$cursymb; }
 9642:     } else {
 9643: 	$courseid=$env{'request.course.id'};
 9644:     }
 9645:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9646:     my $rest;
 9647:     if (defined($therest[0])) {
 9648:        $rest=join('.',@therest);
 9649:     } else {
 9650:        $rest='';
 9651:     }
 9652: 
 9653:     my $qualifierrest=$qualifier;
 9654:     if ($rest) { $qualifierrest.='.'.$rest; }
 9655:     my $spacequalifierrest=$space;
 9656:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9657:     if ($realm eq 'user') {
 9658: # --------------------------------------------------------------- user.resource
 9659: 	if ($space eq 'resource') {
 9660: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9661: 		  || defined($Apache::lonhomework::parsing_a_task))
 9662: 		 &&
 9663: 		 ($symbparm eq &symbread()) ) {	
 9664: 		# if we are in the middle of processing the resource the
 9665: 		# get the value we are planning on committing
 9666:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9667:                     return $Apache::lonhomework::results{$qualifierrest};
 9668:                 } else {
 9669:                     return $Apache::lonhomework::history{$qualifierrest};
 9670:                 }
 9671: 	    } else {
 9672: 		my %restored;
 9673: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9674: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9675: 		} else {
 9676: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9677: 		}
 9678: 		return $restored{$qualifierrest};
 9679: 	    }
 9680: # ----------------------------------------------------------------- user.access
 9681:         } elsif ($space eq 'access') {
 9682: 	    # FIXME - not supporting calls for a specific user
 9683:             return &allowed($qualifier,$rest);
 9684: # ------------------------------------------ user.preferences, user.environment
 9685:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9686: 	    if (($uname eq $env{'user.name'}) &&
 9687: 		($udom eq $env{'user.domain'})) {
 9688: 		return $env{join('.',('environment',$qualifierrest))};
 9689: 	    } else {
 9690: 		my %returnhash;
 9691: 		if (!$publicuser) {
 9692: 		    %returnhash=&userenvironment($udom,$uname,
 9693: 						 $qualifierrest);
 9694: 		}
 9695: 		return $returnhash{$qualifierrest};
 9696: 	    }
 9697: # ----------------------------------------------------------------- user.course
 9698:         } elsif ($space eq 'course') {
 9699: 	    # FIXME - not supporting calls for a specific user
 9700:             return $env{join('.',('request.course',$qualifier))};
 9701: # ------------------------------------------------------------------- user.role
 9702:         } elsif ($space eq 'role') {
 9703: 	    # FIXME - not supporting calls for a specific user
 9704:             my ($role,$where)=split(/\./,$env{'request.role'});
 9705:             if ($qualifier eq 'value') {
 9706: 		return $role;
 9707:             } elsif ($qualifier eq 'extent') {
 9708:                 return $where;
 9709:             }
 9710: # ----------------------------------------------------------------- user.domain
 9711:         } elsif ($space eq 'domain') {
 9712:             return $udom;
 9713: # ------------------------------------------------------------------- user.name
 9714:         } elsif ($space eq 'name') {
 9715:             return $uname;
 9716: # ---------------------------------------------------- Any other user namespace
 9717:         } else {
 9718: 	    my %reply;
 9719: 	    if (!$publicuser) {
 9720: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9721: 	    }
 9722: 	    return $reply{$qualifierrest};
 9723:         }
 9724:     } elsif ($realm eq 'query') {
 9725: # ---------------------------------------------- pull stuff out of query string
 9726:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9727: 						[$spacequalifierrest]);
 9728: 	return $env{'form.'.$spacequalifierrest}; 
 9729:    } elsif ($realm eq 'request') {
 9730: # ------------------------------------------------------------- request.browser
 9731:         if ($space eq 'browser') {
 9732:             return $env{'browser.'.$qualifier};
 9733: # ------------------------------------------------------------ request.filename
 9734:         } else {
 9735:             return $env{'request.'.$spacequalifierrest};
 9736:         }
 9737:     } elsif ($realm eq 'course') {
 9738: # ---------------------------------------------------------- course.description
 9739:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9740:     } elsif ($realm eq 'resource') {
 9741: 
 9742: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9743: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9744: 	}
 9745: 
 9746: 	if ($space eq 'title') {
 9747: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9748: 	    return &gettitle($symbparm);
 9749: 	}
 9750: 	
 9751: 	if ($space eq 'map') {
 9752: 	    my ($map) = &decode_symb($symbparm);
 9753: 	    return &symbread($map);
 9754: 	}
 9755: 	if ($space eq 'filename') {
 9756: 	    if ($symbparm) {
 9757: 		return &clutter((&decode_symb($symbparm))[2]);
 9758: 	    }
 9759: 	    return &hreflocation('',$env{'request.filename'});
 9760: 	}
 9761: 
 9762: 	my ($section, $group, @groups);
 9763: 	my ($courselevelm,$courselevel);
 9764:         if (($courseid eq '') && ($cid)) {
 9765:             $courseid = $cid;
 9766:         }
 9767: 	if (($symbparm && $courseid) && 
 9768: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9769: 
 9770: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9771: 
 9772: # ----------------------------------------------------- Cascading lookup scheme
 9773: 	    my $symbp=$symbparm;
 9774: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9775: 
 9776: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9777: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9778: 
 9779: 	    if (($env{'user.name'} eq $uname) &&
 9780: 		($env{'user.domain'} eq $udom)) {
 9781: 		$section=$env{'request.course.sec'};
 9782:                 @groups = split(/:/,$env{'request.course.groups'});  
 9783:                 @groups=&sort_course_groups($courseid,@groups); 
 9784: 	    } else {
 9785: 		if (! defined($usection)) {
 9786: 		    $section=&getsection($udom,$uname,$courseid);
 9787: 		} else {
 9788: 		    $section = $usection;
 9789: 		}
 9790:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9791: 	    }
 9792: 
 9793: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9794: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9795: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9796: 
 9797: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9798: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9799: 	    $courselevelm=$courseid.'.'.$mapparm;
 9800: 
 9801: # ----------------------------------------------------------- first, check user
 9802: 
 9803: 	    my $userreply=&resdata($uname,$udom,'user',
 9804: 				       ([$courselevelr,'resource'],
 9805: 					[$courselevelm,'map'     ],
 9806: 					[$courselevel, 'course'  ]));
 9807: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9808: 
 9809: # ------------------------------------------------ second, check some of course
 9810:             my $coursereply;
 9811:             if (@groups > 0) {
 9812:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9813:                                        $mapparm,$spacequalifierrest);
 9814:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9815:             }
 9816: 
 9817: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9818: 				  $env{'course.'.$courseid.'.domain'},
 9819: 				  'course',
 9820: 				  ([$seclevelr,   'resource'],
 9821: 				   [$seclevelm,   'map'     ],
 9822: 				   [$seclevel,    'course'  ],
 9823: 				   [$courselevelr,'resource']));
 9824: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9825: 
 9826: # ------------------------------------------------------ third, check map parms
 9827: 	    my %parmhash=();
 9828: 	    my $thisparm='';
 9829: 	    if (tie(%parmhash,'GDBM_File',
 9830: 		    $env{'request.course.fn'}.'_parms.db',
 9831: 		    &GDBM_READER(),0640)) {
 9832: 		$thisparm=$parmhash{$symbparm};
 9833: 		untie(%parmhash);
 9834: 	    }
 9835: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9836: 	}
 9837: # ------------------------------------------ fourth, look in resource metadata
 9838: 
 9839: 	$spacequalifierrest=~s/\./\_/;
 9840: 	my $filename;
 9841: 	if (!$symbparm) { $symbparm=&symbread(); }
 9842: 	if ($symbparm) {
 9843: 	    $filename=(&decode_symb($symbparm))[2];
 9844: 	} else {
 9845: 	    $filename=$env{'request.filename'};
 9846: 	}
 9847: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9848: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9849: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9850: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9851: 
 9852: # ---------------------------------------------- fourth, look in rest of course
 9853: 	if ($symbparm && defined($courseid) && 
 9854: 	    $courseid eq $env{'request.course.id'}) {
 9855: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9856: 				     $env{'course.'.$courseid.'.domain'},
 9857: 				     'course',
 9858: 				     ([$courselevelm,'map'   ],
 9859: 				      [$courselevel, 'course']));
 9860: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9861: 	}
 9862: # ------------------------------------------------------------------ Cascade up
 9863: 	unless ($space eq '0') {
 9864: 	    my @parts=split(/_/,$space);
 9865: 	    my $id=pop(@parts);
 9866: 	    my $part=join('_',@parts);
 9867: 	    if ($part eq '') { $part='0'; }
 9868: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9869: 				 $symbparm,$udom,$uname,$section,1);
 9870: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9871: 	}
 9872: 	if ($recurse) { return undef; }
 9873: 	my $pack_def=&packages_tab_default($filename,$varname);
 9874: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9875: # ---------------------------------------------------- Any other user namespace
 9876:     } elsif ($realm eq 'environment') {
 9877: # ----------------------------------------------------------------- environment
 9878: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9879: 	    return $env{'environment.'.$spacequalifierrest};
 9880: 	} else {
 9881: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9882: 		return '';
 9883: 	    }
 9884: 	    my %returnhash=&userenvironment($udom,$uname,
 9885: 					    $spacequalifierrest);
 9886: 	    return $returnhash{$spacequalifierrest};
 9887: 	}
 9888:     } elsif ($realm eq 'system') {
 9889: # ----------------------------------------------------------------- system.time
 9890: 	if ($space eq 'time') {
 9891: 	    return time;
 9892:         }
 9893:     } elsif ($realm eq 'server') {
 9894: # ----------------------------------------------------------------- system.time
 9895: 	if ($space eq 'name') {
 9896: 	    return $ENV{'SERVER_NAME'};
 9897:         }
 9898:     }
 9899:     return '';
 9900: }
 9901: 
 9902: sub get_reply {
 9903:     my ($reply_value) = @_;
 9904:     if (ref($reply_value) eq 'ARRAY') {
 9905:         if (wantarray) {
 9906: 	    return @$reply_value;
 9907:         }
 9908:         return $reply_value->[0];
 9909:     } else {
 9910:         return $reply_value;
 9911:     }
 9912: }
 9913: 
 9914: sub check_group_parms {
 9915:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9916:     my @groupitems = ();
 9917:     my $resultitem;
 9918:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9919:     foreach my $group (@{$groups}) {
 9920:         foreach my $level (@levels) {
 9921:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9922:              push(@groupitems,[$item,$level->[1]]);
 9923:         }
 9924:     }
 9925:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9926:                             $env{'course.'.$courseid.'.domain'},
 9927:                                      'course',@groupitems);
 9928:     return $coursereply;
 9929: }
 9930: 
 9931: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9932:     my ($courseid,@groups) = @_;
 9933:     @groups = sort(@groups);
 9934:     return @groups;
 9935: }
 9936: 
 9937: sub packages_tab_default {
 9938:     my ($uri,$varname)=@_;
 9939:     my (undef,$part,$name)=split(/\./,$varname);
 9940: 
 9941:     my (@extension,@specifics,$do_default);
 9942:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9943: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9944: 	if ($pack_type eq 'default') {
 9945: 	    $do_default=1;
 9946: 	} elsif ($pack_type eq 'extension') {
 9947: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9948: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9949: 	    # only look at packages defaults for packages that this id is
 9950: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9951: 	}
 9952:     }
 9953:     # first look for a package that matches the requested part id
 9954:     foreach my $package (@specifics) {
 9955: 	my (undef,$pack_type,$pack_part)=@{$package};
 9956: 	next if ($pack_part ne $part);
 9957: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9958: 	    return $packagetab{"$pack_type&$name&default"};
 9959: 	}
 9960:     }
 9961:     # look for any possible matching non extension_ package
 9962:     foreach my $package (@specifics) {
 9963: 	my (undef,$pack_type,$pack_part)=@{$package};
 9964: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9965: 	    return $packagetab{"$pack_type&$name&default"};
 9966: 	}
 9967: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9968: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9969: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9970: 	}
 9971:     }
 9972:     # look for any posible extension_ match
 9973:     foreach my $package (@extension) {
 9974: 	my ($package,$pack_type)=@{$package};
 9975: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9976: 	    return $packagetab{"$pack_type&$name&default"};
 9977: 	}
 9978: 	if (defined($packagetab{$package."&$name&default"})) {
 9979: 	    return $packagetab{$package."&$name&default"};
 9980: 	}
 9981:     }
 9982:     # look for a global default setting
 9983:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9984: 	return $packagetab{"default&$name&default"};
 9985:     }
 9986:     return undef;
 9987: }
 9988: 
 9989: sub add_prefix_and_part {
 9990:     my ($prefix,$part)=@_;
 9991:     my $keyroot;
 9992:     if (defined($prefix) && $prefix !~ /^__/) {
 9993: 	# prefix that has a part already
 9994: 	$keyroot=$prefix;
 9995:     } elsif (defined($prefix)) {
 9996: 	# prefix that is missing a part
 9997: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9998:     } else {
 9999: 	# no prefix at all
10000: 	if (defined($part)) { $keyroot='_'.$part; }
10001:     }
10002:     return $keyroot;
10003: }
10004: 
10005: # ---------------------------------------------------------------- Get metadata
10006: 
10007: my %metaentry;
10008: my %importedpartids;
10009: sub metadata {
10010:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10011:     $uri=&declutter($uri);
10012:     # if it is a non metadata possible uri return quickly
10013:     if (($uri eq '') || 
10014: 	(($uri =~ m|^/*adm/|) && 
10015: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10016:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10017: 	return undef;
10018:     }
10019:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10020: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10021: 	return undef;
10022:     }
10023:     my $filename=$uri;
10024:     $uri=~s/\.meta$//;
10025: #
10026: # Is the metadata already cached?
10027: # Look at timestamp of caching
10028: # Everything is cached by the main uri, libraries are never directly cached
10029: #
10030:     if (!defined($liburi)) {
10031: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10032: 	if (defined($cached)) { return $result->{':'.$what}; }
10033:     }
10034:     {
10035: # Imported parts would go here
10036:         my %importedids=();
10037:         my @origfileimportpartids=();
10038:         my $importedparts=0;
10039: #
10040: # Is this a recursive call for a library?
10041: #
10042: #	if (! exists($metacache{$uri})) {
10043: #	    $metacache{$uri}={};
10044: #	}
10045: 	my $cachetime = 60*60;
10046:         if ($liburi) {
10047: 	    $liburi=&declutter($liburi);
10048:             $filename=$liburi;
10049:         } else {
10050: 	    &devalidate_cache_new('meta',$uri);
10051: 	    undef(%metaentry);
10052: 	}
10053:         my %metathesekeys=();
10054:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10055: 	my $metastring;
10056: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10057: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10058: 	    $metastring = 
10059: 		&Apache::lonnet::ssi_body($which,
10060: 					  ('grade_target' => 'meta'));
10061: 	    $cachetime = 1; # only want this cached in the child not long term
10062: 	} elsif (($uri !~ m -^(editupload)/-) && 
10063:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10064: 	    my $file=&filelocation('',&clutter($filename));
10065: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10066: 	    $metastring=&getfile($file);
10067: 	}
10068:         my $parser=HTML::LCParser->new(\$metastring);
10069:         my $token;
10070:         undef %metathesekeys;
10071:         while ($token=$parser->get_token) {
10072: 	    if ($token->[0] eq 'S') {
10073: 		if (defined($token->[2]->{'package'})) {
10074: #
10075: # This is a package - get package info
10076: #
10077: 		    my $package=$token->[2]->{'package'};
10078: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10079: 		    if (defined($token->[2]->{'id'})) { 
10080: 			$keyroot.='_'.$token->[2]->{'id'}; 
10081: 		    }
10082: 		    if ($metaentry{':packages'}) {
10083: 			$metaentry{':packages'}.=','.$package.$keyroot;
10084: 		    } else {
10085: 			$metaentry{':packages'}=$package.$keyroot;
10086: 		    }
10087: 		    foreach my $pack_entry (keys(%packagetab)) {
10088: 			my $part=$keyroot;
10089: 			$part=~s/^\_//;
10090: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10091: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10092: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10093: 			    # ignore package.tab specified default values
10094:                             # here &package_tab_default() will fetch those
10095: 			    if ($subp eq 'default') { next; }
10096: 			    my $value=$packagetab{$pack_entry};
10097: 			    my $unikey;
10098: 			    if ($pack =~ /_0$/) {
10099: 				$unikey='parameter_0_'.$name;
10100: 				$part=0;
10101: 			    } else {
10102: 				$unikey='parameter'.$keyroot.'_'.$name;
10103: 			    }
10104: 			    if ($subp eq 'display') {
10105: 				$value.=' [Part: '.$part.']';
10106: 			    }
10107: 			    $metaentry{':'.$unikey.'.part'}=$part;
10108: 			    $metathesekeys{$unikey}=1;
10109: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10110: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10111: 			    }
10112: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10113: 				$metaentry{':'.$unikey}=
10114: 				    $metaentry{':'.$unikey.'.default'};
10115: 			    }
10116: 			}
10117: 		    }
10118: 		} else {
10119: #
10120: # This is not a package - some other kind of start tag
10121: #
10122: 		    my $entry=$token->[1];
10123: 		    my $unikey='';
10124: 
10125: 		    if ($entry eq 'import') {
10126: #
10127: # Importing a library here
10128: #
10129:                         my $location=$parser->get_text('/import');
10130:                         my $dir=$filename;
10131:                         $dir=~s|[^/]*$||;
10132:                         $location=&filelocation($dir,$location);
10133:                        
10134:                         my $importmode=$token->[2]->{'importmode'};
10135:                         if ($importmode eq 'problem') {
10136: # Import as problem/response
10137:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10138:                         } elsif ($importmode eq 'part') {
10139: # Import as part(s)
10140:                            $importedparts=1;
10141: # We need to get the original file and the imported file to get the part order correct
10142: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10143: # Load and inspect original file
10144:                            if ($#origfileimportpartids<0) {
10145:                               undef(%importedpartids);
10146:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10147:                               my $origfile=&getfile($origfilelocation);
10148:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10149:                            }
10150: 
10151: # Load and inspect imported file
10152:                            my $impfile=&getfile($location);
10153:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10154:                            if ($#impfilepartids>=0) {
10155: # This problem had parts
10156:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10157:                            } else {
10158: # Importing by turning a single problem into a problem part
10159: # It gets the import-tags ID as part-ID
10160:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10161:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10162:                            }
10163:                         } else {
10164: # Normal import
10165:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10166:                            if (defined($token->[2]->{'id'})) {
10167:                               $unikey.='_'.$token->[2]->{'id'};
10168:                            }
10169:                         }
10170: 
10171: 			if ($depthcount<20) {
10172: 			    my $metadata = 
10173: 				&metadata($uri,'keys', $location,$unikey,
10174: 					  $depthcount+1);
10175: 			    foreach my $meta (split(',',$metadata)) {
10176: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10177: 				$metathesekeys{$meta}=1;
10178: 			    }
10179: 			
10180:                         }
10181: 		    } else {
10182: #
10183: # Not importing, some other kind of non-package, non-library start tag
10184: # 
10185:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10186:                         if (defined($token->[2]->{'id'})) {
10187:                             $unikey.='_'.$token->[2]->{'id'};
10188:                         }
10189: 			if (defined($token->[2]->{'name'})) { 
10190: 			    $unikey.='_'.$token->[2]->{'name'}; 
10191: 			}
10192: 			$metathesekeys{$unikey}=1;
10193: 			foreach my $param (@{$token->[3]}) {
10194: 			    $metaentry{':'.$unikey.'.'.$param} =
10195: 				$token->[2]->{$param};
10196: 			}
10197: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10198: 			my $default=$metaentry{':'.$unikey.'.default'};
10199: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10200: 		 # only ws inside the tag, and not in default, so use default
10201: 		 # as value
10202: 			    $metaentry{':'.$unikey}=$default;
10203: 			} elsif ( $internaltext =~ /\S/ ) {
10204: 		  # something interesting inside the tag
10205: 			    $metaentry{':'.$unikey}=$internaltext;
10206: 			} else {
10207: 		  # no interesting values, don't set a default
10208: 			}
10209: # end of not-a-package not-a-library import
10210: 		    }
10211: # end of not-a-package start tag
10212: 		}
10213: # the next is the end of "start tag"
10214: 	    }
10215: 	}
10216: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10217: 	$extension = lc($extension);
10218: 	if ($extension eq 'htm') { $extension='html'; }
10219: 
10220: 	foreach my $key (keys(%packagetab)) {
10221: 	    #no specific packages #how's our extension
10222: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10223: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10224: 					 \%metathesekeys);
10225: 	}
10226: 
10227: 	if (!exists($metaentry{':packages'})
10228: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10229: 	    foreach my $key (keys(%packagetab)) {
10230: 		#no specific packages well let's get default then
10231: 		if ($key!~/^default&/) { next; }
10232: 		&metadata_create_package_def($uri,$key,'default',
10233: 					     \%metathesekeys);
10234: 	    }
10235: 	}
10236: # are there custom rights to evaluate
10237: 	if ($metaentry{':copyright'} eq 'custom') {
10238: 
10239:     #
10240:     # Importing a rights file here
10241:     #
10242: 	    unless ($depthcount) {
10243: 		my $location=$metaentry{':customdistributionfile'};
10244: 		my $dir=$filename;
10245: 		$dir=~s|[^/]*$||;
10246: 		$location=&filelocation($dir,$location);
10247: 		my $rights_metadata =
10248: 		    &metadata($uri,'keys',$location,'_rights',
10249: 			      $depthcount+1);
10250: 		foreach my $rights (split(',',$rights_metadata)) {
10251: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10252: 		    $metathesekeys{$rights}=1;
10253: 		}
10254: 	    }
10255: 	}
10256: 	# uniqifiy package listing
10257: 	my %seen;
10258: 	my @uniq_packages =
10259: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10260: 	$metaentry{':packages'} = join(',',@uniq_packages);
10261: 
10262:         if ($importedparts) {
10263: # We had imported parts and need to rebuild partorder
10264:            $metaentry{':partorder'}='';
10265:            $metathesekeys{'partorder'}=1;
10266:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10267:                if ($origfileimportpartids[$index] eq 'part') {
10268: # original part, part of the problem
10269:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10270:                } else {
10271: # we have imported parts at this position
10272:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10273:                }
10274:            }
10275:            $metaentry{':partorder'}=~s/^\,//;
10276:         }
10277: 
10278: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10279: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10280: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10281: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10282: # this is the end of "was not already recently cached
10283:     }
10284:     return $metaentry{':'.$what};
10285: }
10286: 
10287: sub metadata_create_package_def {
10288:     my ($uri,$key,$package,$metathesekeys)=@_;
10289:     my ($pack,$name,$subp)=split(/\&/,$key);
10290:     if ($subp eq 'default') { next; }
10291:     
10292:     if (defined($metaentry{':packages'})) {
10293: 	$metaentry{':packages'}.=','.$package;
10294:     } else {
10295: 	$metaentry{':packages'}=$package;
10296:     }
10297:     my $value=$packagetab{$key};
10298:     my $unikey;
10299:     $unikey='parameter_0_'.$name;
10300:     $metaentry{':'.$unikey.'.part'}=0;
10301:     $$metathesekeys{$unikey}=1;
10302:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10303: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10304:     }
10305:     if (defined($metaentry{':'.$unikey.'.default'})) {
10306: 	$metaentry{':'.$unikey}=
10307: 	    $metaentry{':'.$unikey.'.default'};
10308:     }
10309: }
10310: 
10311: sub metadata_generate_part0 {
10312:     my ($metadata,$metacache,$uri) = @_;
10313:     my %allnames;
10314:     foreach my $metakey (keys(%$metadata)) {
10315: 	if ($metakey=~/^parameter\_(.*)/) {
10316: 	  my $part=$$metacache{':'.$metakey.'.part'};
10317: 	  my $name=$$metacache{':'.$metakey.'.name'};
10318: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10319: 	    $allnames{$name}=$part;
10320: 	  }
10321: 	}
10322:     }
10323:     foreach my $name (keys(%allnames)) {
10324:       $$metadata{"parameter_0_$name"}=1;
10325:       my $key=":parameter_0_$name";
10326:       $$metacache{"$key.part"}='0';
10327:       $$metacache{"$key.name"}=$name;
10328:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10329: 					   $allnames{$name}.'_'.$name.
10330: 					   '.type'};
10331:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10332: 			     '.display'};
10333:       my $expr='[Part: '.$allnames{$name}.']';
10334:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10335:       $$metacache{"$key.display"}=$olddis;
10336:     }
10337: }
10338: 
10339: # ------------------------------------------------------ Devalidate title cache
10340: 
10341: sub devalidate_title_cache {
10342:     my ($url)=@_;
10343:     if (!$env{'request.course.id'}) { return; }
10344:     my $symb=&symbread($url);
10345:     if (!$symb) { return; }
10346:     my $key=$env{'request.course.id'}."\0".$symb;
10347:     &devalidate_cache_new('title',$key);
10348: }
10349: 
10350: # ------------------------------------------------- Get the title of a course
10351: 
10352: sub current_course_title {
10353:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10354: }
10355: # ------------------------------------------------- Get the title of a resource
10356: 
10357: sub gettitle {
10358:     my $urlsymb=shift;
10359:     my $symb=&symbread($urlsymb);
10360:     if ($symb) {
10361: 	my $key=$env{'request.course.id'}."\0".$symb;
10362: 	my ($result,$cached)=&is_cached_new('title',$key);
10363: 	if (defined($cached)) { 
10364: 	    return $result;
10365: 	}
10366: 	my ($map,$resid,$url)=&decode_symb($symb);
10367: 	my $title='';
10368: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10369: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10370: 	} else {
10371: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10372: 		    &GDBM_READER(),0640)) {
10373: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10374: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10375: 		untie(%bighash);
10376: 	    }
10377: 	}
10378: 	$title=~s/\&colon\;/\:/gs;
10379: 	if ($title) {
10380: # Remember both $symb and $title for dynamic metadata
10381:             $accesshash{$symb.'___crstitle'}=$title;
10382:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10383: # Cache this title and then return it
10384: 	    return &do_cache_new('title',$key,$title,600);
10385: 	}
10386: 	$urlsymb=$url;
10387:     }
10388:     my $title=&metadata($urlsymb,'title');
10389:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10390:     return $title;
10391: }
10392: 
10393: sub get_slot {
10394:     my ($which,$cnum,$cdom)=@_;
10395:     if (!$cnum || !$cdom) {
10396: 	(undef,my $courseid)=&whichuser();
10397: 	$cdom=$env{'course.'.$courseid.'.domain'};
10398: 	$cnum=$env{'course.'.$courseid.'.num'};
10399:     }
10400:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10401:     my %slotinfo;
10402:     if (exists($remembered{$key})) {
10403: 	$slotinfo{$which} = $remembered{$key};
10404:     } else {
10405: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10406: 	&Apache::lonhomework::showhash(%slotinfo);
10407: 	my ($tmp)=keys(%slotinfo);
10408: 	if ($tmp=~/^error:/) { return (); }
10409: 	$remembered{$key} = $slotinfo{$which};
10410:     }
10411:     if (ref($slotinfo{$which}) eq 'HASH') {
10412: 	return %{$slotinfo{$which}};
10413:     }
10414:     return $slotinfo{$which};
10415: }
10416: 
10417: sub get_reservable_slots {
10418:     my ($cnum,$cdom,$uname,$udom) = @_;
10419:     my $now = time;
10420:     my $reservable_info;
10421:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10422:     if (exists($remembered{$key})) {
10423:         $reservable_info = $remembered{$key};
10424:     } else {
10425:         my %resv;
10426:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10427:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10428:         $reservable_info = \%resv;
10429:         $remembered{$key} = $reservable_info;
10430:     }
10431:     return $reservable_info;
10432: }
10433: 
10434: sub get_course_slots {
10435:     my ($cnum,$cdom) = @_;
10436:     my $hashid=$cnum.':'.$cdom;
10437:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10438:     if (defined($cached)) {
10439:         if (ref($result) eq 'HASH') {
10440:             return %{$result};
10441:         }
10442:     } else {
10443:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10444:         my ($tmp) = keys(%slots);
10445:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10446:             &do_cache_new('allslots',$hashid,\%slots,600);
10447:             return %slots;
10448:         }
10449:     }
10450:     return;
10451: }
10452: 
10453: sub devalidate_slots_cache {
10454:     my ($cnum,$cdom)=@_;
10455:     my $hashid=$cnum.':'.$cdom;
10456:     &devalidate_cache_new('allslots',$hashid);
10457: }
10458: 
10459: sub get_coursechange {
10460:     my ($cdom,$cnum) = @_;
10461:     if ($cdom eq '' || $cnum eq '') {
10462:         return unless ($env{'request.course.id'});
10463:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10464:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10465:     }
10466:     my $hashid=$cdom.'_'.$cnum;
10467:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10468:     if ((defined($cached)) && ($change ne '')) {
10469:         return $change;
10470:     } else {
10471:         my %crshash;
10472:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10473:         if ($crshash{'internal.contentchange'} eq '') {
10474:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10475:             if ($change eq '') {
10476:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10477:                 $change = $crshash{'internal.created'};
10478:             }
10479:         } else {
10480:             $change = $crshash{'internal.contentchange'};
10481:         }
10482:         my $cachetime = 600;
10483:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10484:     }
10485:     return $change;
10486: }
10487: 
10488: sub devalidate_coursechange_cache {
10489:     my ($cnum,$cdom)=@_;
10490:     my $hashid=$cnum.':'.$cdom;
10491:     &devalidate_cache_new('crschange',$hashid);
10492: }
10493: 
10494: # ------------------------------------------------- Update symbolic store links
10495: 
10496: sub symblist {
10497:     my ($mapname,%newhash)=@_;
10498:     $mapname=&deversion(&declutter($mapname));
10499:     my %hash;
10500:     if (($env{'request.course.fn'}) && (%newhash)) {
10501:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10502:                       &GDBM_WRCREAT(),0640)) {
10503: 	    foreach my $url (keys(%newhash)) {
10504: 		next if ($url eq 'last_known'
10505: 			 && $env{'form.no_update_last_known'});
10506: 		$hash{declutter($url)}=&encode_symb($mapname,
10507: 						    $newhash{$url}->[1],
10508: 						    $newhash{$url}->[0]);
10509:             }
10510:             if (untie(%hash)) {
10511: 		return 'ok';
10512:             }
10513:         }
10514:     }
10515:     return 'error';
10516: }
10517: 
10518: # --------------------------------------------------------------- Verify a symb
10519: 
10520: sub symbverify {
10521:     my ($symb,$thisurl,$encstate)=@_;
10522:     my $thisfn=$thisurl;
10523:     $thisfn=&declutter($thisfn);
10524: # direct jump to resource in page or to a sequence - will construct own symbs
10525:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10526: # check URL part
10527:     my ($map,$resid,$url)=&decode_symb($symb);
10528: 
10529:     unless ($url eq $thisfn) { return 0; }
10530: 
10531:     $symb=&symbclean($symb);
10532:     $thisurl=&deversion($thisurl);
10533:     $thisfn=&deversion($thisfn);
10534: 
10535:     my %bighash;
10536:     my $okay=0;
10537: 
10538:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10539:                             &GDBM_READER(),0640)) {
10540:         my $noclutter;
10541:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10542:             $thisurl =~ s/\?.+$//;
10543:             if ($map =~ m{^uploaded/.+\.page$}) {
10544:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10545:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10546:                 $noclutter = 1;
10547:             }
10548:         }
10549:         my $ids;
10550:         if ($noclutter) {
10551:             $ids=$bighash{'ids_'.$thisurl};
10552:         } else {
10553:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10554:         }
10555:         unless ($ids) {
10556:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10557:             $ids=$bighash{$idkey};
10558:         }
10559:         if ($ids) {
10560: # ------------------------------------------------------------------- Has ID(s)
10561:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10562:                 $symb =~ s/\?.+$//;
10563:             }
10564: 	    foreach my $id (split(/\,/,$ids)) {
10565: 	       my ($mapid,$resid)=split(/\./,$id);
10566:                if (
10567:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10568:    eq $symb) {
10569:                    if (ref($encstate)) {
10570:                        $$encstate = $bighash{'encrypted_'.$id};
10571:                    }
10572: 		   if (($env{'request.role.adv'}) ||
10573: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10574:                        ($thisurl eq '/adm/navmaps')) {
10575: 		       $okay=1;
10576:                        last;
10577: 		   }
10578: 	       }
10579: 	   }
10580:         }
10581: 	untie(%bighash);
10582:     }
10583:     return $okay;
10584: }
10585: 
10586: # --------------------------------------------------------------- Clean-up symb
10587: 
10588: sub symbclean {
10589:     my $symb=shift;
10590:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10591: # remove version from map
10592:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10593: 
10594: # remove version from URL
10595:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10596: 
10597: # remove wrapper
10598: 
10599:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10600:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10601:     return $symb;
10602: }
10603: 
10604: # ---------------------------------------------- Split symb to find map and url
10605: 
10606: sub encode_symb {
10607:     my ($map,$resid,$url)=@_;
10608:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10609: }
10610: 
10611: sub decode_symb {
10612:     my $symb=shift;
10613:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10614:     my ($map,$resid,$url)=split(/___/,$symb);
10615:     return (&fixversion($map),$resid,&fixversion($url));
10616: }
10617: 
10618: sub fixversion {
10619:     my $fn=shift;
10620:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10621:     my %bighash;
10622:     my $uri=&clutter($fn);
10623:     my $key=$env{'request.course.id'}.'_'.$uri;
10624: # is this cached?
10625:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10626:     if (defined($cached)) { return $result; }
10627: # unfortunately not cached, or expired
10628:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10629: 	    &GDBM_READER(),0640)) {
10630:  	if ($bighash{'version_'.$uri}) {
10631:  	    my $version=$bighash{'version_'.$uri};
10632:  	    unless (($version eq 'mostrecent') || 
10633: 		    ($version==&getversion($uri))) {
10634:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10635:  	    }
10636:  	}
10637:  	untie %bighash;
10638:     }
10639:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10640: }
10641: 
10642: sub deversion {
10643:     my $url=shift;
10644:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10645:     return $url;
10646: }
10647: 
10648: # ------------------------------------------------------ Return symb list entry
10649: 
10650: sub symbread {
10651:     my ($thisfn,$donotrecurse)=@_;
10652:     my $cache_str;
10653:     if ($thisfn ne '') {
10654:         $cache_str='request.symbread.cached.'.$thisfn;
10655:         if ($env{$cache_str} ne '') {
10656:             return $env{$cache_str};
10657:         }
10658:     } else {
10659: # no filename provided? try from environment
10660:         if ($env{'request.symb'}) {
10661: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10662: 	}
10663: 	$thisfn=$env{'request.filename'};
10664:     }
10665:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10666: # is that filename actually a symb? Verify, clean, and return
10667:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10668: 	if (&symbverify($thisfn,$1)) {
10669: 	    return $env{$cache_str}=&symbclean($thisfn);
10670: 	}
10671:     }
10672:     $thisfn=declutter($thisfn);
10673:     my %hash;
10674:     my %bighash;
10675:     my $syval='';
10676:     if (($env{'request.course.fn'}) && ($thisfn)) {
10677:         my $targetfn = $thisfn;
10678:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10679:             $targetfn = 'adm/wrapper/'.$thisfn;
10680:         }
10681: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10682: 	    $targetfn=$1;
10683: 	}
10684:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10685:                       &GDBM_READER(),0640)) {
10686: 	    $syval=$hash{$targetfn};
10687:             untie(%hash);
10688:         }
10689: # ---------------------------------------------------------- There was an entry
10690:         if ($syval) {
10691: 	    #unless ($syval=~/\_\d+$/) {
10692: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10693: 		    #&appenv({'request.ambiguous' => $thisfn});
10694: 		    #return $env{$cache_str}='';
10695: 		#}    
10696: 		#$syval.=$1;
10697: 	    #}
10698:         } else {
10699: # ------------------------------------------------------- Was not in symb table
10700:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10701:                             &GDBM_READER(),0640)) {
10702: # ---------------------------------------------- Get ID(s) for current resource
10703:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10704:               unless ($ids) { 
10705:                  $ids=$bighash{'ids_/'.$thisfn};
10706:               }
10707:               unless ($ids) {
10708: # alias?
10709: 		  $ids=$bighash{'mapalias_'.$thisfn};
10710:               }
10711:               if ($ids) {
10712: # ------------------------------------------------------------------- Has ID(s)
10713:                  my @possibilities=split(/\,/,$ids);
10714:                  if ($#possibilities==0) {
10715: # ----------------------------------------------- There is only one possibility
10716: 		     my ($mapid,$resid)=split(/\./,$ids);
10717: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10718: 						    $resid,$thisfn);
10719:                  } elsif (!$donotrecurse) {
10720: # ------------------------------------------ There is more than one possibility
10721:                      my $realpossible=0;
10722:                      foreach my $id (@possibilities) {
10723: 			 my $file=$bighash{'src_'.$id};
10724:                          if (&allowed('bre',$file)) {
10725:          		    my ($mapid,$resid)=split(/\./,$id);
10726:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10727: 				$realpossible++;
10728:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10729: 						    $resid,$thisfn);
10730:                             }
10731: 			 }
10732:                      }
10733: 		     if ($realpossible!=1) { $syval=''; }
10734:                  } else {
10735:                      $syval='';
10736:                  }
10737: 	      }
10738:               untie(%bighash)
10739:            }
10740:         }
10741:         if ($syval) {
10742: 	    return $env{$cache_str}=$syval;
10743:         }
10744:     }
10745:     &appenv({'request.ambiguous' => $thisfn});
10746:     return $env{$cache_str}='';
10747: }
10748: 
10749: # ---------------------------------------------------------- Return random seed
10750: 
10751: sub numval {
10752:     my $txt=shift;
10753:     $txt=~tr/A-J/0-9/;
10754:     $txt=~tr/a-j/0-9/;
10755:     $txt=~tr/K-T/0-9/;
10756:     $txt=~tr/k-t/0-9/;
10757:     $txt=~tr/U-Z/0-5/;
10758:     $txt=~tr/u-z/0-5/;
10759:     $txt=~s/\D//g;
10760:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10761:     return int($txt);
10762: }
10763: 
10764: sub numval2 {
10765:     my $txt=shift;
10766:     $txt=~tr/A-J/0-9/;
10767:     $txt=~tr/a-j/0-9/;
10768:     $txt=~tr/K-T/0-9/;
10769:     $txt=~tr/k-t/0-9/;
10770:     $txt=~tr/U-Z/0-5/;
10771:     $txt=~tr/u-z/0-5/;
10772:     $txt=~s/\D//g;
10773:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10774:     my $total;
10775:     foreach my $val (@txts) { $total+=$val; }
10776:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10777:     return int($total);
10778: }
10779: 
10780: sub numval3 {
10781:     use integer;
10782:     my $txt=shift;
10783:     $txt=~tr/A-J/0-9/;
10784:     $txt=~tr/a-j/0-9/;
10785:     $txt=~tr/K-T/0-9/;
10786:     $txt=~tr/k-t/0-9/;
10787:     $txt=~tr/U-Z/0-5/;
10788:     $txt=~tr/u-z/0-5/;
10789:     $txt=~s/\D//g;
10790:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10791:     my $total;
10792:     foreach my $val (@txts) { $total+=$val; }
10793:     if ($_64bit) { $total=(($total<<32)>>32); }
10794:     return $total;
10795: }
10796: 
10797: sub digest {
10798:     my ($data)=@_;
10799:     my $digest=&Digest::MD5::md5($data);
10800:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10801:     my ($e,$f);
10802:     {
10803:         use integer;
10804:         $e=($a+$b);
10805:         $f=($c+$d);
10806:         if ($_64bit) {
10807:             $e=(($e<<32)>>32);
10808:             $f=(($f<<32)>>32);
10809:         }
10810:     }
10811:     if (wantarray) {
10812: 	return ($e,$f);
10813:     } else {
10814: 	my $g;
10815: 	{
10816: 	    use integer;
10817: 	    $g=($e+$f);
10818: 	    if ($_64bit) {
10819: 		$g=(($g<<32)>>32);
10820: 	    }
10821: 	}
10822: 	return $g;
10823:     }
10824: }
10825: 
10826: sub latest_rnd_algorithm_id {
10827:     return '64bit5';
10828: }
10829: 
10830: sub get_rand_alg {
10831:     my ($courseid)=@_;
10832:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10833:     if ($courseid) {
10834: 	return $env{"course.$courseid.rndseed"};
10835:     }
10836:     return &latest_rnd_algorithm_id();
10837: }
10838: 
10839: sub validCODE {
10840:     my ($CODE)=@_;
10841:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10842:     return 0;
10843: }
10844: 
10845: sub getCODE {
10846:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10847:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10848: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10849: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10850: 	return $Apache::lonhomework::history{'resource.CODE'};
10851:     }
10852:     return undef;
10853: }
10854: #
10855: #  Determines the random seed for a specific context:
10856: #
10857: # parameters:
10858: #   symb      - in course context the symb for the seed.
10859: #   course_id - The course id of the form domain_coursenum.
10860: #   domain    - Domain for the user.
10861: #   course    - Course for the user.
10862: #   cenv      - environment of the course.
10863: #
10864: # NOTE:
10865: #   All parameters are picked out of the environment if missing
10866: #   or not defined.
10867: #   If a symb cannot be determined the current time is used instead.
10868: #
10869: #  For a given well defined symb, courside, domain, username,
10870: #  and course environment, the seed is reproducible.
10871: #
10872: sub rndseed {
10873:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10874:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10875:     if (!defined($symb)) {
10876: 	unless ($symb=$wsymb) { return time; }
10877:     }
10878:     if (!defined $courseid) { 
10879: 	$courseid=$wcourseid; 
10880:     }
10881:     if (!defined $domain) { $domain=$wdomain; }
10882:     if (!defined $username) { $username=$wusername }
10883: 
10884:     my $which;
10885:     if (defined($cenv->{'rndseed'})) {
10886: 	$which = $cenv->{'rndseed'};
10887:     } else {
10888: 	$which =&get_rand_alg($courseid);
10889:     }
10890:     if (defined(&getCODE())) {
10891: 
10892: 	if ($which eq '64bit5') {
10893: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10894: 	} elsif ($which eq '64bit4') {
10895: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10896: 	} else {
10897: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10898: 	}
10899:     } elsif ($which eq '64bit5') {
10900: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10901:     } elsif ($which eq '64bit4') {
10902: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10903:     } elsif ($which eq '64bit3') {
10904: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10905:     } elsif ($which eq '64bit2') {
10906: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10907:     } elsif ($which eq '64bit') {
10908: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10909:     }
10910:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10911: }
10912: 
10913: sub rndseed_32bit {
10914:     my ($symb,$courseid,$domain,$username)=@_;
10915:     {
10916: 	use integer;
10917: 	my $symbchck=unpack("%32C*",$symb) << 27;
10918: 	my $symbseed=numval($symb) << 22;
10919: 	my $namechck=unpack("%32C*",$username) << 17;
10920: 	my $nameseed=numval($username) << 12;
10921: 	my $domainseed=unpack("%32C*",$domain) << 7;
10922: 	my $courseseed=unpack("%32C*",$courseid);
10923: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10924: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10925: 	#&logthis("rndseed :$num:$symb");
10926: 	if ($_64bit) { $num=(($num<<32)>>32); }
10927: 	return $num;
10928:     }
10929: }
10930: 
10931: sub rndseed_64bit {
10932:     my ($symb,$courseid,$domain,$username)=@_;
10933:     {
10934: 	use integer;
10935: 	my $symbchck=unpack("%32S*",$symb) << 21;
10936: 	my $symbseed=numval($symb) << 10;
10937: 	my $namechck=unpack("%32S*",$username);
10938: 	
10939: 	my $nameseed=numval($username) << 21;
10940: 	my $domainseed=unpack("%32S*",$domain) << 10;
10941: 	my $courseseed=unpack("%32S*",$courseid);
10942: 	
10943: 	my $num1=$symbchck+$symbseed+$namechck;
10944: 	my $num2=$nameseed+$domainseed+$courseseed;
10945: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10946: 	#&logthis("rndseed :$num:$symb");
10947: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10948: 	return "$num1,$num2";
10949:     }
10950: }
10951: 
10952: sub rndseed_64bit2 {
10953:     my ($symb,$courseid,$domain,$username)=@_;
10954:     {
10955: 	use integer;
10956: 	# strings need to be an even # of cahracters long, it it is odd the
10957:         # last characters gets thrown away
10958: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10959: 	my $symbseed=numval($symb) << 10;
10960: 	my $namechck=unpack("%32S*",$username.' ');
10961: 	
10962: 	my $nameseed=numval($username) << 21;
10963: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10964: 	my $courseseed=unpack("%32S*",$courseid.' ');
10965: 	
10966: 	my $num1=$symbchck+$symbseed+$namechck;
10967: 	my $num2=$nameseed+$domainseed+$courseseed;
10968: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10969: 	#&logthis("rndseed :$num:$symb");
10970: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10971: 	return "$num1,$num2";
10972:     }
10973: }
10974: 
10975: sub rndseed_64bit3 {
10976:     my ($symb,$courseid,$domain,$username)=@_;
10977:     {
10978: 	use integer;
10979: 	# strings need to be an even # of cahracters long, it it is odd the
10980:         # last characters gets thrown away
10981: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10982: 	my $symbseed=numval2($symb) << 10;
10983: 	my $namechck=unpack("%32S*",$username.' ');
10984: 	
10985: 	my $nameseed=numval2($username) << 21;
10986: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10987: 	my $courseseed=unpack("%32S*",$courseid.' ');
10988: 	
10989: 	my $num1=$symbchck+$symbseed+$namechck;
10990: 	my $num2=$nameseed+$domainseed+$courseseed;
10991: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10992: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10993: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10994: 	
10995: 	return "$num1:$num2";
10996:     }
10997: }
10998: 
10999: sub rndseed_64bit4 {
11000:     my ($symb,$courseid,$domain,$username)=@_;
11001:     {
11002: 	use integer;
11003: 	# strings need to be an even # of cahracters long, it it is odd the
11004:         # last characters gets thrown away
11005: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11006: 	my $symbseed=numval3($symb) << 10;
11007: 	my $namechck=unpack("%32S*",$username.' ');
11008: 	
11009: 	my $nameseed=numval3($username) << 21;
11010: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11011: 	my $courseseed=unpack("%32S*",$courseid.' ');
11012: 	
11013: 	my $num1=$symbchck+$symbseed+$namechck;
11014: 	my $num2=$nameseed+$domainseed+$courseseed;
11015: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11016: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11017: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11018: 	
11019: 	return "$num1:$num2";
11020:     }
11021: }
11022: 
11023: sub rndseed_64bit5 {
11024:     my ($symb,$courseid,$domain,$username)=@_;
11025:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11026:     return "$num1:$num2";
11027: }
11028: 
11029: sub rndseed_CODE_64bit {
11030:     my ($symb,$courseid,$domain,$username)=@_;
11031:     {
11032: 	use integer;
11033: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11034: 	my $symbseed=numval2($symb);
11035: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11036: 	my $CODEseed=numval(&getCODE());
11037: 	my $courseseed=unpack("%32S*",$courseid.' ');
11038: 	my $num1=$symbseed+$CODEchck;
11039: 	my $num2=$CODEseed+$courseseed+$symbchck;
11040: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11041: 	#&logthis("rndseed :$num1:$num2:$symb");
11042: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11043: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11044: 	return "$num1:$num2";
11045:     }
11046: }
11047: 
11048: sub rndseed_CODE_64bit4 {
11049:     my ($symb,$courseid,$domain,$username)=@_;
11050:     {
11051: 	use integer;
11052: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11053: 	my $symbseed=numval3($symb);
11054: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11055: 	my $CODEseed=numval3(&getCODE());
11056: 	my $courseseed=unpack("%32S*",$courseid.' ');
11057: 	my $num1=$symbseed+$CODEchck;
11058: 	my $num2=$CODEseed+$courseseed+$symbchck;
11059: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11060: 	#&logthis("rndseed :$num1:$num2:$symb");
11061: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11062: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11063: 	return "$num1:$num2";
11064:     }
11065: }
11066: 
11067: sub rndseed_CODE_64bit5 {
11068:     my ($symb,$courseid,$domain,$username)=@_;
11069:     my $code = &getCODE();
11070:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11071:     return "$num1:$num2";
11072: }
11073: 
11074: sub setup_random_from_rndseed {
11075:     my ($rndseed)=@_;
11076:     if ($rndseed =~/([,:])/) {
11077: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11078: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11079:     } else {
11080: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11081:     }
11082: }
11083: 
11084: sub latest_receipt_algorithm_id {
11085:     return 'receipt3';
11086: }
11087: 
11088: sub recunique {
11089:     my $fucourseid=shift;
11090:     my $unique;
11091:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11092: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11093: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11094:     } else {
11095: 	$unique=$perlvar{'lonReceipt'};
11096:     }
11097:     return unpack("%32C*",$unique);
11098: }
11099: 
11100: sub recprefix {
11101:     my $fucourseid=shift;
11102:     my $prefix;
11103:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11104: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11105: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11106:     } else {
11107: 	$prefix=$perlvar{'lonHostID'};
11108:     }
11109:     return unpack("%32C*",$prefix);
11110: }
11111: 
11112: sub ireceipt {
11113:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11114: 
11115:     my $return =&recprefix($fucourseid).'-';
11116: 
11117:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11118: 	$env{'request.state'} eq 'construct') {
11119: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11120: 	return $return;
11121:     }
11122: 
11123:     my $cuname=unpack("%32C*",$funame);
11124:     my $cudom=unpack("%32C*",$fudom);
11125:     my $cucourseid=unpack("%32C*",$fucourseid);
11126:     my $cusymb=unpack("%32C*",$fusymb);
11127:     my $cunique=&recunique($fucourseid);
11128:     my $cpart=unpack("%32S*",$part);
11129:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11130: 
11131: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11132: 			       
11133: 	$return.= ($cunique%$cuname+
11134: 		   $cunique%$cudom+
11135: 		   $cusymb%$cuname+
11136: 		   $cusymb%$cudom+
11137: 		   $cucourseid%$cuname+
11138: 		   $cucourseid%$cudom+
11139: 		   $cpart%$cuname+
11140: 		   $cpart%$cudom);
11141:     } else {
11142: 	$return.= ($cunique%$cuname+
11143: 		   $cunique%$cudom+
11144: 		   $cusymb%$cuname+
11145: 		   $cusymb%$cudom+
11146: 		   $cucourseid%$cuname+
11147: 		   $cucourseid%$cudom);
11148:     }
11149:     return $return;
11150: }
11151: 
11152: sub receipt {
11153:     my ($part)=@_;
11154:     my ($symb,$courseid,$domain,$name) = &whichuser();
11155:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11156: }
11157: 
11158: sub whichuser {
11159:     my ($passedsymb)=@_;
11160:     my ($symb,$courseid,$domain,$name,$publicuser);
11161:     if (defined($env{'form.grade_symb'})) {
11162: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11163: 	my $allowed=&allowed('vgr',$tmp_courseid);
11164: 	if (!$allowed &&
11165: 	    exists($env{'request.course.sec'}) &&
11166: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11167: 	    $allowed=&allowed('vgr',$tmp_courseid.
11168: 			      '/'.$env{'request.course.sec'});
11169: 	}
11170: 	if ($allowed) {
11171: 	    ($symb)=&get_env_multiple('form.grade_symb');
11172: 	    $courseid=$tmp_courseid;
11173: 	    ($domain)=&get_env_multiple('form.grade_domain');
11174: 	    ($name)=&get_env_multiple('form.grade_username');
11175: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11176: 	}
11177:     }
11178:     if (!$passedsymb) {
11179: 	$symb=&symbread();
11180:     } else {
11181: 	$symb=$passedsymb;
11182:     }
11183:     $courseid=$env{'request.course.id'};
11184:     $domain=$env{'user.domain'};
11185:     $name=$env{'user.name'};
11186:     if ($name eq 'public' && $domain eq 'public') {
11187: 	if (!defined($env{'form.username'})) {
11188: 	    $env{'form.username'}.=time.rand(10000000);
11189: 	}
11190: 	$name.=$env{'form.username'};
11191:     }
11192:     return ($symb,$courseid,$domain,$name,$publicuser);
11193: 
11194: }
11195: 
11196: # ------------------------------------------------------------ Serves up a file
11197: # returns either the contents of the file or 
11198: # -1 if the file doesn't exist
11199: #
11200: # if the target is a file that was uploaded via DOCS, 
11201: # a check will be made to see if a current copy exists on the local server,
11202: # if it does this will be served, otherwise a copy will be retrieved from
11203: # the home server for the course and stored in /home/httpd/html/userfiles on
11204: # the local server.   
11205: 
11206: sub getfile {
11207:     my ($file) = @_;
11208:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11209:     &repcopy($file);
11210:     return &readfile($file);
11211: }
11212: 
11213: sub repcopy_userfile {
11214:     my ($file)=@_;
11215:     my $londocroot = $perlvar{'lonDocRoot'};
11216:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11217:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11218:     my ($cdom,$cnum,$filename) = 
11219: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11220:     my $uri="/uploaded/$cdom/$cnum/$filename";
11221:     if (-e "$file") {
11222: # we already have a local copy, check it out
11223: 	my @fileinfo = stat($file);
11224: 	my $rtncode;
11225: 	my $info;
11226: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11227: 	if ($lwpresp ne 'ok') {
11228: # there is no such file anymore, even though we had a local copy
11229: 	    if ($rtncode eq '404') {
11230: 		unlink($file);
11231: 	    }
11232: 	    return -1;
11233: 	}
11234: 	if ($info < $fileinfo[9]) {
11235: # nice, the file we have is up-to-date, just say okay
11236: 	    return 'ok';
11237: 	} else {
11238: # the file is outdated, get rid of it
11239: 	    unlink($file);
11240: 	}
11241:     }
11242: # one way or the other, at this point, we don't have the file
11243: # construct the correct path for the file
11244:     my @parts = ($cdom,$cnum); 
11245:     if ($filename =~ m|^(.+)/[^/]+$|) {
11246: 	push @parts, split(/\//,$1);
11247:     }
11248:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11249:     foreach my $part (@parts) {
11250: 	$path .= '/'.$part;
11251: 	if (!-e $path) {
11252: 	    mkdir($path,0770);
11253: 	}
11254:     }
11255: # now the path exists for sure
11256: # get a user agent
11257:     my $ua=new LWP::UserAgent;
11258:     my $transferfile=$file.'.in.transfer';
11259: # FIXME: this should flock
11260:     if (-e $transferfile) { return 'ok'; }
11261:     my $request;
11262:     $uri=~s/^\///;
11263:     my $homeserver = &homeserver($cnum,$cdom);
11264:     my $protocol = $protocol{$homeserver};
11265:     $protocol = 'http' if ($protocol ne 'https');
11266:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11267:     my $response=$ua->request($request,$transferfile);
11268: # did it work?
11269:     if ($response->is_error()) {
11270: 	unlink($transferfile);
11271: 	&logthis("Userfile repcopy failed for $uri");
11272: 	return -1;
11273:     }
11274: # worked, rename the transfer file
11275:     rename($transferfile,$file);
11276:     return 'ok';
11277: }
11278: 
11279: sub tokenwrapper {
11280:     my $uri=shift;
11281:     $uri=~s|^https?\://([^/]+)||;
11282:     $uri=~s|^/||;
11283:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11284:     my $token=$1;
11285:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11286:     if ($udom && $uname && $file) {
11287: 	$file=~s|(\?\.*)*$||;
11288:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11289:         my $homeserver = &homeserver($uname,$udom);
11290:         my $protocol = $protocol{$homeserver};
11291:         $protocol = 'http' if ($protocol ne 'https');
11292:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11293:                (($uri=~/\?/)?'&':'?').'token='.$token.
11294:                                '&tokenissued='.$perlvar{'lonHostID'};
11295:     } else {
11296:         return '/adm/notfound.html';
11297:     }
11298: }
11299: 
11300: # call with reqtype HEAD: get last modification time
11301: # call with reqtype GET: get the file contents
11302: # Do not call this with reqtype GET for large files! It loads everything into memory
11303: #
11304: sub getuploaded {
11305:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11306:     $uri=~s/^\///;
11307:     my $homeserver = &homeserver($cnum,$cdom);
11308:     my $protocol = $protocol{$homeserver};
11309:     $protocol = 'http' if ($protocol ne 'https');
11310:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11311:     my $ua=new LWP::UserAgent;
11312:     my $request=new HTTP::Request($reqtype,$uri);
11313:     my $response=$ua->request($request);
11314:     $$rtncode = $response->code;
11315:     if (! $response->is_success()) {
11316: 	return 'failed';
11317:     }      
11318:     if ($reqtype eq 'HEAD') {
11319: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11320:     } elsif ($reqtype eq 'GET') {
11321: 	$$info = $response->content;
11322:     }
11323:     return 'ok';
11324: }
11325: 
11326: sub readfile {
11327:     my $file = shift;
11328:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11329:     my $fh;
11330:     open($fh,"<$file");
11331:     my $a='';
11332:     while (my $line = <$fh>) { $a .= $line; }
11333:     return $a;
11334: }
11335: 
11336: sub filelocation {
11337:     my ($dir,$file) = @_;
11338:     my $location;
11339:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11340: 
11341:     if ($file =~ m-^/adm/-) {
11342: 	$file=~s-^/adm/wrapper/-/-;
11343: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11344:     }
11345: 
11346:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11347:         $location = $file;
11348:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11349:         my ($udom,$uname,$filename)=
11350:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11351:         my $home=&homeserver($uname,$udom);
11352:         my $is_me=0;
11353:         my @ids=&current_machine_ids();
11354:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11355:         if ($is_me) {
11356:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11357:         } else {
11358:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11359:   	      $udom.'/'.$uname.'/'.$filename;
11360:         }
11361:     } elsif ($file =~ m-^/adm/-) {
11362: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11363:     } else {
11364:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11365:         $file=~s:^/(res|priv)/:/:;
11366:         my $space=$1;
11367:         if ( !( $file =~ m:^/:) ) {
11368:             $location = $dir. '/'.$file;
11369:         } else {
11370:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11371:         }
11372:     }
11373:     $location=~s://+:/:g; # remove duplicate /
11374:     while ($location=~m{/\.\./}) {
11375: 	if ($location =~ m{/[^/]+/\.\./}) {
11376: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11377: 	} else {
11378: 	    $location=~ s{/\.\./}{/}g;
11379: 	}
11380:     } #remove dir/..
11381:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11382:     return $location;
11383: }
11384: 
11385: sub hreflocation {
11386:     my ($dir,$file)=@_;
11387:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11388: 	$file=filelocation($dir,$file);
11389:     } elsif ($file=~m-^/adm/-) {
11390: 	$file=~s-^/adm/wrapper/-/-;
11391: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11392:     }
11393:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11394: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11395:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11396: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11397: 	        {/uploaded/$1/$2/}x;
11398:     }
11399:     if ($file=~ m{^/userfiles/}) {
11400: 	$file =~ s{^/userfiles/}{/uploaded/};
11401:     }
11402:     return $file;
11403: }
11404: 
11405: 
11406: 
11407: 
11408: 
11409: sub current_machine_domains {
11410:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11411: }
11412: 
11413: sub machine_domains {
11414:     my ($hostname) = @_;
11415:     my @domains;
11416:     my %hostname = &all_hostnames();
11417:     while( my($id, $name) = each(%hostname)) {
11418: #	&logthis("-$id-$name-$hostname-");
11419: 	if ($hostname eq $name) {
11420: 	    push(@domains,&host_domain($id));
11421: 	}
11422:     }
11423:     return @domains;
11424: }
11425: 
11426: sub current_machine_ids {
11427:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11428: }
11429: 
11430: sub machine_ids {
11431:     my ($hostname) = @_;
11432:     $hostname ||= &hostname($perlvar{'lonHostID'});
11433:     my @ids;
11434:     my %name_to_host = &all_names();
11435:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11436: 	return @{ $name_to_host{$hostname} };
11437:     }
11438:     return;
11439: }
11440: 
11441: sub additional_machine_domains {
11442:     my @domains;
11443:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11444:     while( my $line = <$fh>) {
11445:         $line =~ s/\s//g;
11446:         push(@domains,$line);
11447:     }
11448:     return @domains;
11449: }
11450: 
11451: sub default_login_domain {
11452:     my $domain = $perlvar{'lonDefDomain'};
11453:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11454:     foreach my $posdom (&current_machine_domains(),
11455:                         &additional_machine_domains()) {
11456:         if (lc($posdom) eq lc($testdomain)) {
11457:             $domain=$posdom;
11458:             last;
11459:         }
11460:     }
11461:     return $domain;
11462: }
11463: 
11464: # ------------------------------------------------------------- Declutters URLs
11465: 
11466: sub declutter {
11467:     my $thisfn=shift;
11468:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11469:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11470:     $thisfn=~s/^\///;
11471:     $thisfn=~s|^adm/wrapper/||;
11472:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11473:     $thisfn=~s/^res\///;
11474:     $thisfn=~s/^priv\///;
11475:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11476:         $thisfn=~s/\?.+$//;
11477:     }
11478:     return $thisfn;
11479: }
11480: 
11481: # ------------------------------------------------------------- Clutter up URLs
11482: 
11483: sub clutter {
11484:     my $thisfn='/'.&declutter(shift);
11485:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11486: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11487:        $thisfn='/res'.$thisfn; 
11488:     }
11489:     if ($thisfn !~m|^/adm|) {
11490: 	if ($thisfn =~ m|^/ext/|) {
11491: 	    $thisfn='/adm/wrapper'.$thisfn;
11492: 	} else {
11493: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11494: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11495: 	    if ($embstyle eq 'ssi'
11496: 		|| ($embstyle eq 'hdn')
11497: 		|| ($embstyle eq 'rat')
11498: 		|| ($embstyle eq 'prv')
11499: 		|| ($embstyle eq 'ign')) {
11500: 		#do nothing with these
11501: 	    } elsif (($embstyle eq 'img') 
11502: 		|| ($embstyle eq 'emb')
11503: 		|| ($embstyle eq 'wrp')) {
11504: 		$thisfn='/adm/wrapper'.$thisfn;
11505: 	    } elsif ($embstyle eq 'unk'
11506: 		     && $thisfn!~/\.(sequence|page)$/) {
11507: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11508: 	    } else {
11509: #		&logthis("Got a blank emb style");
11510: 	    }
11511: 	}
11512:     }
11513:     return $thisfn;
11514: }
11515: 
11516: sub clutter_with_no_wrapper {
11517:     my $uri = &clutter(shift);
11518:     if ($uri =~ m-^/adm/-) {
11519: 	$uri =~ s-^/adm/wrapper/-/-;
11520: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11521:     }
11522:     return $uri;
11523: }
11524: 
11525: sub freeze_escape {
11526:     my ($value)=@_;
11527:     if (ref($value)) {
11528: 	$value=&nfreeze($value);
11529: 	return '__FROZEN__'.&escape($value);
11530:     }
11531:     return &escape($value);
11532: }
11533: 
11534: 
11535: sub thaw_unescape {
11536:     my ($value)=@_;
11537:     if ($value =~ /^__FROZEN__/) {
11538: 	substr($value,0,10,undef);
11539: 	$value=&unescape($value);
11540: 	return &thaw($value);
11541:     }
11542:     return &unescape($value);
11543: }
11544: 
11545: sub correct_line_ends {
11546:     my ($result)=@_;
11547:     $$result =~s/\r\n/\n/mg;
11548:     $$result =~s/\r/\n/mg;
11549: }
11550: # ================================================================ Main Program
11551: 
11552: sub goodbye {
11553:    &logthis("Starting Shut down");
11554: #not converted to using infrastruture and probably shouldn't be
11555:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11556: #converted
11557: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11558:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11559: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11560: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11561: #1.1 only
11562: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11563: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11564: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11565: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11566:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11567:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11568:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11569:    &flushcourselogs();
11570:    &logthis("Shutting down");
11571: }
11572: 
11573: sub get_dns {
11574:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11575:     if (!$ignore_cache) {
11576: 	my ($content,$cached)=
11577: 	    &Apache::lonnet::is_cached_new('dns',$url);
11578: 	if ($cached) {
11579: 	    &$func($content,$hashref);
11580: 	    return;
11581: 	}
11582:     }
11583: 
11584:     my %alldns;
11585:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11586:     foreach my $dns (<$config>) {
11587: 	next if ($dns !~ /^\^(\S*)/x);
11588:         my $line = $1;
11589:         my ($host,$protocol) = split(/:/,$line);
11590:         if ($protocol ne 'https') {
11591:             $protocol = 'http';
11592:         }
11593: 	$alldns{$host} = $protocol;
11594:     }
11595:     while (%alldns) {
11596: 	my ($dns) = keys(%alldns);
11597: 	my $ua=new LWP::UserAgent;
11598:         $ua->timeout(30);
11599: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11600: 	my $response=$ua->request($request);
11601:         delete($alldns{$dns});
11602: 	next if ($response->is_error());
11603: 	my @content = split("\n",$response->content);
11604: 	unless ($nocache) {
11605: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11606: 	}
11607: 	&$func(\@content,$hashref);
11608: 	return;
11609:     }
11610:     close($config);
11611:     my $which = (split('/',$url))[3];
11612:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11613:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11614:     my @content = <$config>;
11615:     &$func(\@content,$hashref);
11616:     return;
11617: }
11618: 
11619: # ------------------------------------------------------Get DNS checksums file
11620: sub parse_dns_checksums_tab {
11621:     my ($lines,$hashref) = @_;
11622:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11623:     my $loncaparev = &get_server_loncaparev($machine_dom);
11624:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11625:     my (%chksum,%revnum);
11626:     if (ref($lines) eq 'ARRAY') {
11627:         chomp(@{$lines});
11628:         my $versions = shift(@{$lines});
11629:         my %supported;
11630:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11631:             my $releaseslist = $1;
11632:             if ($releaseslist =~ /,/) {
11633:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
11634:             } elsif ($releaseslist) {
11635:                 $supported{$releaseslist} = 1;
11636:             }
11637:         }
11638:         if ($supported{$release}) {  
11639:             my $matchthis = 0;
11640:             foreach my $line (@{$lines}) {
11641:                 if ($line =~ /^(\d[\w\.]+)$/) {
11642:                     if ($matchthis) {
11643:                         last;
11644:                     } elsif ($1 eq $release) {
11645:                         $matchthis = 1;
11646:                     }
11647:                 } elsif ($matchthis) {
11648:                     my ($file,$version,$shasum) = split(/,/,$line);
11649:                     $chksum{$file} = $shasum;
11650:                     $revnum{$file} = $version;
11651:                 }
11652:             }
11653:             if (ref($hashref) eq 'HASH') {
11654:                 %{$hashref} = (
11655:                                 sums     => \%chksum,
11656:                                 versions => \%revnum,
11657:                               );
11658:             }
11659:         }
11660:     }
11661:     return;
11662: }
11663: 
11664: sub fetch_dns_checksums {
11665:     my %checksums; 
11666:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11667:              \%checksums);
11668:     return \%checksums;
11669: }
11670: 
11671: # ------------------------------------------------------------ Read domain file
11672: {
11673:     my $loaded;
11674:     my %domain;
11675: 
11676:     sub parse_domain_tab {
11677: 	my ($lines) = @_;
11678: 	foreach my $line (@$lines) {
11679: 	    next if ($line =~ /^(\#|\s*$ )/x);
11680: 
11681: 	    chomp($line);
11682: 	    my ($name,@elements) = split(/:/,$line,9);
11683: 	    my %this_domain;
11684: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11685: 			       'lang_def', 'city', 'longi', 'lati',
11686: 			       'primary') {
11687: 		$this_domain{$field} = shift(@elements);
11688: 	    }
11689: 	    $domain{$name} = \%this_domain;
11690: 	}
11691:     }
11692: 
11693:     sub reset_domain_info {
11694: 	undef($loaded);
11695: 	undef(%domain);
11696:     }
11697: 
11698:     sub load_domain_tab {
11699: 	my ($ignore_cache) = @_;
11700: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11701: 	my $fh;
11702: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11703: 	    my @lines = <$fh>;
11704: 	    &parse_domain_tab(\@lines);
11705: 	}
11706: 	close($fh);
11707: 	$loaded = 1;
11708:     }
11709: 
11710:     sub domain {
11711: 	&load_domain_tab() if (!$loaded);
11712: 
11713: 	my ($name,$what) = @_;
11714: 	return if ( !exists($domain{$name}) );
11715: 
11716: 	if (!$what) {
11717: 	    return $domain{$name}{'description'};
11718: 	}
11719: 	return $domain{$name}{$what};
11720:     }
11721: 
11722:     sub domain_info {
11723:         &load_domain_tab() if (!$loaded);
11724:         return %domain;
11725:     }
11726: 
11727: }
11728: 
11729: 
11730: # ------------------------------------------------------------- Read hosts file
11731: {
11732:     my %hostname;
11733:     my %hostdom;
11734:     my %libserv;
11735:     my $loaded;
11736:     my %name_to_host;
11737:     my %internetdom;
11738:     my %LC_dns_serv;
11739: 
11740:     sub parse_hosts_tab {
11741: 	my ($file) = @_;
11742: 	foreach my $configline (@$file) {
11743: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11744:             chomp($configline);
11745: 	    if ($configline =~ /^\^/) {
11746:                 if ($configline =~ /^\^([\w.\-]+)/) {
11747:                     $LC_dns_serv{$1} = 1;
11748:                 }
11749:                 next;
11750:             }
11751: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11752: 	    $name=~s/\s//g;
11753: 	    if ($id && $domain && $role && $name) {
11754: 		$hostname{$id}=$name;
11755: 		push(@{$name_to_host{$name}}, $id);
11756: 		$hostdom{$id}=$domain;
11757: 		if ($role eq 'library') { $libserv{$id}=$name; }
11758:                 if (defined($protocol)) {
11759:                     if ($protocol eq 'https') {
11760:                         $protocol{$id} = $protocol;
11761:                     } else {
11762:                         $protocol{$id} = 'http'; 
11763:                     }
11764:                 } else {
11765:                     $protocol{$id} = 'http';
11766:                 }
11767:                 if (defined($intdom)) {
11768:                     $internetdom{$id} = $intdom;
11769:                 }
11770: 	    }
11771: 	}
11772:     }
11773:     
11774:     sub reset_hosts_info {
11775: 	&purge_remembered();
11776: 	&reset_domain_info();
11777: 	&reset_hosts_ip_info();
11778: 	undef(%name_to_host);
11779: 	undef(%hostname);
11780: 	undef(%hostdom);
11781: 	undef(%libserv);
11782: 	undef($loaded);
11783:     }
11784: 
11785:     sub load_hosts_tab {
11786: 	my ($ignore_cache) = @_;
11787: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11788: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11789: 	my @config = <$config>;
11790: 	&parse_hosts_tab(\@config);
11791: 	close($config);
11792: 	$loaded=1;
11793:     }
11794: 
11795:     sub hostname {
11796: 	&load_hosts_tab() if (!$loaded);
11797: 
11798: 	my ($lonid) = @_;
11799: 	return $hostname{$lonid};
11800:     }
11801: 
11802:     sub all_hostnames {
11803: 	&load_hosts_tab() if (!$loaded);
11804: 
11805: 	return %hostname;
11806:     }
11807: 
11808:     sub all_names {
11809: 	&load_hosts_tab() if (!$loaded);
11810: 
11811: 	return %name_to_host;
11812:     }
11813: 
11814:     sub all_host_domain {
11815:         &load_hosts_tab() if (!$loaded);
11816:         return %hostdom;
11817:     }
11818: 
11819:     sub is_library {
11820: 	&load_hosts_tab() if (!$loaded);
11821: 
11822: 	return exists($libserv{$_[0]});
11823:     }
11824: 
11825:     sub all_library {
11826: 	&load_hosts_tab() if (!$loaded);
11827: 
11828: 	return %libserv;
11829:     }
11830: 
11831:     sub unique_library {
11832: 	#2x reverse removes all hostnames that appear more than once
11833:         my %unique = reverse &all_library();
11834:         return reverse %unique;
11835:     }
11836: 
11837:     sub get_servers {
11838: 	&load_hosts_tab() if (!$loaded);
11839: 
11840: 	my ($domain,$type) = @_;
11841: 	my %possible_hosts = ($type eq 'library') ? %libserv
11842: 	                                          : %hostname;
11843: 	my %result;
11844: 	if (ref($domain) eq 'ARRAY') {
11845: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11846: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11847: 		    $result{$host} = $hostname;
11848: 		}
11849: 	    }
11850: 	} else {
11851: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11852: 		if ($hostdom{$host} eq $domain) {
11853: 		    $result{$host} = $hostname;
11854: 		}
11855: 	    }
11856: 	}
11857: 	return %result;
11858:     }
11859: 
11860:     sub get_unique_servers {
11861:         my %unique = reverse &get_servers(@_);
11862: 	return reverse %unique;
11863:     }
11864: 
11865:     sub host_domain {
11866: 	&load_hosts_tab() if (!$loaded);
11867: 
11868: 	my ($lonid) = @_;
11869: 	return $hostdom{$lonid};
11870:     }
11871: 
11872:     sub all_domains {
11873: 	&load_hosts_tab() if (!$loaded);
11874: 
11875: 	my %seen;
11876: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11877: 	return @uniq;
11878:     }
11879: 
11880:     sub internet_dom {
11881:         &load_hosts_tab() if (!$loaded);
11882: 
11883:         my ($lonid) = @_;
11884:         return $internetdom{$lonid};
11885:     }
11886: 
11887:     sub is_LC_dns {
11888:         &load_hosts_tab() if (!$loaded);
11889: 
11890:         my ($hostname) = @_;
11891:         return exists($LC_dns_serv{$hostname});
11892:     }
11893: 
11894: }
11895: 
11896: { 
11897:     my %iphost;
11898:     my %name_to_ip;
11899:     my %lonid_to_ip;
11900: 
11901:     sub get_hosts_from_ip {
11902: 	my ($ip) = @_;
11903: 	my %iphosts = &get_iphost();
11904: 	if (ref($iphosts{$ip})) {
11905: 	    return @{$iphosts{$ip}};
11906: 	}
11907: 	return;
11908:     }
11909:     
11910:     sub reset_hosts_ip_info {
11911: 	undef(%iphost);
11912: 	undef(%name_to_ip);
11913: 	undef(%lonid_to_ip);
11914:     }
11915: 
11916:     sub get_host_ip {
11917: 	my ($lonid) = @_;
11918: 	if (exists($lonid_to_ip{$lonid})) {
11919: 	    return $lonid_to_ip{$lonid};
11920: 	}
11921: 	my $name=&hostname($lonid);
11922:    	my $ip = gethostbyname($name);
11923: 	return if (!$ip || length($ip) ne 4);
11924: 	$ip=inet_ntoa($ip);
11925: 	$name_to_ip{$name}   = $ip;
11926: 	$lonid_to_ip{$lonid} = $ip;
11927: 	return $ip;
11928:     }
11929:     
11930:     sub get_iphost {
11931: 	my ($ignore_cache) = @_;
11932: 
11933: 	if (!$ignore_cache) {
11934: 	    if (%iphost) {
11935: 		return %iphost;
11936: 	    }
11937: 	    my ($ip_info,$cached)=
11938: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11939: 	    if ($cached) {
11940: 		%iphost      = %{$ip_info->[0]};
11941: 		%name_to_ip  = %{$ip_info->[1]};
11942: 		%lonid_to_ip = %{$ip_info->[2]};
11943: 		return %iphost;
11944: 	    }
11945: 	}
11946: 
11947: 	# get yesterday's info for fallback
11948: 	my %old_name_to_ip;
11949: 	my ($ip_info,$cached)=
11950: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11951: 	if ($cached) {
11952: 	    %old_name_to_ip = %{$ip_info->[1]};
11953: 	}
11954: 
11955: 	my %name_to_host = &all_names();
11956: 	foreach my $name (keys(%name_to_host)) {
11957: 	    my $ip;
11958: 	    if (!exists($name_to_ip{$name})) {
11959: 		$ip = gethostbyname($name);
11960: 		if (!$ip || length($ip) ne 4) {
11961: 		    if (defined($old_name_to_ip{$name})) {
11962: 			$ip = $old_name_to_ip{$name};
11963: 			&logthis("Can't find $name defaulting to old $ip");
11964: 		    } else {
11965: 			&logthis("Name $name no IP found");
11966: 			next;
11967: 		    }
11968: 		} else {
11969: 		    $ip=inet_ntoa($ip);
11970: 		}
11971: 		$name_to_ip{$name} = $ip;
11972: 	    } else {
11973: 		$ip = $name_to_ip{$name};
11974: 	    }
11975: 	    foreach my $id (@{ $name_to_host{$name} }) {
11976: 		$lonid_to_ip{$id} = $ip;
11977: 	    }
11978: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11979: 	}
11980: 	&do_cache_new('iphost','iphost',
11981: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11982: 		      48*60*60);
11983: 
11984: 	return %iphost;
11985:     }
11986: 
11987:     #
11988:     #  Given a DNS returns the loncapa host name for that DNS 
11989:     # 
11990:     sub host_from_dns {
11991:         my ($dns) = @_;
11992:         my @hosts;
11993:         my $ip;
11994: 
11995:         if (exists($name_to_ip{$dns})) {
11996:             $ip = $name_to_ip{$dns};
11997:         }
11998:         if (!$ip) {
11999:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12000:             if (length($ip) == 4) { 
12001: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12002:             }
12003:         }
12004:         if ($ip) {
12005: 	    @hosts = get_hosts_from_ip($ip);
12006: 	    return $hosts[0];
12007:         }
12008:         return undef;
12009:     }
12010: 
12011:     sub get_internet_names {
12012:         my ($lonid) = @_;
12013:         return if ($lonid eq '');
12014:         my ($idnref,$cached)=
12015:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12016:         if ($cached) {
12017:             return $idnref;
12018:         }
12019:         my $ip = &get_host_ip($lonid);
12020:         my @hosts = &get_hosts_from_ip($ip);
12021:         my %iphost = &get_iphost();
12022:         my (@idns,%seen);
12023:         foreach my $id (@hosts) {
12024:             my $dom = &host_domain($id);
12025:             my $prim_id = &domain($dom,'primary');
12026:             my $prim_ip = &get_host_ip($prim_id);
12027:             next if ($seen{$prim_ip});
12028:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12029:                 foreach my $id (@{$iphost{$prim_ip}}) {
12030:                     my $intdom = &internet_dom($id);
12031:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12032:                         push(@idns,$intdom);
12033:                     }
12034:                 }
12035:             }
12036:             $seen{$prim_ip} = 1;
12037:         }
12038:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12039:     }
12040: 
12041: }
12042: 
12043: sub all_loncaparevs {
12044:     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);
12045: }
12046: 
12047: # ---------------------------------------------------------- Read loncaparev table
12048: {
12049:     sub load_loncaparevs { 
12050:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12051:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12052:                 while (my $configline=<$config>) {
12053:                     chomp($configline);
12054:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12055:                     $loncaparevs{$hostid}=$loncaparev;
12056:                 }
12057:                 close($config);
12058:             }
12059:         }
12060:     }
12061: }
12062: 
12063: # ---------------------------------------------------------- Read serverhostID table
12064: {
12065:     sub load_serverhomeIDs {
12066:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12067:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12068:                 while (my $configline=<$config>) {
12069:                     chomp($configline);
12070:                     my ($name,$id)=split(/:/,$configline);
12071:                     $serverhomeIDs{$name}=$id;
12072:                 }
12073:                 close($config);
12074:             }
12075:         }
12076:     }
12077: }
12078: 
12079: 
12080: BEGIN {
12081: 
12082: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12083:     unless ($readit) {
12084: {
12085:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12086:     %perlvar = (%perlvar,%{$configvars});
12087: }
12088: 
12089: 
12090: # ------------------------------------------------------ Read spare server file
12091: {
12092:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12093: 
12094:     while (my $configline=<$config>) {
12095:        chomp($configline);
12096:        if ($configline) {
12097: 	   my ($host,$type) = split(':',$configline,2);
12098: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12099: 	   push(@{ $spareid{$type} }, $host);
12100:        }
12101:     }
12102:     close($config);
12103: }
12104: # ------------------------------------------------------------ Read permissions
12105: {
12106:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12107: 
12108:     while (my $configline=<$config>) {
12109: 	chomp($configline);
12110: 	if ($configline) {
12111: 	    my ($role,$perm)=split(/ /,$configline);
12112: 	    if ($perm ne '') { $pr{$role}=$perm; }
12113: 	}
12114:     }
12115:     close($config);
12116: }
12117: 
12118: # -------------------------------------------- Read plain texts for permissions
12119: {
12120:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12121: 
12122:     while (my $configline=<$config>) {
12123: 	chomp($configline);
12124: 	if ($configline) {
12125: 	    my ($short,@plain)=split(/:/,$configline);
12126:             %{$prp{$short}} = ();
12127: 	    if (@plain > 0) {
12128:                 $prp{$short}{'std'} = $plain[0];
12129:                 for (my $i=1; $i<@plain; $i++) {
12130:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12131:                 }
12132:             }
12133: 	}
12134:     }
12135:     close($config);
12136: }
12137: 
12138: # ---------------------------------------------------------- Read package table
12139: {
12140:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12141: 
12142:     while (my $configline=<$config>) {
12143: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12144: 	chomp($configline);
12145: 	my ($short,$plain)=split(/:/,$configline);
12146: 	my ($pack,$name)=split(/\&/,$short);
12147: 	if ($plain ne '') {
12148: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12149: 	    $packagetab{$short}=$plain; 
12150: 	}
12151:     }
12152:     close($config);
12153: }
12154: 
12155: # ---------------------------------------------------------- Read loncaparev table
12156: 
12157: &load_loncaparevs();
12158: 
12159: # ---------------------------------------------------------- Read serverhostID table
12160: 
12161: &load_serverhomeIDs();
12162: 
12163: # ---------------------------------------------------------- Read releaseslist XML
12164: {
12165:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12166:     if (-e $file) {
12167:         my $parser = HTML::LCParser->new($file);
12168:         while (my $token = $parser->get_token()) {
12169:             if ($token->[0] eq 'S') {
12170:                 my $item = $token->[1];
12171:                 my $name = $token->[2]{'name'};
12172:                 my $value = $token->[2]{'value'};
12173:                 if ($item ne '' && $name ne '' && $value ne '') {
12174:                     my $release = $parser->get_text();
12175:                     $release =~ s/(^\s*|\s*$ )//gx;
12176:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12177:                 }
12178:             }
12179:         }
12180:     }
12181: }
12182: 
12183: # ---------------------------------------------------------- Read managers table
12184: {
12185:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12186:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12187:             while (my $configline=<$config>) {
12188:                 chomp($configline);
12189:                 next if ($configline =~ /^\#/);
12190:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12191:                     $managerstab{$configline} = 1;
12192:                 }
12193:             }
12194:             close($config);
12195:         }
12196:     }
12197: }
12198: 
12199: # ------------- set up temporary directory
12200: {
12201:     $tmpdir = LONCAPA::tempdir();
12202: 
12203: }
12204: 
12205: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12206: 				'compress_threshold'=> 20_000,
12207:  			        });
12208: 
12209: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12210: $dumpcount=0;
12211: $locknum=0;
12212: 
12213: &logtouch();
12214: &logthis('<font color="yellow">INFO: Read configuration</font>');
12215: $readit=1;
12216:     {
12217: 	use integer;
12218: 	my $test=(2**32)+1;
12219: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12220: 	&logthis(" Detected 64bit platform ($_64bit)");
12221:     }
12222: 
12223:     {
12224:         eval {
12225:             ($apache) =
12226:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12227:         };
12228:         if ($@) {
12229:            $apache = 1.3;
12230:         }
12231:     }
12232: 
12233: }
12234: }
12235: 
12236: 1;
12237: __END__
12238: 
12239: =pod
12240: 
12241: =head1 NAME
12242: 
12243: Apache::lonnet - Subroutines to ask questions about things in the network.
12244: 
12245: =head1 SYNOPSIS
12246: 
12247: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12248: 
12249:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12250: 
12251: Common parameters:
12252: 
12253: =over 4
12254: 
12255: =item *
12256: 
12257: $uname : an internal username (if $cname expecting a course Id specifically)
12258: 
12259: =item *
12260: 
12261: $udom : a domain (if $cdom expecting a course's domain specifically)
12262: 
12263: =item *
12264: 
12265: $symb : a resource instance identifier
12266: 
12267: =item *
12268: 
12269: $namespace : the name of a .db file that contains the data needed or
12270: being set.
12271: 
12272: =back
12273: 
12274: =head1 OVERVIEW
12275: 
12276: lonnet provides subroutines which interact with the
12277: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12278: about classes, users, and resources.
12279: 
12280: For many of these objects you can also use this to store data about
12281: them or modify them in various ways.
12282: 
12283: =head2 Symbs
12284: 
12285: To identify a specific instance of a resource, LON-CAPA uses symbols
12286: or "symbs"X<symb>. These identifiers are built from the URL of the
12287: map, the resource number of the resource in the map, and the URL of
12288: the resource itself. The latter is somewhat redundant, but might help
12289: if maps change.
12290: 
12291: An example is
12292: 
12293:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12294: 
12295: The respective map entry is
12296: 
12297:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12298:   title="Problem 2">
12299:  </resource>
12300: 
12301: Symbs are used by the random number generator, as well as to store and
12302: restore data specific to a certain instance of for example a problem.
12303: 
12304: =head2 Storing And Retrieving Data
12305: 
12306: X<store()>X<cstore()>X<restore()>Three of the most important functions
12307: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12308: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12309: is is the non-critical message twin of cstore. These functions are for
12310: handlers to store a perl hash to a user's permanent data space in an
12311: easy manner, and to retrieve it again on another call. It is expected
12312: that a handler would use this once at the beginning to retrieve data,
12313: and then again once at the end to send only the new data back.
12314: 
12315: The data is stored in the user's data directory on the user's
12316: homeserver under the ID of the course.
12317: 
12318: The hash that is returned by restore will have all of the previous
12319: value for all of the elements of the hash.
12320: 
12321: Example:
12322: 
12323:  #creating a hash
12324:  my %hash;
12325:  $hash{'foo'}='bar';
12326: 
12327:  #storing it
12328:  &Apache::lonnet::cstore(\%hash);
12329: 
12330:  #changing a value
12331:  $hash{'foo'}='notbar';
12332: 
12333:  #adding a new value
12334:  $hash{'bar'}='foo';
12335:  &Apache::lonnet::cstore(\%hash);
12336: 
12337:  #retrieving the hash
12338:  my %history=&Apache::lonnet::restore();
12339: 
12340:  #print the hash
12341:  foreach my $key (sort(keys(%history))) {
12342:    print("\%history{$key} = $history{$key}");
12343:  }
12344: 
12345: Will print out:
12346: 
12347:  %history{1:foo} = bar
12348:  %history{1:keys} = foo:timestamp
12349:  %history{1:timestamp} = 990455579
12350:  %history{2:bar} = foo
12351:  %history{2:foo} = notbar
12352:  %history{2:keys} = foo:bar:timestamp
12353:  %history{2:timestamp} = 990455580
12354:  %history{bar} = foo
12355:  %history{foo} = notbar
12356:  %history{timestamp} = 990455580
12357:  %history{version} = 2
12358: 
12359: Note that the special hash entries C<keys>, C<version> and
12360: C<timestamp> were added to the hash. C<version> will be equal to the
12361: total number of versions of the data that have been stored. The
12362: C<timestamp> attribute will be the UNIX time the hash was
12363: stored. C<keys> is available in every historical section to list which
12364: keys were added or changed at a specific historical revision of a
12365: hash.
12366: 
12367: B<Warning>: do not store the hash that restore returns directly. This
12368: will cause a mess since it will restore the historical keys as if the
12369: were new keys. I.E. 1:foo will become 1:1:foo etc.
12370: 
12371: Calling convention:
12372: 
12373:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12374:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12375: 
12376: For more detailed information, see lonnet specific documentation.
12377: 
12378: =head1 RETURN MESSAGES
12379: 
12380: =over 4
12381: 
12382: =item * B<con_lost>: unable to contact remote host
12383: 
12384: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12385: when the connection is brought back up
12386: 
12387: =item * B<con_failed>: unable to contact remote host and unable to save message
12388: for later delivery
12389: 
12390: =item * B<error:>: an error a occurred, a description of the error follows the :
12391: 
12392: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12393: that was requested
12394: 
12395: =back
12396: 
12397: =head1 PUBLIC SUBROUTINES
12398: 
12399: =head2 Session Environment Functions
12400: 
12401: =over 4
12402: 
12403: =item * 
12404: X<appenv()>
12405: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12406: the user envirnoment file, and will be restored for each access this
12407: user makes during this session, also modifies the %env for the current
12408: process. Optional rolesarrayref - if defined contains a reference to an array
12409: of roles which are exempt from the restriction on modifying user.role entries 
12410: in the user's environment.db and in %env.    
12411: 
12412: =item *
12413: X<delenv()>
12414: B<delenv($delthis,$regexp)>: removes all items from the session
12415: environment file that begin with $delthis. If the 
12416: optional second arg - $regexp - is true, $delthis is treated as a 
12417: regular expression, otherwise \Q$delthis\E is used. 
12418: The values are also deleted from the current processes %env.
12419: 
12420: =item * get_env_multiple($name) 
12421: 
12422: gets $name from the %env hash, it seemlessly handles the cases where multiple
12423: values may be defined and end up as an array ref.
12424: 
12425: returns an array of values
12426: 
12427: =back
12428: 
12429: =head2 User Information
12430: 
12431: =over 4
12432: 
12433: =item *
12434: X<queryauthenticate()>
12435: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12436: authentication scheme
12437: 
12438: =item *
12439: X<authenticate()>
12440: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12441: authenticate user from domain's lib servers (first use the current
12442: one). C<$upass> should be the users password.
12443: $checkdefauth is optional (value is 1 if a check should be made to
12444:    authenticate user using default authentication method, and allow
12445:    account creation if username does not have account in the domain).
12446: $clientcancheckhost is optional (value is 1 if checking whether the
12447:    server can host will occur on the client side in lonauth.pm).   
12448: 
12449: =item *
12450: X<homeserver()>
12451: B<homeserver($uname,$udom)>: find the server which has
12452: the user's directory and files (there must be only one), this caches
12453: the answer, and also caches if there is a borken connection.
12454: 
12455: =item *
12456: X<idget()>
12457: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12458: (IDs are a unique resource in a domain, there must be only 1 ID per
12459: username, and only 1 username per ID in a specific domain) (returns
12460: hash: id=>name,id=>name)
12461: 
12462: =item *
12463: X<idrget()>
12464: B<idrget($udom,@unames)>: find the IDs behind a list of
12465: usernames (returns hash: name=>id,name=>id)
12466: 
12467: =item *
12468: X<idput()>
12469: B<idput($udom,%ids)>: store away a list of names and associated IDs
12470: 
12471: =item *
12472: X<rolesinit()>
12473: B<rolesinit($udom,$username)>: get user privileges.
12474: returns user role, first access and timer interval hashes
12475: 
12476: =item *
12477: X<privileged()>
12478: B<privileged($username,$domain)>: returns a true if user has a
12479: privileged and active role (i.e. su or dc), false otherwise.
12480: 
12481: =item *
12482: X<getsection()>
12483: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12484: course $cname, return section name/number or '' for "not in course"
12485: and '-1' for "no section"
12486: 
12487: =item *
12488: X<userenvironment()>
12489: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12490: passed in @what from the requested user's environment, returns a hash
12491: 
12492: =item * 
12493: X<userlog_query()>
12494: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12495: activity.log file. %filters defines filters applied when parsing the
12496: log file. These can be start or end timestamps, or the type of action
12497: - log to look for Login or Logout events, check for Checkin or
12498: Checkout, role for role selection. The response is in the form
12499: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12500: escaped strings of the action recorded in the activity.log file.
12501: 
12502: =back
12503: 
12504: =head2 User Roles
12505: 
12506: =over 4
12507: 
12508: =item *
12509: 
12510: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12511:  F: full access
12512:  U,I,K: authentication modes (cxx only)
12513:  '': forbidden
12514:  1: user needs to choose course
12515:  2: browse allowed
12516:  A: passphrase authentication needed
12517: 
12518: =item *
12519: 
12520: constructaccess($url,$setpriv) : check for access to construction space URL
12521: 
12522: See if the owner domain and name in the URL match those in the
12523: expected environment.  If so, return three element list
12524: ($ownername,$ownerdomain,$ownerhome).
12525: 
12526: Otherwise return the null string.
12527: 
12528: If second argument 'setpriv' is true, it assigns the privileges,
12529: and returns the same three element list, unless the owner has
12530: blocked "ad hoc" Domain Coordinator access to the Author Space,
12531: in which case the null string is returned.
12532: 
12533: =item *
12534: 
12535: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12536: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12537: and course level
12538: 
12539: =item *
12540: 
12541: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12542: (rolesplain.tab); plain text explanation of a user role term.
12543: $type is Course (default) or Community.
12544: If $forcedefault evaluates to true, text returned will be default 
12545: text for $type. Otherwise, if this is a course, the text returned 
12546: will be a custom name for the role (if defined in the course's 
12547: environment).  If no custom name is defined the default is returned.
12548:    
12549: =item *
12550: 
12551: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12552: All arguments are optional. Returns a hash of a roles, either for
12553: co-author/assistant author roles for a user's Construction Space
12554: (default), or if $context is 'userroles', roles for the user himself,
12555: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12556: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12557: For each key, value is set to colon-separated start and end times for
12558: the role.  If no username and domain are specified, will default to
12559: current user/domain. Types, roles, and roledoms are references to arrays
12560: of role statuses (active, future or previous), roles 
12561: (e.g., cc,in, st etc.) and domains of the roles which can be used
12562: to restrict the list of roles reported. If no array ref is 
12563: provided for types, will default to return only active roles.
12564: 
12565: =item *
12566: 
12567: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12568: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12569: 
12570: Additional optional arguments are: $type (if role checking is to be restricted 
12571: to certain user status types -- previous (expired roles), active (currently
12572: available roles) or future (roles available in the future), and
12573: $hideprivileged -- if true will not report course roles for users who
12574: have active Domain Coordinator role in course's domain or in additional
12575: domains (specified in 'Domains to check for privileged users' in course
12576: environment -- set via:  Course Settings -> Classlists and staff listing).
12577: 
12578: =item *
12579: 
12580: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12581: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12582: $possdomains and $possroles are optional array refs -- to domains to check and
12583: roles to check.  If $possdomains is not specified, a dump will be done of the
12584: users' roles.db to check for a dc or su role in any domain. This can be
12585: time consuming if &privileged is called repeatedly (e.g., when displaying a
12586: classlist), so in such cases, supplying a $possdomains array is preferred, as
12587: this then allows &privileged_by_domain() to be used, which caches the identity
12588: of privileged users, eliminating the need for repeated calls to &dump().
12589: 
12590: =item *
12591: 
12592: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12593: where the outer hash keys are domains specified in the $possdomains array ref,
12594: next inner hash keys are privileged roles specified in the $roles array ref,
12595: and the innermost hash contains key = value pairs for username:domain = end:start
12596: for active or future "privileged" users with that role in that domain. To avoid
12597: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12598: innerhash are cached using priv_$role and $dom as the identifiers.
12599: 
12600: =back
12601: 
12602: =head2 User Modification
12603: 
12604: =over 4
12605: 
12606: =item *
12607: 
12608: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12609: user for the level given by URL.  Optional start and end dates (leave empty
12610: string or zero for "no date")
12611: 
12612: =item *
12613: 
12614: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12615: change a users, password, possible return values are: ok,
12616: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12617: refused
12618: 
12619: =item *
12620: 
12621: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12622: 
12623: =item *
12624: 
12625: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12626:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12627: 
12628: will update user information (firstname,middlename,lastname,generation,
12629: permanentemail), and if forceid is true, student/employee ID also.
12630: A user's institutional affiliation(s) can also be updated.
12631: User information fields will not be overwritten with empty entries 
12632: unless the field is included in the $candelete array reference.
12633: This array is included when a single user is modified via "Manage Users",
12634: or when Autoupdate.pl is run by cron in a domain.
12635: 
12636: =item *
12637: 
12638: modifystudent
12639: 
12640: modify a student's enrollment and identification information.
12641: The course id is resolved based on the current users environment.  
12642: This means the envoking user must be a course coordinator or otherwise
12643: associated with a course.
12644: 
12645: This call is essentially a wrapper for lonnet::modifyuser and
12646: lonnet::modify_student_enrollment
12647: 
12648: Inputs: 
12649: 
12650: =over 4
12651: 
12652: =item B<$udom> Student's loncapa domain
12653: 
12654: =item B<$uname> Student's loncapa login name
12655: 
12656: =item B<$uid> Student/Employee ID
12657: 
12658: =item B<$umode> Student's authentication mode
12659: 
12660: =item B<$upass> Student's password
12661: 
12662: =item B<$first> Student's first name
12663: 
12664: =item B<$middle> Student's middle name
12665: 
12666: =item B<$last> Student's last name
12667: 
12668: =item B<$gene> Student's generation
12669: 
12670: =item B<$usec> Student's section in course
12671: 
12672: =item B<$end> Unix time of the roles expiration
12673: 
12674: =item B<$start> Unix time of the roles start date
12675: 
12676: =item B<$forceid> If defined, allow $uid to be changed
12677: 
12678: =item B<$desiredhome> server to use as home server for student
12679: 
12680: =item B<$email> Student's permanent e-mail address
12681: 
12682: =item B<$type> Type of enrollment (auto or manual)
12683: 
12684: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12685: 
12686: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12687: 
12688: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12689: 
12690: =item B<$context> role change context (shown in User Management Logs display in a course)
12691: 
12692: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12693: 
12694: =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.
12695: 
12696: =back
12697: 
12698: =item *
12699: 
12700: modify_student_enrollment
12701: 
12702: Change a students enrollment status in a class.  The environment variable
12703: 'role.request.course' must be defined for this function to proceed.
12704: 
12705: Inputs:
12706: 
12707: =over 4
12708: 
12709: =item $udom, students domain
12710: 
12711: =item $uname, students name
12712: 
12713: =item $uid, students user id
12714: 
12715: =item $first, students first name
12716: 
12717: =item $middle
12718: 
12719: =item $last
12720: 
12721: =item $gene
12722: 
12723: =item $usec
12724: 
12725: =item $end
12726: 
12727: =item $start
12728: 
12729: =item $type
12730: 
12731: =item $locktype
12732: 
12733: =item $cid
12734: 
12735: =item $selfenroll
12736: 
12737: =item $context
12738: 
12739: =item $credits, number of credits student will earn from this class
12740: 
12741: =back
12742: 
12743: 
12744: =item *
12745: 
12746: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12747: custom role; give a custom role to a user for the level given by URL.  Specify
12748: name and domain of role author, and role name
12749: 
12750: =item *
12751: 
12752: revokerole($udom,$uname,$url,$role) : revoke a role for url
12753: 
12754: =item *
12755: 
12756: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12757: 
12758: =back
12759: 
12760: =head2 Course Infomation
12761: 
12762: =over 4
12763: 
12764: =item *
12765: 
12766: coursedescription($courseid,$options) : returns a hash of information about the
12767: specified course id, including all environment settings for the
12768: course, the description of the course will be in the hash under the
12769: key 'description'
12770: 
12771: $options is an optional parameter that if supplied is a hash reference that controls
12772: what how this function works.  It has the following key/values:
12773: 
12774: =over 4
12775: 
12776: =item freshen_cache
12777: 
12778: If defined, and the environment cache for the course is valid, it is 
12779: returned in the returned hash.
12780: 
12781: =item one_time
12782: 
12783: If defined, the last cache time is set to _now_
12784: 
12785: =item user
12786: 
12787: If defined, the supplied username is used instead of the current user.
12788: 
12789: 
12790: =back
12791: 
12792: =item *
12793: 
12794: resdata($name,$domain,$type,@which) : request for current parameter
12795: setting for a specific $type, where $type is either 'course' or 'user',
12796: @what should be a list of parameters to ask about. This routine caches
12797: answers for 5 minutes.
12798: 
12799: =item *
12800: 
12801: get_courseresdata($courseid, $domain) : dump the entire course resource
12802: data base, returning a hash that is keyed by the resource name and has
12803: values that are the resource value.  I believe that the timestamps and
12804: versions are also returned.
12805: 
12806: =back
12807: 
12808: =head2 Course Modification
12809: 
12810: =over 4
12811: 
12812: =item *
12813: 
12814: writecoursepref($courseid,%prefs) : write preferences (environment
12815: database) for a course
12816: 
12817: =item *
12818: 
12819: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12820: 
12821: =item *
12822: 
12823: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12824: 
12825: =item *
12826: 
12827: is_course($courseid), is_course($cdom, $cnum)
12828: 
12829: Accepts either a combined $courseid (in the form of domain_courseid) or the
12830: two component version $cdom, $cnum. It checks if the specified course exists.
12831: 
12832: Returns:
12833:     undef if the course doesn't exist, otherwise
12834:     in scalar context the combined courseid.
12835:     in list context the two components of the course identifier, domain and 
12836:     courseid.    
12837: 
12838: =back
12839: 
12840: =head2 Resource Subroutines
12841: 
12842: =over 4
12843: 
12844: =item *
12845: 
12846: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12847: 
12848: =item *
12849: 
12850: repcopy($filename) : subscribes to the requested file, and attempts to
12851: replicate from the owning library server, Might return
12852: 'unavailable', 'not_found', 'forbidden', 'ok', or
12853: 'bad_request', also attempts to grab the metadata for the
12854: resource. Expects the local filesystem pathname
12855: (/home/httpd/html/res/....)
12856: 
12857: =back
12858: 
12859: =head2 Resource Information
12860: 
12861: =over 4
12862: 
12863: =item *
12864: 
12865: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12866: and returns the value of a variety of different possible values,
12867: $varname should be a request string, and the other parameters can be
12868: used to specify who and what one is asking about. Ordinarily, $cid 
12869: does not need to be specified, as it is retrived from 
12870: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12871: within lonuserstate::loadmap() when initializing a course, before
12872: $env{'request.course.id'} has been set, so it needs to be provided
12873: in that one case.
12874: 
12875: Possible values for $varname are environment.lastname (or other item
12876: from the envirnment hash), user.name (or someother aspect about the
12877: user), resource.0.maxtries (or some other part and parameter of a
12878: resource)
12879: 
12880: =item *
12881: 
12882: directcondval($number) : get current value of a condition; reads from a state
12883: string
12884: 
12885: =item *
12886: 
12887: condval($condidx) : value of condition index based on state
12888: 
12889: =item *
12890: 
12891: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12892: resource's metadata, $what should be either a specific key, or either
12893: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12894: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12895: 
12896: this function automatically caches all requests
12897: 
12898: =item *
12899: 
12900: metadata_query($query,$custom,$customshow) : make a metadata query against the
12901: network of library servers; returns file handle of where SQL and regex results
12902: will be stored for query
12903: 
12904: =item *
12905: 
12906: symbread($filename) : return symbolic list entry (filename argument optional);
12907: returns the data handle
12908: 
12909: =item *
12910: 
12911: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12912: and is a possible symb for the URL in $thisfn, and if is an encrypted
12913: resource that the user accessed using /enc/ returns a 1 on success, 0
12914: on failure, user must be in a course, as it assumes the existence of
12915: the course initial hash, and uses $env('request.course.id'}.  The third
12916: arg is an optional reference to a scalar.  If this arg is passed in the 
12917: call to symbverify, it will be set to 1 if the symb has been set to be 
12918: encrypted; otherwise it will be null.  
12919: 
12920: =item *
12921: 
12922: symbclean($symb) : removes versions numbers from a symb, returns the
12923: cleaned symb
12924: 
12925: =item *
12926: 
12927: is_on_map($uri) : checks if the $uri is somewhere on the current
12928: course map, user must be in a course for it to work.
12929: 
12930: =item *
12931: 
12932: numval($salt) : return random seed value (addend for rndseed)
12933: 
12934: =item *
12935: 
12936: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12937: a random seed, all arguments are optional, if they aren't sent it uses the
12938: environment to derive them. Note: if symb isn't sent and it can't get one
12939: from &symbread it will use the current time as its return value
12940: 
12941: =item *
12942: 
12943: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12944: unfakeable, receipt
12945: 
12946: =item *
12947: 
12948: receipt() : API to ireceipt working off of env values; given out to users
12949: 
12950: =item *
12951: 
12952: countacc($url) : count the number of accesses to a given URL
12953: 
12954: =item *
12955: 
12956: 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
12957: 
12958: =item *
12959: 
12960: 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)
12961: 
12962: =item *
12963: 
12964: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12965: 
12966: =item *
12967: 
12968: devalidate($symb) : devalidate temporary spreadsheet calculations,
12969: forcing spreadsheet to reevaluate the resource scores next time.
12970: 
12971: =item * 
12972: 
12973: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12974: when viewing in course context.
12975: 
12976:  input: six args -- filename (decluttered), course number, course domain,
12977:                     url, symb (if registered) and group (if this is a 
12978:                     group item -- e.g., bulletin board, group page etc.).
12979: 
12980:  output: array of five scalars --
12981:          $cfile -- url for file editing if editable on current server
12982:          $home -- homeserver of resource (i.e., for author if published,
12983:                                           or course if uploaded.).
12984:          $switchserver --  1 if server switch will be needed.
12985:          $forceedit -- 1 if icon/link should be to go to edit mode 
12986:          $forceview -- 1 if icon/link should be to go to view mode
12987: 
12988: =item *
12989: 
12990: is_course_upload($file,$cnum,$cdom)
12991: 
12992: Used in course context to determine if current file was uploaded to 
12993: the course (i.e., would be found in /userfiles/docs on the course's 
12994: homeserver.
12995: 
12996:   input: 3 args -- filename (decluttered), course number and course domain.
12997:   output: boolean -- 1 if file was uploaded.
12998: 
12999: =back
13000: 
13001: =head2 Storing/Retreiving Data
13002: 
13003: =over 4
13004: 
13005: =item *
13006: 
13007: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13008: for this url; hashref needs to be given and should be a \%hashname; the
13009: remaining args aren't required and if they aren't passed or are '' they will
13010: be derived from the env
13011: 
13012: =item *
13013: 
13014: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13015: uses critical subroutine
13016: 
13017: =item *
13018: 
13019: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13020: all args are optional
13021: 
13022: =item *
13023: 
13024: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13025: dumps the complete (or key matching regexp) namespace into a hash
13026: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13027: normally &store()ed into
13028: 
13029: $range should be either an integer '100' (give me the first 100
13030:                                            matching records)
13031:               or be  two integers sperated by a - with no spaces
13032:                  '30-50' (give me the 30th through the 50th matching
13033:                           records)
13034: 
13035: 
13036: =item *
13037: 
13038: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13039: replaces a &store() version of data with a replacement set of data
13040: for a particular resource in a namespace passed in the $storehash hash 
13041: reference
13042: 
13043: =item *
13044: 
13045: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13046: works very similar to store/cstore, but all data is stored in a
13047: temporary location and can be reset using tmpreset, $storehash should
13048: be a hash reference, returns nothing on success
13049: 
13050: =item *
13051: 
13052: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13053: similar to restore, but all data is stored in a temporary location and
13054: can be reset using tmpreset. Returns a hash of values on success,
13055: error string otherwise.
13056: 
13057: =item *
13058: 
13059: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13060: deltes all keys for $symb form the temporary storage hash.
13061: 
13062: =item *
13063: 
13064: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13065: reference filled in from namesp ($udom and $uname are optional)
13066: 
13067: =item *
13068: 
13069: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13070: namesp ($udom and $uname are optional)
13071: 
13072: =item *
13073: 
13074: dump($namespace,$udom,$uname,$regexp,$range) : 
13075: dumps the complete (or key matching regexp) namespace into a hash
13076: ($udom, $uname, $regexp, $range are optional)
13077: 
13078: $range should be either an integer '100' (give me the first 100
13079:                                            matching records)
13080:               or be  two integers sperated by a - with no spaces
13081:                  '30-50' (give me the 30th through the 50th matching
13082:                           records)
13083: =item *
13084: 
13085: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13086: $store can be a scalar, an array reference, or if the amount to be 
13087: incremented is > 1, a hash reference.
13088: 
13089: ($udom and $uname are optional)
13090: 
13091: =item *
13092: 
13093: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13094: ($udom and $uname are optional)
13095: 
13096: =item *
13097: 
13098: cput($namespace,$storehash,$udom,$uname) : critical put
13099: ($udom and $uname are optional)
13100: 
13101: =item *
13102: 
13103: newput($namespace,$storehash,$udom,$uname) :
13104: 
13105: Attempts to store the items in the $storehash, but only if they don't
13106: currently exist, if this succeeds you can be certain that you have 
13107: successfully created a new key value pair in the $namespace db.
13108: 
13109: 
13110: Args:
13111:  $namespace: name of database to store values to
13112:  $storehash: hashref to store to the db
13113:  $udom: (optional) domain of user containing the db
13114:  $uname: (optional) name of user caontaining the db
13115: 
13116: Returns:
13117:  'ok' -> succeeded in storing all keys of $storehash
13118:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13119:                         least <key> already existed in the db (other
13120:                         requested keys may also already exist)
13121:  'error: <msg>' -> unable to tie the DB or other error occurred
13122:  'con_lost' -> unable to contact request server
13123:  'refused' -> action was not allowed by remote machine
13124: 
13125: 
13126: =item *
13127: 
13128: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13129: reference filled in from namesp (encrypts the return communication)
13130: ($udom and $uname are optional)
13131: 
13132: =item *
13133: 
13134: log($udom,$name,$home,$message) : write to permanent log for user; use
13135: critical subroutine
13136: 
13137: =item *
13138: 
13139: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13140: array reference filled in from namespace found in domain level on either
13141: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13142: 
13143: =item *
13144: 
13145: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13146: domain level either on specified domain server ($uhome) or primary domain 
13147: server ($udom and $uhome are optional)
13148: 
13149: =item * 
13150: 
13151: get_domain_defaults($target_domain) : returns hash with defaults for
13152: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13153: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13154: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13155: Values are retrieved from cache (if current), or from domain's configuration.db
13156: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13157: or lonTabs/domain.tab. 
13158: 
13159: %domdefaults = &get_auth_defaults($target_domain);
13160: 
13161: =back
13162: 
13163: =head2 Network Status Functions
13164: 
13165: =over 4
13166: 
13167: =item *
13168: 
13169: dirlist() : return directory list based on URI (first arg).
13170: 
13171: Inputs: 1 required, 5 optional.
13172: 
13173: =over
13174: 
13175: =item 
13176: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13177: 
13178: =item
13179: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13180: 
13181: =item
13182: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13183: 
13184: =item
13185: $getpropath - boolean: 1 if prepend path using &propath(). 
13186: 
13187: =item
13188: $getuserdir - boolean: 1 if prepend path for "userfiles".
13189: 
13190: =item 
13191: $alternateRoot - path to prepend in place of path from $uri.
13192: 
13193: =back
13194: 
13195: Returns: Array of up to two items.
13196: 
13197: =over
13198: 
13199: a reference to an array of files/subdirectories
13200: 
13201: =over
13202: 
13203: Each element in the array of files/subdirectories is a & separated list of
13204: item name and the result of running stat on the item.  If dirlist was requested
13205: for a file instead of a directory, the item name will be ''. For a directory 
13206: listing, if the item is a metadata file, the element will end &N&M 
13207: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13208: default copyright set (1).  
13209: 
13210: =back
13211: 
13212: a scalar containing error condition (if encountered).
13213: 
13214: =over
13215: 
13216: =item 
13217: no_host (no homeserver identified for $username:$domain).
13218: 
13219: =item 
13220: no_such_host (server contacted for listing not identified as valid host).
13221: 
13222: =item 
13223: con_lost (connection to remote server failed).
13224: 
13225: =item 
13226: refused (invalid $username:$domain received on lond side).
13227: 
13228: =item 
13229: no_such_dir (directory at specified path on lond side does not exist). 
13230: 
13231: =item 
13232: empty (directory at specified path on lond side is empty).
13233: 
13234: =over
13235: 
13236: This is currently not encountered because the &ls3, &ls2, 
13237: &ls (_handler) routines on the lond side do not filter out
13238: . and .. from a directory listing. 
13239: 
13240: =back
13241: 
13242: =back
13243: 
13244: =back
13245: 
13246: =item *
13247: 
13248: spareserver() : find server with least workload from spare.tab
13249: 
13250: 
13251: =item *
13252: 
13253: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13254: if there is no corresponding loncapa host.
13255: 
13256: =back
13257: 
13258: 
13259: =head2 Apache Request
13260: 
13261: =over 4
13262: 
13263: =item *
13264: 
13265: ssi($url,%hash) : server side include, does a complete request cycle on url to
13266: localhost, posts hash
13267: 
13268: =back
13269: 
13270: =head2 Data to String to Data
13271: 
13272: =over 4
13273: 
13274: =item *
13275: 
13276: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13277: and '&' separators, supports elements that are arrayrefs and hashrefs
13278: 
13279: =item *
13280: 
13281: hashref2str($hashref) : convert a hashref into a string complete with
13282: escaping and '=' and '&' separators, supports elements that are
13283: arrayrefs and hashrefs
13284: 
13285: =item *
13286: 
13287: arrayref2str($arrayref) : convert an arrayref into a string complete
13288: with escaping and '&' separators, supports elements that are arrayrefs
13289: and hashrefs
13290: 
13291: =item *
13292: 
13293: str2hash($string) : convert string to hash using unescaping and
13294: splitting on '=' and '&', supports elements that are arrayrefs and
13295: hashrefs
13296: 
13297: =item *
13298: 
13299: str2array($string) : convert string to hash using unescaping and
13300: splitting on '&', supports elements that are arrayrefs and hashrefs
13301: 
13302: =back
13303: 
13304: =head2 Logging Routines
13305: 
13306: 
13307: These routines allow one to make log messages in the lonnet.log and
13308: lonnet.perm logfiles.
13309: 
13310: =over 4
13311: 
13312: =item *
13313: 
13314: logtouch() : make sure the logfile, lonnet.log, exists
13315: 
13316: =item *
13317: 
13318: logthis() : append message to the normal lonnet.log file, it gets
13319: preiodically rolled over and deleted.
13320: 
13321: =item *
13322: 
13323: logperm() : append a permanent message to lonnet.perm.log, this log
13324: file never gets deleted by any automated portion of the system, only
13325: messages of critical importance should go in here.
13326: 
13327: 
13328: =back
13329: 
13330: =head2 General File Helper Routines
13331: 
13332: =over 4
13333: 
13334: =item *
13335: 
13336: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13337: (a) files in /uploaded
13338:   (i) If a local copy of the file exists - 
13339:       compares modification date of local copy with last-modified date for 
13340:       definitive version stored on home server for course. If local copy is 
13341:       stale, requests a new version from the home server and stores it. 
13342:       If the original has been removed from the home server, then local copy 
13343:       is unlinked.
13344:   (ii) If local copy does not exist -
13345:       requests the file from the home server and stores it. 
13346:   
13347:   If $caller is 'uploadrep':  
13348:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13349:     for request for files originally uploaded via DOCS. 
13350:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13351:   
13352:   Otherwise:
13353:      This indicates a call from the content generation phase of the request.
13354:      -  returns the entire contents of the file or -1.
13355:      
13356: (b) files in /res
13357:    - returns the entire contents of a file or -1; 
13358:    it properly subscribes to and replicates the file if neccessary.
13359: 
13360: 
13361: =item *
13362: 
13363: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13364:                   reference
13365: 
13366: returns either a stat() list of data about the file or an empty list
13367: if the file doesn't exist or couldn't find out about it (connection
13368: problems or user unknown)
13369: 
13370: =item *
13371: 
13372: filelocation($dir,$file) : returns file system location of a file
13373: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13374: directory that relative $file lookups are to looked in ($dir of /a/dir
13375: and a file of ../bob will become /a/bob)
13376: 
13377: =item *
13378: 
13379: hreflocation($dir,$file) : returns file system location or a URL; same as
13380: filelocation except for hrefs
13381: 
13382: =item *
13383: 
13384: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13385: 
13386: =back
13387: 
13388: =head2 Usererfile file routines (/uploaded*)
13389: 
13390: =over 4
13391: 
13392: =item *
13393: 
13394: userfileupload(): main rotine for putting a file in a user or course's
13395:                   filespace, arguments are,
13396: 
13397:  formname - required - this is the name of the element in $env where the
13398:            filename, and the contents of the file to create/modifed exist
13399:            the filename is in $env{'form.'.$formname.'.filename'} and the
13400:            contents of the file is located in $env{'form.'.$formname}
13401:  context - if coursedoc, store the file in the course of the active role
13402:              of the current user; 
13403:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13404:            if 'canceloverwrite': delete file in tmp/overwrites directory
13405:  subdir - required - subdirectory to put the file in under ../userfiles/
13406:          if undefined, it will be placed in "unknown"
13407: 
13408:  (This routine calls clean_filename() to remove any dangerous
13409:  characters from the filename, and then calls finuserfileupload() to
13410:  complete the transaction)
13411: 
13412:  returns either the url of the uploaded file (/uploaded/....) if successful
13413:  and /adm/notfound.html if unsuccessful
13414: 
13415: =item *
13416: 
13417: clean_filename(): routine for cleaing a filename up for storage in
13418:                  userfile space, argument is:
13419: 
13420:  filename - proposed filename
13421: 
13422: returns: the new clean filename
13423: 
13424: =item *
13425: 
13426: finishuserfileupload(): routine that creates and sends the file to
13427: userspace, probably shouldn't be called directly
13428: 
13429:   docuname: username or courseid of destination for the file
13430:   docudom: domain of user/course of destination for the file
13431:   formname: same as for userfileupload()
13432:   fname: filename (including subdirectories) for the file
13433:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13434:   allfiles: reference to hash used to store objects found by parser
13435:   codebase: reference to hash used for codebases of java objects found by parser
13436:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13437:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13438:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13439:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13440:   context: if 'overwrite', will move the uploaded file from its temporary location to
13441:             userfiles to facilitate overwriting a previously uploaded file with same name.
13442:   mimetype: reference to scalar to accommodate mime type determined
13443:             from File::MMagic if $parser = parse.
13444: 
13445:  returns either the url of the uploaded file (/uploaded/....) if successful
13446:  and /adm/notfound.html if unsuccessful (or an error message if context 
13447:  was 'overwrite').
13448:  
13449: 
13450: =item *
13451: 
13452: renameuserfile(): renames an existing userfile to a new name
13453: 
13454:   Args:
13455:    docuname: username or courseid of destination for the file
13456:    docudom: domain of user/course of destination for the file
13457:    old: current file name (including any subdirs under userfiles)
13458:    new: desired file name (including any subdirs under userfiles)
13459: 
13460: =item *
13461: 
13462: mkdiruserfile(): creates a directory is a userfiles dir
13463: 
13464:   Args:
13465:    docuname: username or courseid of destination for the file
13466:    docudom: domain of user/course of destination for the file
13467:    dir: dir to create (including any subdirs under userfiles)
13468: 
13469: =item *
13470: 
13471: removeuserfile(): removes a file that exists in userfiles
13472: 
13473:   Args:
13474:    docuname: username or courseid of destination for the file
13475:    docudom: domain of user/course of destination for the file
13476:    fname: filname to delete (including any subdirs under userfiles)
13477: 
13478: =item *
13479: 
13480: removeuploadedurl(): convience function for removeuserfile()
13481: 
13482:   Args:
13483:    url:  a full /uploaded/... url to delete
13484: 
13485: =item * 
13486: 
13487: get_portfile_permissions():
13488:   Args:
13489:     domain: domain of user or course contain the portfolio files
13490:     user: name of user or num of course contain the portfolio files
13491:   Returns:
13492:     hashref of a dump of the proper file_permissions.db
13493:    
13494: 
13495: =item * 
13496: 
13497: get_access_controls():
13498: 
13499: Args:
13500:   current_permissions: the hash ref returned from get_portfile_permissions()
13501:   group: (optional) the group you want the files associated with
13502:   file: (optional) the file you want access info on
13503: 
13504: Returns:
13505:     a hash (keys are file names) of hashes containing
13506:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13507:         values are XML containing access control settings (see below) 
13508: 
13509: Internal notes:
13510: 
13511:  access controls are stored in file_permissions.db as key=value pairs.
13512:     key -> path to file/file_name\0uniqueID:scope_end_start
13513:         where scope -> public,guest,course,group,domains or users.
13514:               end -> UNIX time for end of access (0 -> no end date)
13515:               start -> UNIX time for start of access
13516: 
13517:     value -> XML description of access control
13518:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13519:             <start></start>
13520:             <end></end>
13521: 
13522:             <password></password>  for scope type = guest
13523: 
13524:             <domain></domain>     for scope type = course or group
13525:             <number></number>
13526:             <roles id="">
13527:              <role></role>
13528:              <access></access>
13529:              <section></section>
13530:              <group></group>
13531:             </roles>
13532: 
13533:             <dom></dom>         for scope type = domains
13534: 
13535:             <users>             for scope type = users
13536:              <user>
13537:               <uname></uname>
13538:               <udom></udom>
13539:              </user>
13540:             </users>
13541:            </scope> 
13542:               
13543:  Access data is also aggregated for each file in an additional key=value pair:
13544:  key -> path to file/file_name\0accesscontrol 
13545:  value -> reference to hash
13546:           hash contains key = value pairs
13547:           where key = uniqueID:scope_end_start
13548:                 value = UNIX time record was last updated
13549: 
13550:           Used to improve speed of look-ups of access controls for each file.  
13551:  
13552:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13553: 
13554: =item *
13555: 
13556: modify_access_controls():
13557: 
13558: Modifies access controls for a portfolio file
13559: Args
13560: 1. file name
13561: 2. reference to hash of required changes,
13562: 3. domain
13563: 4. username
13564:   where domain,username are the domain of the portfolio owner 
13565:   (either a user or a course) 
13566: 
13567: Returns:
13568: 1. result of additions or updates ('ok' or 'error', with error message). 
13569: 2. result of deletions ('ok' or 'error', with error message).
13570: 3. reference to hash of any new or updated access controls.
13571: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13572:    key = integer (inbound ID)
13573:    value = uniqueID
13574: 
13575: =item *
13576: 
13577: get_timebased_id():
13578: 
13579: Attempts to get a unique timestamp-based suffix for use with items added to a 
13580: course via the Course Editor (e.g., folders, composite pages, 
13581: group bulletin boards).
13582: 
13583: Args: (first three required; six others optional)
13584: 
13585: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13586:    docssequence, or name of group
13587: 
13588: 2. keyid (alphanumeric): name of temporary locking key in hash,
13589:    e.g., num, boardids
13590: 
13591: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13592:    file will be named nohist_namespace.db
13593: 
13594: 4. cdom: domain of course; default is current course domain from %env
13595: 
13596: 5. cnum: course number; default is current course number from %env
13597: 
13598: 6. idtype: set to concat if an additional digit is to be appended to the 
13599:    unix timestamp to form the suffix, if the plain timestamp is already
13600:    in use.  Default is to not do this, but simply increment the unix 
13601:    timestamp by 1 until a unique key is obtained.
13602: 
13603: 7. who: holder of locking key; defaults to user:domain for user.
13604: 
13605: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13606:    retrying); default is 3.
13607: 
13608: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13609: 
13610: Returns:
13611: 
13612: 1. suffix obtained (numeric)
13613: 
13614: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13615: 
13616: 3. error: contains (localized) error message if an error occurred.
13617: 
13618: 
13619: =back
13620: 
13621: =head2 HTTP Helper Routines
13622: 
13623: =over 4
13624: 
13625: =item *
13626: 
13627: escape() : unpack non-word characters into CGI-compatible hex codes
13628: 
13629: =item *
13630: 
13631: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13632: 
13633: =back
13634: 
13635: =head1 PRIVATE SUBROUTINES
13636: 
13637: =head2 Underlying communication routines (Shouldn't call)
13638: 
13639: =over 4
13640: 
13641: =item *
13642: 
13643: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13644: 
13645: =item *
13646: 
13647: reply() : uses subreply to send a message to remote machine, logs all failures
13648: 
13649: =item *
13650: 
13651: critical() : passes a critical message to another server; if cannot
13652: get through then place message in connection buffer directory and
13653: returns con_delayed, if incapable of saving message, returns
13654: con_failed
13655: 
13656: =item *
13657: 
13658: reconlonc() : tries to reconnect lonc client processes.
13659: 
13660: =back
13661: 
13662: =head2 Resource Access Logging
13663: 
13664: =over 4
13665: 
13666: =item *
13667: 
13668: flushcourselogs() : flush (save) buffer logs and access logs
13669: 
13670: =item *
13671: 
13672: courselog($what) : save message for course in hash
13673: 
13674: =item *
13675: 
13676: courseacclog($what) : save message for course using &courselog().  Perform
13677: special processing for specific resource types (problems, exams, quizzes, etc).
13678: 
13679: =item *
13680: 
13681: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13682: as a PerlChildExitHandler
13683: 
13684: =back
13685: 
13686: =head2 Other
13687: 
13688: =over 4
13689: 
13690: =item *
13691: 
13692: symblist($mapname,%newhash) : update symbolic storage links
13693: 
13694: =back
13695: 
13696: =cut
13697: 

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