File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1245: download - view: text, annotated - select for diffs
Fri Dec 13 02:10:33 2013 UTC (10 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support Apache 2.4
  - PerlAuthenHandler needs to set $r->user() for requests for <Location>
    directives which include Require valid-user
  - reverse changes in publiccheck.pm rev. 1.20 and 1.21
  - modify changes in lonacc.pm rev. 1.143 and 1.147
  - reverse changes in lonnet.pm rev. 1.1212 and 1.1213, and modify changes
    in rev. 1.1244 (no longer treating 2.4 as a special case).
- Apache access logs will now include username (or username:domain if user's
  domain is not server's default domain) for URLs requiring "valid-user",
- Apache access logs will now include 'public' as requester for image
  files from /res/adm/pages and also domain logos etc.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1245 2013/12/13 02:10:33 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
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 if ($uint_dom) {
  853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  854:                                                  $try_server));
  855:                 }
  856: 	        ($spare_server, $lowest_load) =
  857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  858:             }
  859:         }
  860: 
  861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  862: 
  863:         if (!$found_server) {
  864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  866:                     if ($uint_dom) {
  867:                         next unless (&spare_can_host($udom,$uint_dom,
  868:                                                      $remotesessions,$try_server));
  869:                     }
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load) = @_;
  894: 
  895:     my $loadans     = &reply('load',    $try_server);
  896:     my $userloadans = &reply('userload',$try_server);
  897: 
  898:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  899: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  900:     }
  901: 
  902:     my $load;
  903:     if ($loadans =~ /\d/) {
  904: 	if ($userloadans =~ /\d/) {
  905: 	    #both are numbers, pick the bigger one
  906: 	    $load = ($loadans > $userloadans) ? $loadans 
  907: 		                              : $userloadans;
  908: 	} else {
  909: 	    $load = $loadans;
  910: 	}
  911:     } else {
  912: 	$load = $userloadans;
  913:     }
  914: 
  915:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  916: 	$spare_server = $try_server;
  917: 	$lowest_load  = $load;
  918:     }
  919:     return ($spare_server,$lowest_load);
  920: }
  921: 
  922: # --------------------------- ask offload servers if user already has a session
  923: sub find_existing_session {
  924:     my ($udom,$uname) = @_;
  925:     my $spareshash = &this_host_spares($udom);
  926:     if (ref($spareshash) eq 'HASH') {
  927:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  928:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  929:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  930:             }
  931:         }
  932:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  933:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  935:             }
  936:         }
  937:     }
  938:     return;
  939: }
  940: 
  941: # -------------------------------- ask if server already has a session for user
  942: sub has_user_session {
  943:     my ($lonid,$udom,$uname) = @_;
  944:     my $result = &reply(join(':','userhassession',
  945: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  946:     return 1 if ($result eq 'ok');
  947: 
  948:     return 0;
  949: }
  950: 
  951: # --------- determine least loaded server in a user's domain which allows login
  952: 
  953: sub choose_server {
  954:     my ($udom,$checkloginvia) = @_;
  955:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  956:     my %servers = &get_servers($udom);
  957:     my $lowest_load = 30000;
  958:     my ($login_host,$hostname,$portal_path,$isredirect);
  959:     foreach my $lonhost (keys(%servers)) {
  960:         my $loginvia;
  961:         if ($checkloginvia) {
  962:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  963:             if ($loginvia) {
  964:                 my ($server,$path) = split(/:/,$loginvia);
  965:                 ($login_host, $lowest_load) =
  966:                     &compare_server_load($server, $login_host, $lowest_load);
  967:                 if ($login_host eq $server) {
  968:                     $portal_path = $path;
  969:                     $isredirect = 1;
  970:                 }
  971:             } else {
  972:                 ($login_host, $lowest_load) =
  973:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  974:                 if ($login_host eq $lonhost) {
  975:                     $portal_path = '';
  976:                     $isredirect = ''; 
  977:                 }
  978:             }
  979:         } else {
  980:             ($login_host, $lowest_load) =
  981:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  982:         }
  983:     }
  984:     if ($login_host ne '') {
  985:         $hostname = &hostname($login_host);
  986:     }
  987:     return ($login_host,$hostname,$portal_path,$isredirect);
  988: }
  989: 
  990: # --------------------------------------------- Try to change a user's password
  991: 
  992: sub changepass {
  993:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  994:     $currentpass = &escape($currentpass);
  995:     $newpass     = &escape($newpass);
  996:     my $lonhost = $perlvar{'lonHostID'};
  997:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  998: 		       $server);
  999:     if (! $answer) {
 1000: 	&logthis("No reply on password change request to $server ".
 1001: 		 "by $uname in domain $udom.");
 1002:     } elsif ($answer =~ "^ok") {
 1003:         &logthis("$uname in $udom successfully changed their password ".
 1004: 		 "on $server.");
 1005:     } elsif ($answer =~ "^pwchange_failure") {
 1006: 	&logthis("$uname in $udom was unable to change their password ".
 1007: 		 "on $server.  The action was blocked by either lcpasswd ".
 1008: 		 "or pwchange");
 1009:     } elsif ($answer =~ "^non_authorized") {
 1010:         &logthis("$uname in $udom did not get their password correct when ".
 1011: 		 "attempting to change it on $server.");
 1012:     } elsif ($answer =~ "^auth_mode_error") {
 1013:         &logthis("$uname in $udom attempted to change their password despite ".
 1014: 		 "not being locally or internally authenticated on $server.");
 1015:     } elsif ($answer =~ "^unknown_user") {
 1016:         &logthis("$uname in $udom attempted to change their password ".
 1017: 		 "on $server but were unable to because $server is not ".
 1018: 		 "their home server.");
 1019:     } elsif ($answer =~ "^refused") {
 1020: 	&logthis("$server refused to change $uname in $udom password because ".
 1021: 		 "it was sent an unencrypted request to change the password.");
 1022:     } elsif ($answer =~ "invalid_client") {
 1023:         &logthis("$server refused to change $uname in $udom password because ".
 1024:                  "it was a reset by e-mail originating from an invalid server.");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # ----------------------- Try to determine user's current authentication scheme
 1030: 
 1031: sub queryauthenticate {
 1032:     my ($uname,$udom)=@_;
 1033:     my $uhome=&homeserver($uname,$udom);
 1034:     if (!$uhome) {
 1035: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1036: 	return 'no_host';
 1037:     }
 1038:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1039:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1040: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1041:     }
 1042:     return $answer;
 1043: }
 1044: 
 1045: # --------- Try to authenticate user from domain's lib servers (first this one)
 1046: 
 1047: sub authenticate {
 1048:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1049:     $upass=&escape($upass);
 1050:     $uname= &LONCAPA::clean_username($uname);
 1051:     my $uhome=&homeserver($uname,$udom,1);
 1052:     my $newhome;
 1053:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1054: # Maybe the machine was offline and only re-appeared again recently?
 1055:         &reconlonc();
 1056: # One more
 1057: 	$uhome=&homeserver($uname,$udom,1);
 1058:         if (($uhome eq 'no_host') && $checkdefauth) {
 1059:             if (defined(&domain($udom,'primary'))) {
 1060:                 $newhome=&domain($udom,'primary');
 1061:             }
 1062:             if ($newhome ne '') {
 1063:                 $uhome = $newhome;
 1064:             }
 1065:         }
 1066: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1067: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1068: 	    return 'no_host';
 1069:         }
 1070:     }
 1071:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1072:     if ($answer eq 'authorized') {
 1073:         if ($newhome) {
 1074:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1075:             return 'no_account_on_host'; 
 1076:         } else {
 1077:             &logthis("User $uname at $udom authorized by $uhome");
 1078:             return $uhome;
 1079:         }
 1080:     }
 1081:     if ($answer eq 'non_authorized') {
 1082: 	&logthis("User $uname at $udom rejected by $uhome");
 1083: 	return 'no_host'; 
 1084:     }
 1085:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1086:     return 'no_host';
 1087: }
 1088: 
 1089: sub can_host_session {
 1090:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1091:     my $canhost = 1;
 1092:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1093:     if (ref($remotesessions) eq 'HASH') {
 1094:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1095:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1096:                 $canhost = 0;
 1097:             } else {
 1098:                 $canhost = 1;
 1099:             }
 1100:         }
 1101:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1102:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1103:                 $canhost = 1;
 1104:             } else {
 1105:                 $canhost = 0;
 1106:             }
 1107:         }
 1108:         if ($canhost) {
 1109:             if ($remotesessions->{'version'} ne '') {
 1110:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1111:                 if ($reqmajor ne '' && $reqminor ne '') {
 1112:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1113:                         my $major = $1;
 1114:                         my $minor = $2;
 1115:                         if (($major < $reqmajor ) ||
 1116:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1117:                             $canhost = 0;
 1118:                         }
 1119:                     } else {
 1120:                         $canhost = 0;
 1121:                     }
 1122:                 }
 1123:             }
 1124:         }
 1125:     }
 1126:     if ($canhost) {
 1127:         if (ref($hostedsessions) eq 'HASH') {
 1128:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1129:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1130:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1131:                 if (($uint_dom ne '') && 
 1132:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1133:                     $canhost = 0;
 1134:                 } else {
 1135:                     $canhost = 1;
 1136:                 }
 1137:             }
 1138:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1139:                 if (($uint_dom ne '') && 
 1140:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1141:                     $canhost = 1;
 1142:                 } else {
 1143:                     $canhost = 0;
 1144:                 }
 1145:             }
 1146:         }
 1147:     }
 1148:     return $canhost;
 1149: }
 1150: 
 1151: sub spare_can_host {
 1152:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1153:     my $canhost=1;
 1154:     my @intdoms;
 1155:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1156:     if (ref($internet_names) eq 'ARRAY') {
 1157:         @intdoms = @{$internet_names};
 1158:     }
 1159:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1160:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1161:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1162:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1163:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1164:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1165:                                      $remotesessions,
 1166:                                      $defdomdefaults{'hostedsessions'});
 1167:     }
 1168:     return $canhost;
 1169: }
 1170: 
 1171: sub this_host_spares {
 1172:     my ($dom) = @_;
 1173:     my ($dom_in_use,$lonhost_in_use,$result);
 1174:     my @hosts = &current_machine_ids();
 1175:     foreach my $lonhost (@hosts) {
 1176:         if (&host_domain($lonhost) eq $dom) {
 1177:             $dom_in_use = $dom;
 1178:             $lonhost_in_use = $lonhost;
 1179:             last;
 1180:         }
 1181:     }
 1182:     if ($dom_in_use ne '') {
 1183:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1184:     }
 1185:     if (ref($result) ne 'HASH') {
 1186:         $lonhost_in_use = $perlvar{'lonHostID'};
 1187:         $dom_in_use = &host_domain($lonhost_in_use);
 1188:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1189:         if (ref($result) ne 'HASH') {
 1190:             $result = \%spareid;
 1191:         }
 1192:     }
 1193:     return $result;
 1194: }
 1195: 
 1196: sub spares_for_offload  {
 1197:     my ($dom_in_use,$lonhost_in_use) = @_;
 1198:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1199:     if (defined($cached)) {
 1200:         return $result;
 1201:     } else {
 1202:         my $cachetime = 60*60*24;
 1203:         my %domconfig =
 1204:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1205:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1206:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1207:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1208:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1209:                 }
 1210:             }
 1211:         }
 1212:     }
 1213:     return;
 1214: }
 1215: 
 1216: sub get_lonbalancer_config {
 1217:     my ($servers) = @_;
 1218:     my ($currbalancer,$currtargets);
 1219:     if (ref($servers) eq 'HASH') {
 1220:         foreach my $server (keys(%{$servers})) {
 1221:             my %what = (
 1222:                          spareid => 1,
 1223:                          perlvar => 1,
 1224:                        );
 1225:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1226:             if ($result eq 'ok') {
 1227:                 if (ref($returnhash) eq 'HASH') {
 1228:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1229:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1230:                             $currbalancer = $server;
 1231:                             $currtargets = {};
 1232:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1233:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1234:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1235:                                 }
 1236:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1237:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1238:                                 }
 1239:                             }
 1240:                             last;
 1241:                         }
 1242:                     }
 1243:                 }
 1244:             }
 1245:         }
 1246:     }
 1247:     return ($currbalancer,$currtargets);
 1248: }
 1249: 
 1250: sub check_loadbalancing {
 1251:     my ($uname,$udom) = @_;
 1252:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1253:         $rule_in_effect,$offloadto,$otherserver);
 1254:     my $lonhost = $perlvar{'lonHostID'};
 1255:     my @hosts = &current_machine_ids();
 1256:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1257:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1258:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1259:     my $serverhomedom = &host_domain($lonhost);
 1260: 
 1261:     my $cachetime = 60*60*24;
 1262: 
 1263:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1264:         $dom_in_use = $udom;
 1265:         $homeintdom = 1;
 1266:     } else {
 1267:         $dom_in_use = $serverhomedom;
 1268:     }
 1269:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1270:     unless (defined($cached)) {
 1271:         my %domconfig =
 1272:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1273:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1274:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1275:         }
 1276:     }
 1277:     if (ref($result) eq 'HASH') {
 1278:         ($is_balancer,$currtargets,$currrules) = 
 1279:             &check_balancer_result($result,@hosts);
 1280:         if ($is_balancer) {
 1281:             if (ref($currrules) eq 'HASH') {
 1282:                 if ($homeintdom) {
 1283:                     if ($uname ne '') {
 1284:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1285:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1286:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1288:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1289:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1290:                             }
 1291:                         }
 1292:                         if ($rule_in_effect eq '') {
 1293:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1294:                             if ($userenv{'inststatus'} ne '') {
 1295:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1296:                                 my ($othertitle,$usertypes,$types) =
 1297:                                     &Apache::loncommon::sorted_inst_types($udom);
 1298:                                 if (ref($types) eq 'ARRAY') {
 1299:                                     foreach my $type (@{$types}) {
 1300:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1301:                                             if (exists($currrules->{$type})) {
 1302:                                                 $rule_in_effect = $currrules->{$type};
 1303:                                             }
 1304:                                         }
 1305:                                     }
 1306:                                 }
 1307:                             } else {
 1308:                                 if (exists($currrules->{'default'})) {
 1309:                                     $rule_in_effect = $currrules->{'default'};
 1310:                                 }
 1311:                             }
 1312:                         }
 1313:                     } else {
 1314:                         if (exists($currrules->{'default'})) {
 1315:                             $rule_in_effect = $currrules->{'default'};
 1316:                         }
 1317:                     }
 1318:                 } else {
 1319:                     if ($currrules->{'_LC_external'} ne '') {
 1320:                         $rule_in_effect = $currrules->{'_LC_external'};
 1321:                     }
 1322:                 }
 1323:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1324:                                                        $uname,$udom);
 1325:             }
 1326:         }
 1327:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1328:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1329:         unless (defined($cached)) {
 1330:             my %domconfig =
 1331:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1332:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1333:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1334:             }
 1335:         }
 1336:         if (ref($result) eq 'HASH') {
 1337:             ($is_balancer,$currtargets,$currrules) = 
 1338:                 &check_balancer_result($result,@hosts);
 1339:             if ($is_balancer) {
 1340:                 if (ref($currrules) eq 'HASH') {
 1341:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1342:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1343:                     }
 1344:                 }
 1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1346:                                                        $uname,$udom);
 1347:             }
 1348:         } else {
 1349:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1350:                 $is_balancer = 1;
 1351:                 $offloadto = &this_host_spares($dom_in_use);
 1352:             }
 1353:         }
 1354:     } else {
 1355:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1356:             $is_balancer = 1;
 1357:             $offloadto = &this_host_spares($dom_in_use);
 1358:         }
 1359:     }
 1360:     if ($is_balancer) {
 1361:         my $lowest_load = 30000;
 1362:         if (ref($offloadto) eq 'HASH') {
 1363:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1364:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1365:                     ($otherserver,$lowest_load) =
 1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                 }
 1368:             }
 1369:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1370: 
 1371:             if (!$found_server) {
 1372:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1373:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1374:                         ($otherserver,$lowest_load) =
 1375:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1376:                     }
 1377:                 }
 1378:             }
 1379:         } elsif (ref($offloadto) eq 'ARRAY') {
 1380:             if (@{$offloadto} == 1) {
 1381:                 $otherserver = $offloadto->[0];
 1382:             } elsif (@{$offloadto} > 1) {
 1383:                 foreach my $try_server (@{$offloadto}) {
 1384:                     ($otherserver,$lowest_load) =
 1385:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1386:                 }
 1387:             }
 1388:         }
 1389:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1390:             $is_balancer = 0;
 1391:             if ($uname ne '' && $udom ne '') {
 1392:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1393:                     
 1394:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1395:                              'user.loadbalcheck.time' => time});
 1396:                 }
 1397:             }
 1398:         }
 1399:     }
 1400:     return ($is_balancer,$otherserver);
 1401: }
 1402: 
 1403: sub check_balancer_result {
 1404:     my ($result,@hosts) = @_;
 1405:     my ($is_balancer,$currtargets,$currrules);
 1406:     if (ref($result) eq 'HASH') {
 1407:         if ($result->{'lonhost'} ne '') {
 1408:             my $currbalancer = $result->{'lonhost'};
 1409:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1410:                 $is_balancer = 1;
 1411:                 $currtargets = $result->{'targets'};
 1412:                 $currrules = $result->{'rules'};
 1413:             }
 1414:         } else {
 1415:             foreach my $key (keys(%{$result})) {
 1416:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1417:                     (ref($result->{$key}) eq 'HASH')) {
 1418:                     $is_balancer = 1;
 1419:                     $currrules = $result->{$key}{'rules'};
 1420:                     $currtargets = $result->{$key}{'targets'};
 1421:                     last;
 1422:                 }
 1423:             }
 1424:         }
 1425:     }
 1426:     return ($is_balancer,$currtargets,$currrules);
 1427: }
 1428: 
 1429: sub get_loadbalancer_targets {
 1430:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1431:     my $offloadto;
 1432:     if ($rule_in_effect eq 'none') {
 1433:         return [$perlvar{'lonHostID'}];
 1434:     } elsif ($rule_in_effect eq '') {
 1435:         $offloadto = $currtargets;
 1436:     } else {
 1437:         if ($rule_in_effect eq 'homeserver') {
 1438:             my $homeserver = &homeserver($uname,$udom);
 1439:             if ($homeserver ne 'no_host') {
 1440:                 $offloadto = [$homeserver];
 1441:             }
 1442:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1443:             my %domconfig =
 1444:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1445:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1446:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1447:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1448:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1449:                     }
 1450:                 }
 1451:             } else {
 1452:                 my %servers = &internet_dom_servers($udom);
 1453:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1454:                 if (&hostname($remotebalancer) ne '') {
 1455:                     $offloadto = [$remotebalancer];
 1456:                 }
 1457:             }
 1458:         } elsif (&hostname($rule_in_effect) ne '') {
 1459:             $offloadto = [$rule_in_effect];
 1460:         }
 1461:     }
 1462:     return $offloadto;
 1463: }
 1464: 
 1465: sub internet_dom_servers {
 1466:     my ($dom) = @_;
 1467:     my (%uniqservers,%servers);
 1468:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1469:     my @machinedoms = &machine_domains($primaryserver);
 1470:     foreach my $mdom (@machinedoms) {
 1471:         my %currservers = %servers;
 1472:         my %server = &get_servers($mdom);
 1473:         %servers = (%currservers,%server);
 1474:     }
 1475:     my %by_hostname;
 1476:     foreach my $id (keys(%servers)) {
 1477:         push(@{$by_hostname{$servers{$id}}},$id);
 1478:     }
 1479:     foreach my $hostname (sort(keys(%by_hostname))) {
 1480:         if (@{$by_hostname{$hostname}} > 1) {
 1481:             my $match = 0;
 1482:             foreach my $id (@{$by_hostname{$hostname}}) {
 1483:                 if (&host_domain($id) eq $dom) {
 1484:                     $uniqservers{$id} = $hostname;
 1485:                     $match = 1;
 1486:                 }
 1487:             }
 1488:             unless ($match) {
 1489:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1490:             }
 1491:         } else {
 1492:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1493:         }
 1494:     }
 1495:     return %uniqservers;
 1496: }
 1497: 
 1498: # ---------------------- Find the homebase for a user from domain's lib servers
 1499: 
 1500: my %homecache;
 1501: sub homeserver {
 1502:     my ($uname,$udom,$ignoreBadCache)=@_;
 1503:     my $index="$uname:$udom";
 1504: 
 1505:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1506: 
 1507:     my %servers = &get_servers($udom,'library');
 1508:     foreach my $tryserver (keys(%servers)) {
 1509:         next if ($ignoreBadCache ne 'true' && 
 1510: 		 exists($badServerCache{$tryserver}));
 1511: 
 1512: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1513: 	if ($answer eq 'found') {
 1514: 	    delete($badServerCache{$tryserver}); 
 1515: 	    return $homecache{$index}=$tryserver;
 1516: 	} elsif ($answer eq 'no_host') {
 1517: 	    $badServerCache{$tryserver}=1;
 1518: 	}
 1519:     }    
 1520:     return 'no_host';
 1521: }
 1522: 
 1523: # ------------------------------------- Find the usernames behind a list of IDs
 1524: 
 1525: sub idget {
 1526:     my ($udom,@ids)=@_;
 1527:     my %returnhash=();
 1528:     
 1529:     my %servers = &get_servers($udom,'library');
 1530:     foreach my $tryserver (keys(%servers)) {
 1531: 	my $idlist=join('&',@ids);
 1532: 	$idlist=~tr/A-Z/a-z/; 
 1533: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1534: 	my @answer=();
 1535: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1536: 	    @answer=split(/\&/,$reply);
 1537: 	}                    ;
 1538: 	my $i;
 1539: 	for ($i=0;$i<=$#ids;$i++) {
 1540: 	    if ($answer[$i]) {
 1541: 		$returnhash{$ids[$i]}=$answer[$i];
 1542: 	    } 
 1543: 	}
 1544:     } 
 1545:     return %returnhash;
 1546: }
 1547: 
 1548: # ------------------------------------- Find the IDs behind a list of usernames
 1549: 
 1550: sub idrget {
 1551:     my ($udom,@unames)=@_;
 1552:     my %returnhash=();
 1553:     foreach my $uname (@unames) {
 1554:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1555:     }
 1556:     return %returnhash;
 1557: }
 1558: 
 1559: # ------------------------------- Store away a list of names and associated IDs
 1560: 
 1561: sub idput {
 1562:     my ($udom,%ids)=@_;
 1563:     my %servers=();
 1564:     foreach my $uname (keys(%ids)) {
 1565: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1566:         my $uhom=&homeserver($uname,$udom);
 1567:         if ($uhom ne 'no_host') {
 1568:             my $id=&escape($ids{$uname});
 1569:             $id=~tr/A-Z/a-z/;
 1570:             my $esc_unam=&escape($uname);
 1571: 	    if ($servers{$uhom}) {
 1572: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1573:             } else {
 1574:                 $servers{$uhom}=$id.'='.$esc_unam;
 1575:             }
 1576:         }
 1577:     }
 1578:     foreach my $server (keys(%servers)) {
 1579:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1580:     }
 1581: }
 1582: 
 1583: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1584: 
 1585: sub iddel {
 1586:     my ($udom,$idshashref,$uhome)=@_;
 1587:     my %result=();
 1588:     unless (ref($idshashref) eq 'HASH') {
 1589:         return %result;
 1590:     }
 1591:     my %servers=();
 1592:     while (my ($id,$uname) = each(%{$idshashref})) {
 1593:         my $uhom;
 1594:         if ($uhome) {
 1595:             $uhom = $uhome;
 1596:         } else {
 1597:             $uhom=&homeserver($uname,$udom);
 1598:         }
 1599:         if ($uhom ne 'no_host') {
 1600:             if ($servers{$uhom}) {
 1601:                 $servers{$uhom}.='&'.&escape($id);
 1602:             } else {
 1603:                 $servers{$uhom}=&escape($id);
 1604:             }
 1605:         }
 1606:     }
 1607:     foreach my $server (keys(%servers)) {
 1608:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1609:     }
 1610:     return %result;
 1611: }
 1612: 
 1613: # ------------------------------dump from db file owned by domainconfig user
 1614: sub dump_dom {
 1615:     my ($namespace, $udom, $regexp) = @_;
 1616: 
 1617:     $udom ||= $env{'user.domain'};
 1618: 
 1619:     return () unless $udom;
 1620: 
 1621:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1622: }
 1623: 
 1624: # ------------------------------------------ get items from domain db files   
 1625: 
 1626: sub get_dom {
 1627:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1628:     my $items='';
 1629:     foreach my $item (@$storearr) {
 1630:         $items.=&escape($item).'&';
 1631:     }
 1632:     $items=~s/\&$//;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     }
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1649:         my %returnhash;
 1650:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1651:             return %returnhash;
 1652:         }
 1653:         my @pairs=split(/\&/,$rep);
 1654:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1655:             return @pairs;
 1656:         }
 1657:         my $i=0;
 1658:         foreach my $item (@$storearr) {
 1659:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1660:             $i++;
 1661:         }
 1662:         return %returnhash;
 1663:     } else {
 1664:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1665:     }
 1666: }
 1667: 
 1668: # -------------------------------------------- put items in domain db files 
 1669: 
 1670: sub put_dom {
 1671:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1672:     if (!$udom) {
 1673:         $udom=$env{'user.domain'};
 1674:         if (defined(&domain($udom,'primary'))) {
 1675:             $uhome=&domain($udom,'primary');
 1676:         } else {
 1677:             undef($uhome);
 1678:         }
 1679:     } else {
 1680:         if (!$uhome) {
 1681:             if (defined(&domain($udom,'primary'))) {
 1682:                 $uhome=&domain($udom,'primary');
 1683:             }
 1684:         }
 1685:     } 
 1686:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1687:         my $items='';
 1688:         foreach my $item (keys(%$storehash)) {
 1689:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1690:         }
 1691:         $items=~s/\&$//;
 1692:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1693:     } else {
 1694:         &logthis("put_dom failed - no homeserver and/or domain");
 1695:     }
 1696: }
 1697: 
 1698: # --------------------- newput for items in db file owned by domainconfig user
 1699: sub newput_dom {
 1700:     my ($namespace,$storehash,$udom) = @_;
 1701:     my $result;
 1702:     if (!$udom) {
 1703:         $udom=$env{'user.domain'};
 1704:     }
 1705:     if ($udom) {
 1706:         my $uname = &get_domainconfiguser($udom);
 1707:         $result = &newput($namespace,$storehash,$udom,$uname);
 1708:     }
 1709:     return $result;
 1710: }
 1711: 
 1712: # --------------------- delete for items in db file owned by domainconfig user
 1713: sub del_dom {
 1714:     my ($namespace,$storearr,$udom)=@_;
 1715:     if (ref($storearr) eq 'ARRAY') {
 1716:         if (!$udom) {
 1717:             $udom=$env{'user.domain'};
 1718:         }
 1719:         if ($udom) {
 1720:             my $uname = &get_domainconfiguser($udom); 
 1721:             return &del($namespace,$storearr,$udom,$uname);
 1722:         }
 1723:     }
 1724: }
 1725: 
 1726: # ----------------------------------construct domainconfig user for a domain 
 1727: sub get_domainconfiguser {
 1728:     my ($udom) = @_;
 1729:     return $udom.'-domainconfig';
 1730: }
 1731: 
 1732: sub retrieve_inst_usertypes {
 1733:     my ($udom) = @_;
 1734:     my (%returnhash,@order);
 1735:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1736:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1737:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1738:         %returnhash = %{$domdefs{'inststatustypes'}};
 1739:         @order = @{$domdefs{'inststatusorder'}};
 1740:     } else {
 1741:         if (defined(&domain($udom,'primary'))) {
 1742:             my $uhome=&domain($udom,'primary');
 1743:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1744:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1745:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1746:                 return (\%returnhash,\@order);
 1747:             }
 1748:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1749:             my @pairs=split(/\&/,$hashitems);
 1750:             foreach my $item (@pairs) {
 1751:                 my ($key,$value)=split(/=/,$item,2);
 1752:                 $key = &unescape($key);
 1753:                 next if ($key =~ /^error: 2 /);
 1754:                 $returnhash{$key}=&thaw_unescape($value);
 1755:             }
 1756:             my @esc_order = split(/\&/,$orderitems);
 1757:             foreach my $item (@esc_order) {
 1758:                 push(@order,&unescape($item));
 1759:             }
 1760:         } else {
 1761:             &logthis("get_dom failed - no primary domain server for $udom");
 1762:         }
 1763:     }
 1764:     return (\%returnhash,\@order);
 1765: }
 1766: 
 1767: sub is_domainimage {
 1768:     my ($url) = @_;
 1769:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1770:         if (&domain($1) ne '') {
 1771:             return '1';
 1772:         }
 1773:     }
 1774:     return;
 1775: }
 1776: 
 1777: sub inst_directory_query {
 1778:     my ($srch) = @_;
 1779:     my $udom = $srch->{'srchdomain'};
 1780:     my %results;
 1781:     my $homeserver = &domain($udom,'primary');
 1782:     my $outcome;
 1783:     if ($homeserver ne '') {
 1784: 	my $queryid=&reply("querysend:instdirsearch:".
 1785: 			   &escape($srch->{'srchby'}).':'.
 1786: 			   &escape($srch->{'srchterm'}).':'.
 1787: 			   &escape($srch->{'srchtype'}),$homeserver);
 1788: 	my $host=&hostname($homeserver);
 1789: 	if ($queryid !~/^\Q$host\E\_/) {
 1790: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1791: 	    return;
 1792: 	}
 1793: 	my $response = &get_query_reply($queryid);
 1794: 	my $maxtries = 5;
 1795: 	my $tries = 1;
 1796: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1797: 	    $response = &get_query_reply($queryid);
 1798: 	    $tries ++;
 1799: 	}
 1800: 
 1801:         if (!&error($response) && $response ne 'refused') {
 1802:             if ($response eq 'unavailable') {
 1803:                 $outcome = $response;
 1804:             } else {
 1805:                 $outcome = 'ok';
 1806:                 my @matches = split(/\n/,$response);
 1807:                 foreach my $match (@matches) {
 1808:                     my ($key,$value) = split(/=/,$match);
 1809:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1810:                 }
 1811:             }
 1812:         }
 1813:     }
 1814:     return ($outcome,%results);
 1815: }
 1816: 
 1817: sub usersearch {
 1818:     my ($srch) = @_;
 1819:     my $dom = $srch->{'srchdomain'};
 1820:     my %results;
 1821:     my %libserv = &all_library();
 1822:     my $query = 'usersearch';
 1823:     foreach my $tryserver (keys(%libserv)) {
 1824:         if (&host_domain($tryserver) eq $dom) {
 1825:             my $host=&hostname($tryserver);
 1826:             my $queryid=
 1827:                 &reply("querysend:".&escape($query).':'.
 1828:                        &escape($srch->{'srchby'}).':'.
 1829:                        &escape($srch->{'srchtype'}).':'.
 1830:                        &escape($srch->{'srchterm'}),$tryserver);
 1831:             if ($queryid !~/^\Q$host\E\_/) {
 1832:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1833:                 next;
 1834:             }
 1835:             my $reply = &get_query_reply($queryid);
 1836:             my $maxtries = 1;
 1837:             my $tries = 1;
 1838:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1839:                 $reply = &get_query_reply($queryid);
 1840:                 $tries ++;
 1841:             }
 1842:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1843:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1844:             } else {
 1845:                 my @matches;
 1846:                 if ($reply =~ /\n/) {
 1847:                     @matches = split(/\n/,$reply);
 1848:                 } else {
 1849:                     @matches = split(/\&/,$reply);
 1850:                 }
 1851:                 foreach my $match (@matches) {
 1852:                     my ($uname,$udom,%userhash);
 1853:                     foreach my $entry (split(/:/,$match)) {
 1854:                         my ($key,$value) =
 1855:                             map {&unescape($_);} split(/=/,$entry);
 1856:                         $userhash{$key} = $value;
 1857:                         if ($key eq 'username') {
 1858:                             $uname = $value;
 1859:                         } elsif ($key eq 'domain') {
 1860:                             $udom = $value;
 1861:                         }
 1862:                     }
 1863:                     $results{$uname.':'.$udom} = \%userhash;
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868:     return %results;
 1869: }
 1870: 
 1871: sub get_instuser {
 1872:     my ($udom,$uname,$id) = @_;
 1873:     my $homeserver = &domain($udom,'primary');
 1874:     my ($outcome,%results);
 1875:     if ($homeserver ne '') {
 1876:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1877:                            &escape($id).':'.&escape($udom),$homeserver);
 1878:         my $host=&hostname($homeserver);
 1879:         if ($queryid !~/^\Q$host\E\_/) {
 1880:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1881:             return;
 1882:         }
 1883:         my $response = &get_query_reply($queryid);
 1884:         my $maxtries = 5;
 1885:         my $tries = 1;
 1886:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1887:             $response = &get_query_reply($queryid);
 1888:             $tries ++;
 1889:         }
 1890:         if (!&error($response) && $response ne 'refused') {
 1891:             if ($response eq 'unavailable') {
 1892:                 $outcome = $response;
 1893:             } else {
 1894:                 $outcome = 'ok';
 1895:                 my @matches = split(/\n/,$response);
 1896:                 foreach my $match (@matches) {
 1897:                     my ($key,$value) = split(/=/,$match);
 1898:                     $results{&unescape($key)} = &thaw_unescape($value);
 1899:                 }
 1900:             }
 1901:         }
 1902:     }
 1903:     my %userinfo;
 1904:     if (ref($results{$uname}) eq 'HASH') {
 1905:         %userinfo = %{$results{$uname}};
 1906:     } 
 1907:     return ($outcome,%userinfo);
 1908: }
 1909: 
 1910: sub inst_rulecheck {
 1911:     my ($udom,$uname,$id,$item,$rules) = @_;
 1912:     my %returnhash;
 1913:     if ($udom ne '') {
 1914:         if (ref($rules) eq 'ARRAY') {
 1915:             @{$rules} = map {&escape($_);} (@{$rules});
 1916:             my $rulestr = join(':',@{$rules});
 1917:             my $homeserver=&domain($udom,'primary');
 1918:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1919:                 my $response;
 1920:                 if ($item eq 'username') {                
 1921:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1922:                                               ':'.&escape($uname).':'.$rulestr,
 1923:                                               $homeserver));
 1924:                 } elsif ($item eq 'id') {
 1925:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1926:                                               ':'.&escape($id).':'.$rulestr,
 1927:                                               $homeserver));
 1928:                 } elsif ($item eq 'selfcreate') {
 1929:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1930:                                                &escape($udom).':'.&escape($uname).
 1931:                                               ':'.$rulestr,$homeserver));
 1932:                 }
 1933:                 if ($response ne 'refused') {
 1934:                     my @pairs=split(/\&/,$response);
 1935:                     foreach my $item (@pairs) {
 1936:                         my ($key,$value)=split(/=/,$item,2);
 1937:                         $key = &unescape($key);
 1938:                         next if ($key =~ /^error: 2 /);
 1939:                         $returnhash{$key}=&thaw_unescape($value);
 1940:                     }
 1941:                 }
 1942:             }
 1943:         }
 1944:     }
 1945:     return %returnhash;
 1946: }
 1947: 
 1948: sub inst_userrules {
 1949:     my ($udom,$check) = @_;
 1950:     my (%ruleshash,@ruleorder);
 1951:     if ($udom ne '') {
 1952:         my $homeserver=&domain($udom,'primary');
 1953:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1954:             my $response;
 1955:             if ($check eq 'id') {
 1956:                 $response=&reply('instidrules:'.&escape($udom),
 1957:                                  $homeserver);
 1958:             } elsif ($check eq 'email') {
 1959:                 $response=&reply('instemailrules:'.&escape($udom),
 1960:                                  $homeserver);
 1961:             } else {
 1962:                 $response=&reply('instuserrules:'.&escape($udom),
 1963:                                  $homeserver);
 1964:             }
 1965:             if (($response ne 'refused') && ($response ne 'error') && 
 1966:                 ($response ne 'unknown_cmd') && 
 1967:                 ($response ne 'no_such_host')) {
 1968:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1969:                 my @pairs=split(/\&/,$hashitems);
 1970:                 foreach my $item (@pairs) {
 1971:                     my ($key,$value)=split(/=/,$item,2);
 1972:                     $key = &unescape($key);
 1973:                     next if ($key =~ /^error: 2 /);
 1974:                     $ruleshash{$key}=&thaw_unescape($value);
 1975:                 }
 1976:                 my @esc_order = split(/\&/,$orderitems);
 1977:                 foreach my $item (@esc_order) {
 1978:                     push(@ruleorder,&unescape($item));
 1979:                 }
 1980:             }
 1981:         }
 1982:     }
 1983:     return (\%ruleshash,\@ruleorder);
 1984: }
 1985: 
 1986: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1987: 
 1988: sub get_domain_defaults {
 1989:     my ($domain,$ignore_cache) = @_;
 1990:     return if (($domain eq '') || ($domain eq 'public'));
 1991:     my $cachetime = 60*60*24;
 1992:     unless ($ignore_cache) {
 1993:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1994:         if (defined($cached)) {
 1995:             if (ref($result) eq 'HASH') {
 1996:                 return %{$result};
 1997:             }
 1998:         }
 1999:     }
 2000:     my %domdefaults;
 2001:     my %domconfig =
 2002:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2003:                                   'requestcourses','inststatus',
 2004:                                   'coursedefaults','usersessions',
 2005:                                   'requestauthor'],$domain);
 2006:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2007:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2008:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2009:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2010:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2011:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2012:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2013:     } else {
 2014:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2015:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2016:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2017:     }
 2018:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2019:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2020:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2021:         } else {
 2022:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2023:         }
 2024:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2025:         foreach my $item (@usertools) {
 2026:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2027:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2028:             }
 2029:         }
 2030:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2031:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2032:         }
 2033:     }
 2034:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2035:         foreach my $item ('official','unofficial','community') {
 2036:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2037:         }
 2038:     }
 2039:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2040:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2041:     }
 2042:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2043:         foreach my $item ('inststatustypes','inststatusorder') {
 2044:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2045:         }
 2046:     }
 2047:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2048:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2049:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2050:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2051:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2052:         }
 2053:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2054:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2055:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2056:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2057:         }
 2058:     }
 2059:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2060:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2061:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2062:         }
 2063:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2064:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2065:         }
 2066:     }
 2067:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2068:     return %domdefaults;
 2069: }
 2070: 
 2071: # --------------------------------------------------- Assign a key to a student
 2072: 
 2073: sub assign_access_key {
 2074: #
 2075: # a valid key looks like uname:udom#comments
 2076: # comments are being appended
 2077: #
 2078:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2079:     $kdom=
 2080:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2081:     $knum=
 2082:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2083:     $cdom=
 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2085:     $cnum=
 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2087:     $udom=$env{'user.name'} unless (defined($udom));
 2088:     $uname=$env{'user.domain'} unless (defined($uname));
 2089:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2090:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2091:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2092:                                                   # assigned to this person
 2093:                                                   # - this should not happen,
 2094:                                                   # unless something went wrong
 2095:                                                   # the first time around
 2096: # ready to assign
 2097:         $logentry=$1.'; '.$logentry;
 2098:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2099:                                                  $kdom,$knum) eq 'ok') {
 2100: # key now belongs to user
 2101: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2102:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2103:                 &appenv({'environment.'.$envkey => $ckey});
 2104:                 return 'ok';
 2105:             } else {
 2106:                 return 
 2107:   'error: Count not permanently assign key, will need to be re-entered later.';
 2108: 	    }
 2109:         } else {
 2110:             return 'error: Could not assign key, try again later.';
 2111:         }
 2112:     } elsif (!$existing{$ckey}) {
 2113: # the key does not exist
 2114: 	return 'error: The key does not exist';
 2115:     } else {
 2116: # the key is somebody else's
 2117: 	return 'error: The key is already in use';
 2118:     }
 2119: }
 2120: 
 2121: # ------------------------------------------ put an additional comment on a key
 2122: 
 2123: sub comment_access_key {
 2124: #
 2125: # a valid key looks like uname:udom#comments
 2126: # comments are being appended
 2127: #
 2128:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2129:     $cdom=
 2130:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2131:     $cnum=
 2132:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2133:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2134:     if ($existing{$ckey}) {
 2135:         $existing{$ckey}.='; '.$logentry;
 2136: # ready to assign
 2137:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2138:                                                  $cdom,$cnum) eq 'ok') {
 2139: 	    return 'ok';
 2140:         } else {
 2141: 	    return 'error: Count not store comment.';
 2142:         }
 2143:     } else {
 2144: # the key does not exist
 2145: 	return 'error: The key does not exist';
 2146:     }
 2147: }
 2148: 
 2149: # ------------------------------------------------------ Generate a set of keys
 2150: 
 2151: sub generate_access_keys {
 2152:     my ($number,$cdom,$cnum,$logentry)=@_;
 2153:     $cdom=
 2154:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2155:     $cnum=
 2156:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2157:     unless (&allowed('mky',$cdom)) { return 0; }
 2158:     unless (($cdom) && ($cnum)) { return 0; }
 2159:     if ($number>10000) { return 0; }
 2160:     sleep(2); # make sure don't get same seed twice
 2161:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2162:     my $total=0;
 2163:     for (my $i=1;$i<=$number;$i++) {
 2164:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2165:                   sprintf("%lx",int(100000*rand)).'-'.
 2166:                   sprintf("%lx",int(100000*rand));
 2167:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2168:        $newkey=~s/0/h/g; # and also 0 and O
 2169:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2170:        if ($existing{$newkey}) {
 2171:            $i--;
 2172:        } else {
 2173: 	  if (&put('accesskeys',
 2174:               { $newkey => '# generated '.localtime().
 2175:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2176:                            '; '.$logentry },
 2177: 		   $cdom,$cnum) eq 'ok') {
 2178:               $total++;
 2179: 	  }
 2180:        }
 2181:     }
 2182:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2183:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2184:     return $total;
 2185: }
 2186: 
 2187: # ------------------------------------------------------- Validate an accesskey
 2188: 
 2189: sub validate_access_key {
 2190:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2191:     $cdom=
 2192:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2193:     $cnum=
 2194:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2195:     $udom=$env{'user.domain'} unless (defined($udom));
 2196:     $uname=$env{'user.name'} unless (defined($uname));
 2197:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2198:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2199: }
 2200: 
 2201: # ------------------------------------- Find the section of student in a course
 2202: sub devalidate_getsection_cache {
 2203:     my ($udom,$unam,$courseid)=@_;
 2204:     my $hashid="$udom:$unam:$courseid";
 2205:     &devalidate_cache_new('getsection',$hashid);
 2206: }
 2207: 
 2208: sub courseid_to_courseurl {
 2209:     my ($courseid) = @_;
 2210:     #already url style courseid
 2211:     return $courseid if ($courseid =~ m{^/});
 2212: 
 2213:     if (exists($env{'course.'.$courseid.'.num'})) {
 2214: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2215: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2216: 	return "/$cdom/$cnum";
 2217:     }
 2218: 
 2219:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2220:     if (exists($courseinfo{'num'})) {
 2221: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2222:     }
 2223: 
 2224:     return undef;
 2225: }
 2226: 
 2227: sub getsection {
 2228:     my ($udom,$unam,$courseid)=@_;
 2229:     my $cachetime=1800;
 2230: 
 2231:     my $hashid="$udom:$unam:$courseid";
 2232:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2233:     if (defined($cached)) { return $result; }
 2234: 
 2235:     my %Pending; 
 2236:     my %Expired;
 2237:     #
 2238:     # Each role can either have not started yet (pending), be active, 
 2239:     #    or have expired.
 2240:     #
 2241:     # If there is an active role, we are done.
 2242:     #
 2243:     # If there is more than one role which has not started yet, 
 2244:     #     choose the one which will start sooner
 2245:     # If there is one role which has not started yet, return it.
 2246:     #
 2247:     # If there is more than one expired role, choose the one which ended last.
 2248:     # If there is a role which has expired, return it.
 2249:     #
 2250:     $courseid = &courseid_to_courseurl($courseid);
 2251:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2252:     foreach my $key (keys(%roleshash)) {
 2253:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2254:         my $section=$1;
 2255:         if ($key eq $courseid.'_st') { $section=''; }
 2256:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2257:         my $now=time;
 2258:         if (defined($end) && $end && ($now > $end)) {
 2259:             $Expired{$end}=$section;
 2260:             next;
 2261:         }
 2262:         if (defined($start) && $start && ($now < $start)) {
 2263:             $Pending{$start}=$section;
 2264:             next;
 2265:         }
 2266:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2267:     }
 2268:     #
 2269:     # Presumedly there will be few matching roles from the above
 2270:     # loop and the sorting time will be negligible.
 2271:     if (scalar(keys(%Pending))) {
 2272:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2273:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2274:     } 
 2275:     if (scalar(keys(%Expired))) {
 2276:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2277:         my $time = pop(@sorted);
 2278:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2279:     }
 2280:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2281: }
 2282: 
 2283: sub save_cache {
 2284:     &purge_remembered();
 2285:     #&Apache::loncommon::validate_page();
 2286:     undef(%env);
 2287:     undef($env_loaded);
 2288: }
 2289: 
 2290: my $to_remember=-1;
 2291: my %remembered;
 2292: my %accessed;
 2293: my $kicks=0;
 2294: my $hits=0;
 2295: sub make_key {
 2296:     my ($name,$id) = @_;
 2297:     if (length($id) > 65 
 2298: 	&& length(&escape($id)) > 200) {
 2299: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2300:     }
 2301:     return &escape($name.':'.$id);
 2302: }
 2303: 
 2304: sub devalidate_cache_new {
 2305:     my ($name,$id,$debug) = @_;
 2306:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2307:     $id=&make_key($name,$id);
 2308:     $memcache->delete($id);
 2309:     delete($remembered{$id});
 2310:     delete($accessed{$id});
 2311: }
 2312: 
 2313: sub is_cached_new {
 2314:     my ($name,$id,$debug) = @_;
 2315:     $id=&make_key($name,$id);
 2316:     if (exists($remembered{$id})) {
 2317: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2318: 	$accessed{$id}=[&gettimeofday()];
 2319: 	$hits++;
 2320: 	return ($remembered{$id},1);
 2321:     }
 2322:     my $value = $memcache->get($id);
 2323:     if (!(defined($value))) {
 2324: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2325: 	return (undef,undef);
 2326:     }
 2327:     if ($value eq '__undef__') {
 2328: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2329: 	$value=undef;
 2330:     }
 2331:     &make_room($id,$value,$debug);
 2332:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2333:     return ($value,1);
 2334: }
 2335: 
 2336: sub do_cache_new {
 2337:     my ($name,$id,$value,$time,$debug) = @_;
 2338:     $id=&make_key($name,$id);
 2339:     my $setvalue=$value;
 2340:     if (!defined($setvalue)) {
 2341: 	$setvalue='__undef__';
 2342:     }
 2343:     if (!defined($time) ) {
 2344: 	$time=600;
 2345:     }
 2346:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2347:     my $result = $memcache->set($id,$setvalue,$time);
 2348:     if (! $result) {
 2349: 	&logthis("caching of id -> $id  failed");
 2350: 	$memcache->disconnect_all();
 2351:     }
 2352:     # need to make a copy of $value
 2353:     &make_room($id,$value,$debug);
 2354:     return $value;
 2355: }
 2356: 
 2357: sub make_room {
 2358:     my ($id,$value,$debug)=@_;
 2359: 
 2360:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2361:                                     : $value;
 2362:     if ($to_remember<0) { return; }
 2363:     $accessed{$id}=[&gettimeofday()];
 2364:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2365:     my $to_kick;
 2366:     my $max_time=0;
 2367:     foreach my $other (keys(%accessed)) {
 2368: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2369: 	    $to_kick=$other;
 2370: 	    $max_time=&tv_interval($accessed{$other});
 2371: 	}
 2372:     }
 2373:     delete($remembered{$to_kick});
 2374:     delete($accessed{$to_kick});
 2375:     $kicks++;
 2376:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2377:     return;
 2378: }
 2379: 
 2380: sub purge_remembered {
 2381:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2382:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2383:     undef(%remembered);
 2384:     undef(%accessed);
 2385: }
 2386: # ------------------------------------- Read an entry from a user's environment
 2387: 
 2388: sub userenvironment {
 2389:     my ($udom,$unam,@what)=@_;
 2390:     my $items;
 2391:     foreach my $item (@what) {
 2392:         $items.=&escape($item).'&';
 2393:     }
 2394:     $items=~s/\&$//;
 2395:     my %returnhash=();
 2396:     my $uhome = &homeserver($unam,$udom);
 2397:     unless ($uhome eq 'no_host') {
 2398:         my @answer=split(/\&/, 
 2399:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2400:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2401:             return %returnhash;
 2402:         }
 2403:         my $i;
 2404:         for ($i=0;$i<=$#what;$i++) {
 2405: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2406:         }
 2407:     }
 2408:     return %returnhash;
 2409: }
 2410: 
 2411: # ---------------------------------------------------------- Get a studentphoto
 2412: sub studentphoto {
 2413:     my ($udom,$unam,$ext) = @_;
 2414:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2415:     if (defined($env{'request.course.id'})) {
 2416:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2417:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2418:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2419:             } else {
 2420:                 my ($result,$perm_reqd)=
 2421: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2422:                 if ($result eq 'ok') {
 2423:                     if (!($perm_reqd eq 'yes')) {
 2424:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2425:                     }
 2426:                 }
 2427:             }
 2428:         }
 2429:     } else {
 2430:         my ($result,$perm_reqd) = 
 2431: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2432:         if ($result eq 'ok') {
 2433:             if (!($perm_reqd eq 'yes')) {
 2434:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2435:             }
 2436:         }
 2437:     }
 2438:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2439: }
 2440: 
 2441: sub retrievestudentphoto {
 2442:     my ($udom,$unam,$ext,$type) = @_;
 2443:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2444:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2445:     if ($ret eq 'ok') {
 2446:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2447:         if ($type eq 'thumbnail') {
 2448:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2449:         }
 2450:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2451:         return $tokenurl;
 2452:     } else {
 2453:         if ($type eq 'thumbnail') {
 2454:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2455:         } else { 
 2456:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2457:         }
 2458:     }
 2459: }
 2460: 
 2461: # -------------------------------------------------------------------- New chat
 2462: 
 2463: sub chatsend {
 2464:     my ($newentry,$anon,$group)=@_;
 2465:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2466:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2467:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2468:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2469: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2470: 		   &escape($newentry)).':'.$group,$chome);
 2471: }
 2472: 
 2473: # ------------------------------------------ Find current version of a resource
 2474: 
 2475: sub getversion {
 2476:     my $fname=&clutter(shift);
 2477:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2478:     return &currentversion(&filelocation('',$fname));
 2479: }
 2480: 
 2481: sub currentversion {
 2482:     my $fname=shift;
 2483:     my $author=$fname;
 2484:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2485:     my ($udom,$uname)=split(/\//,$author);
 2486:     my $home=&homeserver($uname,$udom);
 2487:     if ($home eq 'no_host') { 
 2488:         return -1; 
 2489:     }
 2490:     my $answer=&reply("currentversion:$fname",$home);
 2491:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2492: 	return -1;
 2493:     }
 2494:     return $answer;
 2495: }
 2496: 
 2497: #
 2498: # Return special version number of resource if set by override, empty otherwise
 2499: #
 2500: sub usedversion {
 2501:     my $fname=shift;
 2502:     unless ($fname) { $fname=$env{'request.uri'}; }
 2503:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2504:     if ($urlversion) { return $urlversion; }
 2505:     return '';
 2506: }
 2507: 
 2508: # ----------------------------- Subscribe to a resource, return URL if possible
 2509: 
 2510: sub subscribe {
 2511:     my $fname=shift;
 2512:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2513:     $fname=~s/[\n\r]//g;
 2514:     my $author=$fname;
 2515:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2516:     my ($udom,$uname)=split(/\//,$author);
 2517:     my $home=homeserver($uname,$udom);
 2518:     if ($home eq 'no_host') {
 2519:         return 'not_found';
 2520:     }
 2521:     my $answer=reply("sub:$fname",$home);
 2522:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2523: 	$answer.=' by '.$home;
 2524:     }
 2525:     return $answer;
 2526: }
 2527:     
 2528: # -------------------------------------------------------------- Replicate file
 2529: 
 2530: sub repcopy {
 2531:     my $filename=shift;
 2532:     $filename=~s/\/+/\//g;
 2533:     my $londocroot = $perlvar{'lonDocRoot'};
 2534:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2535:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2536:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2537: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2538: 	return &repcopy_userfile($filename);
 2539:     }
 2540:     $filename=~s/[\n\r]//g;
 2541:     my $transname="$filename.in.transfer";
 2542: # FIXME: this should flock
 2543:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2544:     my $remoteurl=subscribe($filename);
 2545:     if ($remoteurl =~ /^con_lost by/) {
 2546: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2547:            return 'unavailable';
 2548:     } elsif ($remoteurl eq 'not_found') {
 2549: 	   #&logthis("Subscribe returned not_found: $filename");
 2550: 	   return 'not_found';
 2551:     } elsif ($remoteurl =~ /^rejected by/) {
 2552: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2553:            return 'forbidden';
 2554:     } elsif ($remoteurl eq 'directory') {
 2555:            return 'ok';
 2556:     } else {
 2557:         my $author=$filename;
 2558:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2559:         my ($udom,$uname)=split(/\//,$author);
 2560:         my $home=homeserver($uname,$udom);
 2561:         unless ($home eq $perlvar{'lonHostID'}) {
 2562:            my @parts=split(/\//,$filename);
 2563:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2564:            if ($path ne "$londocroot/res") {
 2565:                &logthis("Malconfiguration for replication: $filename");
 2566: 	       return 'bad_request';
 2567:            }
 2568:            my $count;
 2569:            for ($count=5;$count<$#parts;$count++) {
 2570:                $path.="/$parts[$count]";
 2571:                if ((-e $path)!=1) {
 2572: 		   mkdir($path,0777);
 2573:                }
 2574:            }
 2575:            my $ua=new LWP::UserAgent;
 2576:            my $request=new HTTP::Request('GET',"$remoteurl");
 2577:            my $response=$ua->request($request,$transname);
 2578:            if ($response->is_error()) {
 2579: 	       unlink($transname);
 2580:                my $message=$response->status_line;
 2581:                &logthis("<font color=\"blue\">WARNING:"
 2582:                        ." LWP get: $message: $filename</font>");
 2583:                return 'unavailable';
 2584:            } else {
 2585: 	       if ($remoteurl!~/\.meta$/) {
 2586:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2587:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2588:                   if ($mresponse->is_error()) {
 2589: 		      unlink($filename.'.meta');
 2590:                       &logthis(
 2591:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2592:                   }
 2593: 	       }
 2594:                rename($transname,$filename);
 2595:                return 'ok';
 2596:            }
 2597:        }
 2598:     }
 2599: }
 2600: 
 2601: # ------------------------------------------------ Get server side include body
 2602: sub ssi_body {
 2603:     my ($filelink,%form)=@_;
 2604:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2605:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2606:     }
 2607:     my $output='';
 2608:     my $response;
 2609:     if ($filelink=~/^https?\:/) {
 2610:        ($output,$response)=&externalssi($filelink);
 2611:     } else {
 2612:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2613:        $filelink .= 'inhibitmenu=yes';
 2614:        ($output,$response)=&ssi($filelink,%form);
 2615:     }
 2616:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2617:     $output=~s/^.*?\<body[^\>]*\>//si;
 2618:     $output=~s/\<\/body\s*\>.*?$//si;
 2619:     if (wantarray) {
 2620:         return ($output, $response);
 2621:     } else {
 2622:         return $output;
 2623:     }
 2624: }
 2625: 
 2626: # --------------------------------------------------------- Server Side Include
 2627: 
 2628: sub absolute_url {
 2629:     my ($host_name) = @_;
 2630:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2631:     if ($host_name eq '') {
 2632: 	$host_name = $ENV{'SERVER_NAME'};
 2633:     }
 2634:     return $protocol.$host_name;
 2635: }
 2636: 
 2637: #
 2638: #   Server side include.
 2639: # Parameters:
 2640: #  fn     Possibly encrypted resource name/id.
 2641: #  form   Hash that describes how the rendering should be done
 2642: #         and other things.
 2643: # Returns:
 2644: #   Scalar context: The content of the response.
 2645: #   Array context:  2 element list of the content and the full response object.
 2646: #     
 2647: sub ssi {
 2648: 
 2649:     my ($fn,%form)=@_;
 2650:     my $ua=new LWP::UserAgent;
 2651:     my $request;
 2652: 
 2653:     $form{'no_update_last_known'}=1;
 2654:     &Apache::lonenc::check_encrypt(\$fn);
 2655:     if (%form) {
 2656:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2657:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2658:     } else {
 2659:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2660:     }
 2661: 
 2662:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2663:     my $response= $ua->request($request);
 2664:     my $content = $response->content;
 2665: 
 2666: 
 2667:     if (wantarray) {
 2668: 	return ($content, $response);
 2669:     } else {
 2670: 	return $content;
 2671:     }
 2672: }
 2673: 
 2674: sub externalssi {
 2675:     my ($url)=@_;
 2676:     my $ua=new LWP::UserAgent;
 2677:     my $request=new HTTP::Request('GET',$url);
 2678:     my $response=$ua->request($request);
 2679:     if (wantarray) {
 2680:         return ($response->content, $response);
 2681:     } else {
 2682:         return $response->content;
 2683:     }
 2684: }
 2685: 
 2686: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2687: 
 2688: sub allowuploaded {
 2689:     my ($srcurl,$url)=@_;
 2690:     $url=&clutter(&declutter($url));
 2691:     my $dir=$url;
 2692:     $dir=~s/\/[^\/]+$//;
 2693:     my %httpref=();
 2694:     my $httpurl=&hreflocation('',$url);
 2695:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2696:     &Apache::lonnet::appenv(\%httpref);
 2697: }
 2698: 
 2699: #
 2700: # Determine if the current user should be able to edit a particular resource,
 2701: # when viewing in course context.
 2702: # (a) When viewing resource used to determine if "Edit" item is included in 
 2703: #     Functions.
 2704: # (b) When displaying folder contents in course editor, used to determine if
 2705: #     "Edit" link will be displayed alongside resource.
 2706: #
 2707: #  input: six args -- filename (decluttered), course number, course domain,
 2708: #                   url, symb (if registered) and group (if this is a group
 2709: #                   item -- e.g., bulletin board, group page etc.).
 2710: #  output: array of five scalars -- 
 2711: #          $cfile -- url for file editing if editable on current server
 2712: #          $home -- homeserver of resource (i.e., for author if published,
 2713: #                                           or course if uploaded.).
 2714: #          $switchserver --  1 if server switch will be needed.
 2715: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2716: #          $forceview -- 1 if icon/link should be to go to view mode
 2717: #
 2718: 
 2719: sub can_edit_resource {
 2720:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2721:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2722: #
 2723: # For aboutme pages user can only edit his/her own.
 2724: #
 2725:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2726:         my ($sdom,$sname) = ($1,$2);
 2727:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2728:             $home = $env{'user.home'};
 2729:             $cfile = $resurl;
 2730:             if ($env{'form.forceedit'}) {
 2731:                 $forceview = 1;
 2732:             } else {
 2733:                 $forceedit = 1;
 2734:             }
 2735:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2736:         } else {
 2737:             return;
 2738:         }
 2739:     }
 2740: 
 2741:     if ($env{'request.course.id'}) {
 2742:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2743:         if ($group ne '') {
 2744: # if this is a group homepage or group bulletin board, check group privs
 2745:             my $allowed = 0;
 2746:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2747:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2748:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2749:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2750:                     $allowed = 1;
 2751:                 }
 2752:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2753:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2754:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2755:                     $allowed = 1;
 2756:                 }
 2757:             }
 2758:             if ($allowed) {
 2759:                 $home=&homeserver($cnum,$cdom);
 2760:                 if ($env{'form.forceedit'}) {
 2761:                     $forceview = 1;
 2762:                 } else {
 2763:                     $forceedit = 1;
 2764:                 }
 2765:                 $cfile = $resurl;
 2766:             } else {
 2767:                 return;
 2768:             }
 2769:         } else {
 2770:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2771:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2772:                     return;
 2773:                 }
 2774:             } elsif (!$crsedit) {
 2775: #
 2776: # No edit allowed where CC has switched to student role.
 2777: #
 2778:                 return;
 2779:             }
 2780:         }
 2781:     }
 2782: 
 2783:     if ($file ne '') {
 2784:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2785:             if (&is_course_upload($file,$cnum,$cdom)) {
 2786:                 $uploaded = 1;
 2787:                 $incourse = 1;
 2788:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2789:                     $cfile = &hreflocation('',$file);
 2790:                     if ($env{'form.forceedit'}) {
 2791:                         $forceview = 1;
 2792:                     } else {
 2793:                         $forceedit = 1;
 2794:                     }
 2795:                 }
 2796:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2797:                 $incourse = 1;
 2798:                 if ($env{'form.forceedit'}) {
 2799:                     $forceview = 1;
 2800:                 } else {
 2801:                     $forceedit = 1;
 2802:                 }
 2803:                 $cfile = $resurl;
 2804:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2805:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2806:                     $incourse = 1;
 2807:                     if ($env{'form.forceedit'}) {
 2808:                         $forceview = 1;
 2809:                     } else {
 2810:                         $forceedit = 1;
 2811:                     }
 2812:                     $cfile = $resurl;
 2813:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2814:                     $incourse = 1;
 2815:                     $cfile = $resurl.'/smpedit';
 2816:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2817:                     $incourse = 1;
 2818:                     if ($env{'form.forceedit'}) {
 2819:                         $forceview = 1;
 2820:                     } else {
 2821:                         $forceedit = 1;
 2822:                     }
 2823:                     $cfile = $resurl;
 2824:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2825:                     $incourse = 1;
 2826:                     if ($env{'form.forceedit'}) {
 2827:                         $forceview = 1;
 2828:                     } else {
 2829:                         $forceedit = 1;
 2830:                     }
 2831:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2832:                 }
 2833:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2834:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2835:                 if (&is_on_map($template)) { 
 2836:                     $incourse = 1;
 2837:                     $forceview = 1;
 2838:                     $cfile = $template;
 2839:                 }
 2840:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2841:                     $incourse = 1;
 2842:                     if ($env{'form.forceedit'}) {
 2843:                         $forceview = 1;
 2844:                     } else {
 2845:                         $forceedit = 1;
 2846:                     }
 2847:                     $cfile = $resurl;
 2848:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2849:                 $incourse = 1;
 2850:                 $forceview = 1;
 2851:                 if ($symb) {
 2852:                     my ($map,$id,$res)=&decode_symb($symb);
 2853:                     $env{'request.symb'} = $symb;
 2854:                     $cfile = &clutter($res);
 2855:                 } else {
 2856:                     $cfile = $env{'form.suppurl'};
 2857:                     $cfile =~ s{^http://}{};
 2858:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2859:                 }
 2860:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2861:                 if ($env{'form.forceedit'}) {
 2862:                     $forceview = 1;
 2863:                 } else {
 2864:                     $forceedit = 1;
 2865:                 }
 2866:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2867:             }
 2868:         }
 2869:         if ($uploaded || $incourse) {
 2870:             $home=&homeserver($cnum,$cdom);
 2871:         } elsif ($file !~ m{/$}) {
 2872:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2873:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2874:             # Check that the user has permission to edit this resource
 2875:             my $setpriv = 1;
 2876:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2877:             if (defined($cfudom)) {
 2878:                 $home=&homeserver($cfuname,$cfudom);
 2879:                 $cfile=$file;
 2880:             }
 2881:         }
 2882:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2883:             (($home ne '') && ($home ne 'no_host'))) {
 2884:             my @ids=&current_machine_ids();
 2885:             unless (grep(/^\Q$home\E$/,@ids)) {
 2886:                 $switchserver=1;
 2887:             }
 2888:         }
 2889:     }
 2890:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2891: }
 2892: 
 2893: sub is_course_upload {
 2894:     my ($file,$cnum,$cdom) = @_;
 2895:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2896:     $uploadpath =~ s{^\/}{};
 2897:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2898:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2899:         return 1;
 2900:     }
 2901:     return;
 2902: }
 2903: 
 2904: sub in_course {
 2905:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2906:     if ($hideprivileged) {
 2907:         my $skipuser;
 2908:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2909:         my @possdoms = ($cdom);  
 2910:         if ($coursehash{'checkforpriv'}) { 
 2911:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2912:         }
 2913:         if (&privileged($uname,$udom,\@possdoms)) {
 2914:             $skipuser = 1;
 2915:             if ($coursehash{'nothideprivileged'}) {
 2916:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2917:                     my $user;
 2918:                     if ($item =~ /:/) {
 2919:                         $user = $item;
 2920:                     } else {
 2921:                         $user = join(':',split(/[\@]/,$item));
 2922:                     }
 2923:                     if ($user eq $uname.':'.$udom) {
 2924:                         undef($skipuser);
 2925:                         last;
 2926:                     }
 2927:                 }
 2928:             }
 2929:             if ($skipuser) {
 2930:                 return 0;
 2931:             }
 2932:         }
 2933:     }
 2934:     $type ||= 'any';
 2935:     if (!defined($cdom) || !defined($cnum)) {
 2936:         my $cid  = $env{'request.course.id'};
 2937:         $cdom = $env{'course.'.$cid.'.domain'};
 2938:         $cnum = $env{'course.'.$cid.'.num'};
 2939:     }
 2940:     my $typesref;
 2941:     if (($type eq 'any') || ($type eq 'all')) {
 2942:         $typesref = ['active','previous','future'];
 2943:     } elsif ($type eq 'previous' || $type eq 'future') {
 2944:         $typesref = [$type];
 2945:     }
 2946:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2947:                               $typesref,undef,[$cdom]);
 2948:     my ($tmp) = keys(%roles);
 2949:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2950:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2951:     if (@course_roles > 0) {
 2952:         return 1;
 2953:     }
 2954:     return 0;
 2955: }
 2956: 
 2957: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2958: # input: action, courseID, current domain, intended
 2959: #        path to file, source of file, instruction to parse file for objects,
 2960: #        ref to hash for embedded objects,
 2961: #        ref to hash for codebase of java objects.
 2962: #        reference to scalar to accommodate mime type determined
 2963: #          from File::MMagic if $parser = parse.
 2964: #
 2965: # output: url to file (if action was uploaddoc), 
 2966: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2967: #
 2968: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2969: # course.
 2970: #
 2971: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2972: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2973: #          course's home server.
 2974: #
 2975: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2976: #          be copied from $source (current location) to 
 2977: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2978: #         and will then be copied to
 2979: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2980: #         course's home server.
 2981: #
 2982: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2983: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2984: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2985: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2986: #         in course's home server.
 2987: #
 2988: 
 2989: sub process_coursefile {
 2990:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2991:         $mimetype)=@_;
 2992:     my $fetchresult;
 2993:     my $home=&homeserver($docuname,$docudom);
 2994:     if ($action eq 'propagate') {
 2995:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2996: 			     $home);
 2997:     } else {
 2998:         my $fpath = '';
 2999:         my $fname = $file;
 3000:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3001:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3002:         my $filepath = &build_filepath($fpath);
 3003:         if ($action eq 'copy') {
 3004:             if ($source eq '') {
 3005:                 $fetchresult = 'no source file';
 3006:                 return $fetchresult;
 3007:             } else {
 3008:                 my $destination = $filepath.'/'.$fname;
 3009:                 rename($source,$destination);
 3010:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3011:                                  $home);
 3012:             }
 3013:         } elsif ($action eq 'uploaddoc') {
 3014:             open(my $fh,'>'.$filepath.'/'.$fname);
 3015:             print $fh $env{'form.'.$source};
 3016:             close($fh);
 3017:             if ($parser eq 'parse') {
 3018:                 my $mm = new File::MMagic;
 3019:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3020:                 if ($type eq 'text/html') {
 3021:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3022:                     unless ($parse_result eq 'ok') {
 3023:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3024:                     }
 3025:                 }
 3026:                 if (ref($mimetype)) {
 3027:                     $$mimetype = $type;
 3028:                 } 
 3029:             }
 3030:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3031:                                  $home);
 3032:             if ($fetchresult eq 'ok') {
 3033:                 return '/uploaded/'.$fpath.'/'.$fname;
 3034:             } else {
 3035:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3036:                         ' to host '.$home.': '.$fetchresult);
 3037:                 return '/adm/notfound.html';
 3038:             }
 3039:         }
 3040:     }
 3041:     unless ( $fetchresult eq 'ok') {
 3042:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3043:              ' to host '.$home.': '.$fetchresult);
 3044:     }
 3045:     return $fetchresult;
 3046: }
 3047: 
 3048: sub build_filepath {
 3049:     my ($fpath) = @_;
 3050:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3051:     unless ($fpath eq '') {
 3052:         my @parts=split('/',$fpath);
 3053:         foreach my $part (@parts) {
 3054:             $filepath.= '/'.$part;
 3055:             if ((-e $filepath)!=1) {
 3056:                 mkdir($filepath,0777);
 3057:             }
 3058:         }
 3059:     }
 3060:     return $filepath;
 3061: }
 3062: 
 3063: sub store_edited_file {
 3064:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3065:     my $file = $primary_url;
 3066:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3067:     my $fpath = '';
 3068:     my $fname = $file;
 3069:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3070:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3071:     my $filepath = &build_filepath($fpath);
 3072:     open(my $fh,'>'.$filepath.'/'.$fname);
 3073:     print $fh $content;
 3074:     close($fh);
 3075:     my $home=&homeserver($docuname,$docudom);
 3076:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3077: 			  $home);
 3078:     if ($$fetchresult eq 'ok') {
 3079:         return '/uploaded/'.$fpath.'/'.$fname;
 3080:     } else {
 3081:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3082: 		 ' to host '.$home.': '.$$fetchresult);
 3083:         return '/adm/notfound.html';
 3084:     }
 3085: }
 3086: 
 3087: sub clean_filename {
 3088:     my ($fname,$args)=@_;
 3089: # Replace Windows backslashes by forward slashes
 3090:     $fname=~s/\\/\//g;
 3091:     if (!$args->{'keep_path'}) {
 3092:         # Get rid of everything but the actual filename
 3093: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3094:     }
 3095: # Replace spaces by underscores
 3096:     $fname=~s/\s+/\_/g;
 3097: # Replace all other weird characters by nothing
 3098:     $fname=~s{[^/\w\.\-]}{}g;
 3099: # Replace all .\d. sequences with _\d. so they no longer look like version
 3100: # numbers
 3101:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3102:     return $fname;
 3103: }
 3104: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3105: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3106: # image with the same aspect ratio as the original, but with dimensions which do 
 3107: # not exceed $resizewidth and $resizeheight.
 3108:  
 3109: sub resizeImage {
 3110:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3111:     my $ima = Image::Magick->new;
 3112:     my $resized;
 3113:     if (-e $img_path) {
 3114:         $ima->Read($img_path);
 3115:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3116:             my $width = $ima->Get('width');
 3117:             my $height = $ima->Get('height');
 3118:             if ($width > $resizewidth) {
 3119: 	        my $factor = $width/$resizewidth;
 3120:                 my $newheight = $height/$factor;
 3121:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3122:                 $resized = 1;
 3123:             }
 3124:         }
 3125:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3126:             my $width = $ima->Get('width');
 3127:             my $height = $ima->Get('height');
 3128:             if ($height > $resizeheight) {
 3129:                 my $factor = $height/$resizeheight;
 3130:                 my $newwidth = $width/$factor;
 3131:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3132:                 $resized = 1;
 3133:             }
 3134:         }
 3135:         if ($resized) {
 3136:             $ima->Write($img_path);
 3137:         }
 3138:     }
 3139:     return;
 3140: }
 3141: 
 3142: # --------------- Take an uploaded file and put it into the userfiles directory
 3143: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3144: #                    the desired filename is in $env{"form.$formname.filename"}
 3145: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3146: #                                    canceloverwrite, or ''. 
 3147: #                   if 'coursedoc': upload to the current course
 3148: #                   if 'existingfile': write file to tmp/overwrites directory 
 3149: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3150: #                   $context is passed as argument to &finishuserfileupload
 3151: #        $subdir - directory in userfile to store the file into
 3152: #        $parser - instruction to parse file for objects ($parser = parse)    
 3153: #        $allfiles - reference to hash for embedded objects
 3154: #        $codebase - reference to hash for codebase of java objects
 3155: #        $desuname - username for permanent storage of uploaded file
 3156: #        $dsetudom - domain for permanaent storage of uploaded file
 3157: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3158: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3159: #        $resizewidth - width (pixels) to which to resize uploaded image
 3160: #        $resizeheight - height (pixels) to which to resize uploaded image
 3161: #        $mimetype - reference to scalar to accommodate mime type determined
 3162: #                    from File::MMagic.
 3163: # 
 3164: # output: url of file in userspace, or error: <message> 
 3165: #             or /adm/notfound.html if failure to upload occurse
 3166: 
 3167: sub userfileupload {
 3168:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3169:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3170:     if (!defined($subdir)) { $subdir='unknown'; }
 3171:     my $fname=$env{'form.'.$formname.'.filename'};
 3172:     $fname=&clean_filename($fname);
 3173:     # See if there is anything left
 3174:     unless ($fname) { return 'error: no uploaded file'; }
 3175:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3176:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3177:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3178:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3179:         my $now = time;
 3180:         my $filepath;
 3181:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3182:              $filepath = 'tmp/helprequests/'.$now;
 3183:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3184:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3185:                          '_'.$env{'user.domain'}.'/pending';
 3186:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3187:             my ($docuname,$docudom);
 3188:             if ($destudom) {
 3189:                 $docudom = $destudom;
 3190:             } else {
 3191:                 $docudom = $env{'user.domain'};
 3192:             }
 3193:             if ($destuname) {
 3194:                 $docuname = $destuname;
 3195:             } else {
 3196:                 $docuname = $env{'user.name'};
 3197:             }
 3198:             if (exists($env{'form.group'})) {
 3199:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3200:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3201:             }
 3202:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3203:             if ($context eq 'canceloverwrite') {
 3204:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3205:                 if (-e  $tempfile) {
 3206:                     my @info = stat($tempfile);
 3207:                     if ($info[9] eq $env{'form.timestamp'}) {
 3208:                         unlink($tempfile);
 3209:                     }
 3210:                 }
 3211:                 return;
 3212:             }
 3213:         }
 3214:         # Create the directory if not present
 3215:         my @parts=split(/\//,$filepath);
 3216:         my $fullpath = $perlvar{'lonDaemons'};
 3217:         for (my $i=0;$i<@parts;$i++) {
 3218:             $fullpath .= '/'.$parts[$i];
 3219:             if ((-e $fullpath)!=1) {
 3220:                 mkdir($fullpath,0777);
 3221:             }
 3222:         }
 3223:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3224:         print $fh $env{'form.'.$formname};
 3225:         close($fh);
 3226:         if ($context eq 'existingfile') {
 3227:             my @info = stat($fullpath.'/'.$fname);
 3228:             return ($fullpath.'/'.$fname,$info[9]);
 3229:         } else {
 3230:             return $fullpath.'/'.$fname;
 3231:         }
 3232:     }
 3233:     if ($subdir eq 'scantron') {
 3234:         $fname = 'scantron_orig_'.$fname;
 3235:     } else {
 3236:         $fname="$subdir/$fname";
 3237:     }
 3238:     if ($context eq 'coursedoc') {
 3239: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3240: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3241:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3242:             return &finishuserfileupload($docuname,$docudom,
 3243: 					 $formname,$fname,$parser,$allfiles,
 3244: 					 $codebase,$thumbwidth,$thumbheight,
 3245:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3246:         } else {
 3247:             if ($env{'form.folder'}) {
 3248:                 $fname=$env{'form.folder'}.'/'.$fname;
 3249:             }
 3250:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3251: 				       $fname,$formname,$parser,
 3252: 				       $allfiles,$codebase,$mimetype);
 3253:         }
 3254:     } elsif (defined($destuname)) {
 3255:         my $docuname=$destuname;
 3256:         my $docudom=$destudom;
 3257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3258: 				     $parser,$allfiles,$codebase,
 3259:                                      $thumbwidth,$thumbheight,
 3260:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3261:     } else {
 3262:         my $docuname=$env{'user.name'};
 3263:         my $docudom=$env{'user.domain'};
 3264:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3265:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3266:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3267:         }
 3268: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3269: 				     $parser,$allfiles,$codebase,
 3270:                                      $thumbwidth,$thumbheight,
 3271:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3272:     }
 3273: }
 3274: 
 3275: sub finishuserfileupload {
 3276:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3277:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3278:     my $path=$docudom.'/'.$docuname.'/';
 3279:     my $filepath=$perlvar{'lonDocRoot'};
 3280:   
 3281:     my ($fnamepath,$file,$fetchthumb);
 3282:     $file=$fname;
 3283:     if ($fname=~m|/|) {
 3284:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3285: 	$path.=$fnamepath.'/';
 3286:     }
 3287:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3288:     my $count;
 3289:     for ($count=4;$count<=$#parts;$count++) {
 3290:         $filepath.="/$parts[$count]";
 3291:         if ((-e $filepath)!=1) {
 3292: 	    mkdir($filepath,0777);
 3293:         }
 3294:     }
 3295: 
 3296: # Save the file
 3297:     {
 3298: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3299: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3300: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3301: 	    return '/adm/notfound.html';
 3302: 	}
 3303:         if ($context eq 'overwrite') {
 3304:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3305:             my $target = $filepath.'/'.$file;
 3306:             if (-e $source) {
 3307:                 my @info = stat($source);
 3308:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3309:                     unless (&File::Copy::move($source,$target)) {
 3310:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3311:                         return "Moving from $source failed";
 3312:                     }
 3313:                 } else {
 3314:                     return "Temporary file: $source had unexpected date/time for last modification";
 3315:                 }
 3316:             } else {
 3317:                 return "Temporary file: $source missing";
 3318:             }
 3319:         } elsif (!print FH ($env{'form.'.$formname})) {
 3320: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3321: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3322: 	    return '/adm/notfound.html';
 3323: 	}
 3324: 	close(FH);
 3325:         if ($resizewidth && $resizeheight) {
 3326:             my $mm = new File::MMagic;
 3327:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3328:             if ($mime_type =~ m{^image/}) {
 3329: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3330:             }  
 3331: 	}
 3332:     }
 3333:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3334:         if (ref($mimetype)) {
 3335:             if ($$mimetype eq '') {
 3336:                 my $mm = new File::MMagic;
 3337:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3338:                 $$mimetype = $type;
 3339:             }
 3340:         }
 3341:     }
 3342:     if ($parser eq 'parse') {
 3343:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3344:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3345:                                                        $allfiles,$codebase);
 3346:             unless ($parse_result eq 'ok') {
 3347:                 &logthis('Failed to parse '.$filepath.$file.
 3348: 	   	         ' for embedded media: '.$parse_result); 
 3349:             }
 3350:         }
 3351:     }
 3352:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3353:         my $input = $filepath.'/'.$file;
 3354:         my $output = $filepath.'/'.'tn-'.$file;
 3355:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3356:         system("convert -sample $thumbsize $input $output");
 3357:         if (-e $filepath.'/'.'tn-'.$file) {
 3358:             $fetchthumb  = 1; 
 3359:         }
 3360:     }
 3361:  
 3362: # Notify homeserver to grep it
 3363: #
 3364:     my $docuhome=&homeserver($docuname,$docudom);	
 3365:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3366:     if ($fetchresult eq 'ok') {
 3367:         if ($fetchthumb) {
 3368:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3369:             if ($thumbresult ne 'ok') {
 3370:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3371:                          $docuhome.': '.$thumbresult);
 3372:             }
 3373:         }
 3374: #
 3375: # Return the URL to it
 3376:         return '/uploaded/'.$path.$file;
 3377:     } else {
 3378:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3379: 		 ': '.$fetchresult);
 3380:         return '/adm/notfound.html';
 3381:     }
 3382: }
 3383: 
 3384: sub extract_embedded_items {
 3385:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3386:     my @state = ();
 3387:     my (%lastids,%related,%shockwave,%flashvars);
 3388:     my %javafiles = (
 3389:                       codebase => '',
 3390:                       code => '',
 3391:                       archive => ''
 3392:                     );
 3393:     my %mediafiles = (
 3394:                       src => '',
 3395:                       movie => '',
 3396:                      );
 3397:     my $p;
 3398:     if ($content) {
 3399:         $p = HTML::LCParser->new($content);
 3400:     } else {
 3401:         $p = HTML::LCParser->new($fullpath);
 3402:     }
 3403:     while (my $t=$p->get_token()) {
 3404: 	if ($t->[0] eq 'S') {
 3405: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3406: 	    push(@state, $tagname);
 3407:             if (lc($tagname) eq 'allow') {
 3408:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3409:             }
 3410: 	    if (lc($tagname) eq 'img') {
 3411: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3412: 	    }
 3413: 	    if (lc($tagname) eq 'a') {
 3414:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3415:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3416:                 }
 3417: 	    }
 3418:             if (lc($tagname) eq 'script') {
 3419:                 my $src;
 3420:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3421:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3422:                 } else {
 3423:                     if ($attr->{'src'} ne '') {
 3424:                         $src = $attr->{'src'};
 3425:                         &add_filetype($allfiles,$src,'src');
 3426:                     }
 3427:                 }
 3428:                 my $text = $p->get_trimmed_text();
 3429:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3430:                     my @swfargs = split(/,/,$1);
 3431:                     foreach my $item (@swfargs) {
 3432:                         $item =~ s/["']//g;
 3433:                         $item =~ s/^\s+//;
 3434:                         $item =~ s/\s+$//;
 3435:                     }
 3436:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3437:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3438:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3439:                         } else {
 3440:                             $related{$swfargs[0]} = [$swfargs[2]];
 3441:                         }
 3442:                     }
 3443:                 }
 3444:             }
 3445:             if (lc($tagname) eq 'link') {
 3446:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3447:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3448:                 }
 3449:             }
 3450: 	    if (lc($tagname) eq 'object' ||
 3451: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3452: 		foreach my $item (keys(%javafiles)) {
 3453: 		    $javafiles{$item} = '';
 3454: 		}
 3455:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3456:                     $lastids{lc($tagname)} = $attr->{'id'};
 3457:                 }
 3458: 	    }
 3459: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3460: 		my $name = lc($attr->{'name'});
 3461: 		foreach my $item (keys(%javafiles)) {
 3462: 		    if ($name eq $item) {
 3463: 			$javafiles{$item} = $attr->{'value'};
 3464: 			last;
 3465: 		    }
 3466: 		}
 3467:                 my $pathfrom;
 3468: 		foreach my $item (keys(%mediafiles)) {
 3469: 		    if ($name eq $item) {
 3470:                         $pathfrom = $attr->{'value'};
 3471:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3472: 			&add_filetype($allfiles,$pathfrom,$name);
 3473: 			last;
 3474: 		    }
 3475: 		}
 3476:                 if ($name eq 'flashvars') {
 3477:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3478:                 }
 3479:                 if ($pathfrom ne '') {
 3480:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3481:                                          $pathfrom);
 3482:                 }
 3483: 	    }
 3484: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3485: 		foreach my $item (keys(%javafiles)) {
 3486: 		    if ($attr->{$item}) {
 3487: 			$javafiles{$item} = $attr->{$item};
 3488: 			last;
 3489: 		    }
 3490: 		}
 3491: 		foreach my $item (keys(%mediafiles)) {
 3492: 		    if ($attr->{$item}) {
 3493: 			&add_filetype($allfiles,$attr->{$item},$item);
 3494: 			last;
 3495: 		    }
 3496: 		}
 3497:                 if (lc($tagname) eq 'embed') {
 3498:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3499:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3500:                                              $attr->{'src'});
 3501:                     }
 3502:                 }
 3503: 	    }
 3504:             if (lc($tagname) eq 'iframe') {
 3505:                 my $src = $attr->{'src'} ;
 3506:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3507:                     &add_filetype($allfiles,$src,'src');
 3508:                 } elsif ($src =~ m{^/}) {
 3509:                     if ($env{'request.course.id'}) {
 3510:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3511:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3512:                         my $url = &hreflocation('',$fullpath);
 3513:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3514:                             my $relpath = $1;
 3515:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3516:                                 &add_filetype($allfiles,$1,'src');
 3517:                             }
 3518:                         }
 3519:                     }
 3520:                 }
 3521:             }
 3522:             if ($t->[4] =~ m{/>$}) {
 3523:                 pop(@state);
 3524:             }
 3525: 	} elsif ($t->[0] eq 'E') {
 3526: 	    my ($tagname) = ($t->[1]);
 3527: 	    if ($javafiles{'codebase'} ne '') {
 3528: 		$javafiles{'codebase'} .= '/';
 3529: 	    }  
 3530: 	    if (lc($tagname) eq 'applet' ||
 3531: 		lc($tagname) eq 'object' ||
 3532: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3533: 		) {
 3534: 		foreach my $item (keys(%javafiles)) {
 3535: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3536: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3537: 			&add_filetype($allfiles,$file,$item);
 3538: 		    }
 3539: 		}
 3540: 	    } 
 3541: 	    pop @state;
 3542: 	}
 3543:     }
 3544:     foreach my $id (sort(keys(%flashvars))) {
 3545:         if ($shockwave{$id} ne '') {
 3546:             my @pairs = split(/\&/,$flashvars{$id});
 3547:             foreach my $pair (@pairs) {
 3548:                 my ($key,$value) = split(/\=/,$pair);
 3549:                 if ($key eq 'thumb') {
 3550:                     &add_filetype($allfiles,$value,$key);
 3551:                 } elsif ($key eq 'content') {
 3552:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3553:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3554:                     if ($ext ne '') {
 3555:                         &add_filetype($allfiles,$path.$value,$ext);
 3556:                     }
 3557:                 }
 3558:             }
 3559:         }
 3560:     }
 3561:     return 'ok';
 3562: }
 3563: 
 3564: sub add_filetype {
 3565:     my ($allfiles,$file,$type)=@_;
 3566:     if (exists($allfiles->{$file})) {
 3567: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3568: 	    push(@{$allfiles->{$file}}, &escape($type));
 3569: 	}
 3570:     } else {
 3571: 	@{$allfiles->{$file}} = (&escape($type));
 3572:     }
 3573: }
 3574: 
 3575: sub embedded_dependency {
 3576:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3577:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3578:         if (($identifier ne '') &&
 3579:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3580:             ($pathfrom ne '')) {
 3581:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3582:             foreach my $dep (@{$related->{$identifier}}) {
 3583:                 &add_filetype($allfiles,$path.$dep,'object');
 3584:             }
 3585:         }
 3586:     }
 3587:     return;
 3588: }
 3589: 
 3590: sub removeuploadedurl {
 3591:     my ($url)=@_;	
 3592:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3593:     return &removeuserfile($uname,$udom,$fname);
 3594: }
 3595: 
 3596: sub removeuserfile {
 3597:     my ($docuname,$docudom,$fname)=@_;
 3598:     my $home=&homeserver($docuname,$docudom);    
 3599:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3600:     if ($result eq 'ok') {	
 3601:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3602:             my $metafile = $fname.'.meta';
 3603:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3604: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3605:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3606:             my $sqlresult = 
 3607:                 &update_portfolio_table($docuname,$docudom,$file,
 3608:                                         'portfolio_metadata',$group,
 3609:                                         'delete');
 3610:         }
 3611:     }
 3612:     return $result;
 3613: }
 3614: 
 3615: sub mkdiruserfile {
 3616:     my ($docuname,$docudom,$dir)=@_;
 3617:     my $home=&homeserver($docuname,$docudom);
 3618:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3619: }
 3620: 
 3621: sub renameuserfile {
 3622:     my ($docuname,$docudom,$old,$new)=@_;
 3623:     my $home=&homeserver($docuname,$docudom);
 3624:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3625:                         &escape("$old").':'.&escape("$new"),$home);
 3626:     if ($result eq 'ok') {
 3627:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3628:             my $oldmeta = $old.'.meta';
 3629:             my $newmeta = $new.'.meta';
 3630:             my $metaresult = 
 3631:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3632: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3633:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3634:             my $sqlresult = 
 3635:                 &update_portfolio_table($docuname,$docudom,$file,
 3636:                                         'portfolio_metadata',$group,
 3637:                                         'delete');
 3638:         }
 3639:     }
 3640:     return $result;
 3641: }
 3642: 
 3643: # ------------------------------------------------------------------------- Log
 3644: 
 3645: sub log {
 3646:     my ($dom,$nam,$hom,$what)=@_;
 3647:     return critical("log:$dom:$nam:$what",$hom);
 3648: }
 3649: 
 3650: # ------------------------------------------------------------------ Course Log
 3651: #
 3652: # This routine flushes several buffers of non-mission-critical nature
 3653: #
 3654: 
 3655: sub flushcourselogs {
 3656:     &logthis('Flushing log buffers');
 3657: #
 3658: # course logs
 3659: # This is a log of all transactions in a course, which can be used
 3660: # for data mining purposes
 3661: #
 3662: # It also collects the courseid database, which lists last transaction
 3663: # times and course titles for all courseids
 3664: #
 3665:     my %courseidbuffer=();
 3666:     foreach my $crsid (keys(%courselogs)) {
 3667:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3668: 		          &escape($courselogs{$crsid}),
 3669: 		          $coursehombuf{$crsid}) eq 'ok') {
 3670: 	    delete $courselogs{$crsid};
 3671:         } else {
 3672:             &logthis('Failed to flush log buffer for '.$crsid);
 3673:             if (length($courselogs{$crsid})>40000) {
 3674:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3675:                         " exceeded maximum size, deleting.</font>");
 3676:                delete $courselogs{$crsid};
 3677:             }
 3678:         }
 3679:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3680:             'description' => $coursedescrbuf{$crsid},
 3681:             'inst_code'    => $courseinstcodebuf{$crsid},
 3682:             'type'        => $coursetypebuf{$crsid},
 3683:             'owner'       => $courseownerbuf{$crsid},
 3684:         };
 3685:     }
 3686: #
 3687: # Write course id database (reverse lookup) to homeserver of courses 
 3688: # Is used in pickcourse
 3689: #
 3690:     foreach my $crs_home (keys(%courseidbuffer)) {
 3691:         my $response = &courseidput(&host_domain($crs_home),
 3692:                                     $courseidbuffer{$crs_home},
 3693:                                     $crs_home,'timeonly');
 3694:     }
 3695: #
 3696: # File accesses
 3697: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3698: #
 3699:     foreach my $entry (keys(%accesshash)) {
 3700:         if ($entry =~ /___count$/) {
 3701:             my ($dom,$name);
 3702:             ($dom,$name,undef)=
 3703: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3704:             if (! defined($dom) || $dom eq '' || 
 3705:                 ! defined($name) || $name eq '') {
 3706:                 my $cid = $env{'request.course.id'};
 3707:                 $dom  = $env{'request.'.$cid.'.domain'};
 3708:                 $name = $env{'request.'.$cid.'.num'};
 3709:             }
 3710:             my $value = $accesshash{$entry};
 3711:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3712:             my %temphash=($url => $value);
 3713:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3714:             if ($result eq 'ok') {
 3715:                 delete $accesshash{$entry};
 3716:             }
 3717:         } else {
 3718:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3719:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3720:             my %temphash=($entry => $accesshash{$entry});
 3721:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3722:                 delete $accesshash{$entry};
 3723:             }
 3724:         }
 3725:     }
 3726: #
 3727: # Roles
 3728: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3729: #
 3730:     foreach my $entry (keys(%userrolehash)) {
 3731:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3732: 	    split(/\:/,$entry);
 3733:         if (&Apache::lonnet::put('nohist_userroles',
 3734:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3735:                 $rudom,$runame) eq 'ok') {
 3736: 	    delete $userrolehash{$entry};
 3737:         }
 3738:     }
 3739: #
 3740: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3741: #
 3742:     my %domrolebuffer = ();
 3743:     foreach my $entry (keys(%domainrolehash)) {
 3744:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3745:         if ($domrolebuffer{$rudom}) {
 3746:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3747:                       '='.&escape($domainrolehash{$entry});
 3748:         } else {
 3749:             $domrolebuffer{$rudom}.=&escape($entry).
 3750:                       '='.&escape($domainrolehash{$entry});
 3751:         }
 3752:         delete $domainrolehash{$entry};
 3753:     }
 3754:     foreach my $dom (keys(%domrolebuffer)) {
 3755: 	my %servers = &get_servers($dom,'library');
 3756: 	foreach my $tryserver (keys(%servers)) {
 3757: 	    unless (&reply('domroleput:'.$dom.':'.
 3758: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3759: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3760: 	    }
 3761:         }
 3762:     }
 3763:     $dumpcount++;
 3764: }
 3765: 
 3766: sub courselog {
 3767:     my $what=shift;
 3768:     $what=time.':'.$what;
 3769:     unless ($env{'request.course.id'}) { return ''; }
 3770:     $coursedombuf{$env{'request.course.id'}}=
 3771:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3772:     $coursenumbuf{$env{'request.course.id'}}=
 3773:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3774:     $coursehombuf{$env{'request.course.id'}}=
 3775:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3776:     $coursedescrbuf{$env{'request.course.id'}}=
 3777:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3778:     $courseinstcodebuf{$env{'request.course.id'}}=
 3779:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3780:     $courseownerbuf{$env{'request.course.id'}}=
 3781:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3782:     $coursetypebuf{$env{'request.course.id'}}=
 3783:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3784:     if (defined $courselogs{$env{'request.course.id'}}) {
 3785: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3786:     } else {
 3787: 	$courselogs{$env{'request.course.id'}}.=$what;
 3788:     }
 3789:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3790: 	&flushcourselogs();
 3791:     }
 3792: }
 3793: 
 3794: sub courseacclog {
 3795:     my $fnsymb=shift;
 3796:     unless ($env{'request.course.id'}) { return ''; }
 3797:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3798:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3799:         $what.=':POST';
 3800:         # FIXME: Probably ought to escape things....
 3801: 	foreach my $key (keys(%env)) {
 3802:             if ($key=~/^form\.(.*)/) {
 3803:                 my $formitem = $1;
 3804:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3805:                     $what.=':'.$formitem.'='.$env{$key};
 3806:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3807:                     $what.=':'.$formitem.'='.$env{$key};
 3808:                 }
 3809:             }
 3810:         }
 3811:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3812:         # FIXME: We should not be depending on a form parameter that someone
 3813:         # editing lonsearchcat.pm might change in the future.
 3814:         if ($env{'form.phase'} eq 'course_search') {
 3815:             $what.= ':POST';
 3816:             # FIXME: Probably ought to escape things....
 3817:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3818:                                  'crsdiscuss') {
 3819:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3820:             }
 3821:         }
 3822:     }
 3823:     &courselog($what);
 3824: }
 3825: 
 3826: sub countacc {
 3827:     my $url=&declutter(shift);
 3828:     return if (! defined($url) || $url eq '');
 3829:     unless ($env{'request.course.id'}) { return ''; }
 3830: #
 3831: # Mark that this url was used in this course
 3832: #
 3833:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3834: #
 3835: # Increase the access count for this resource in this child process
 3836: #
 3837:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3838:     $accesshash{$key}++;
 3839: }
 3840: 
 3841: sub linklog {
 3842:     my ($from,$to)=@_;
 3843:     $from=&declutter($from);
 3844:     $to=&declutter($to);
 3845:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3846:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3847: }
 3848: 
 3849: sub statslog {
 3850:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3851:     if ($users<2) { return; }
 3852:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3853:             'course'       => $env{'request.course.id'},
 3854:             'sections'     => '"all"',
 3855:             'num_students' => $users,
 3856:             'part'         => $part,
 3857:             'symb'         => $symb,
 3858:             'mean_tries'   => $av_attempts,
 3859:             'deg_of_diff'  => $degdiff});
 3860:     foreach my $key (keys(%dynstore)) {
 3861:         $accesshash{$key}=$dynstore{$key};
 3862:     }
 3863: }
 3864:   
 3865: sub userrolelog {
 3866:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3867:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3868:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3869:        $userrolehash
 3870:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3871:                     =$tend.':'.$tstart;
 3872:     }
 3873:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3874:        $userrolehash
 3875:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3876:                     =$tend.':'.$tstart;
 3877:     }
 3878:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3879:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3880:        $domainrolehash
 3881:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3882:                     = $tend.':'.$tstart;
 3883:     }
 3884: }
 3885: 
 3886: sub courserolelog {
 3887:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3888:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3889:         my $cdom = $1;
 3890:         my $cnum = $2;
 3891:         my $sec = $3;
 3892:         my $namespace = 'rolelog';
 3893:         my %storehash = (
 3894:                            role    => $trole,
 3895:                            start   => $tstart,
 3896:                            end     => $tend,
 3897:                            selfenroll => $selfenroll,
 3898:                            context    => $context,
 3899:                         );
 3900:         if ($trole eq 'gr') {
 3901:             $namespace = 'groupslog';
 3902:             $storehash{'group'} = $sec;
 3903:         } else {
 3904:             $storehash{'section'} = $sec;
 3905:         }
 3906:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3907:                    $domain,$cnum,$cdom);
 3908:         if (($trole ne 'st') || ($sec ne '')) {
 3909:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3910:         }
 3911:     }
 3912:     return;
 3913: }
 3914: 
 3915: sub domainrolelog {
 3916:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3917:     if ($area =~ m{^/($match_domain)/$}) {
 3918:         my $cdom = $1;
 3919:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3920:         my $namespace = 'rolelog';
 3921:         my %storehash = (
 3922:                            role    => $trole,
 3923:                            start   => $tstart,
 3924:                            end     => $tend,
 3925:                            context => $context,
 3926:                         );
 3927:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3928:                    $domain,$domconfiguser,$cdom);
 3929:     }
 3930:     return;
 3931: 
 3932: }
 3933: 
 3934: sub coauthorrolelog {
 3935:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3936:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3937:         my $audom = $1;
 3938:         my $auname = $2;
 3939:         my $namespace = 'rolelog';
 3940:         my %storehash = (
 3941:                            role    => $trole,
 3942:                            start   => $tstart,
 3943:                            end     => $tend,
 3944:                            context => $context,
 3945:                         );
 3946:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3947:                    $domain,$auname,$audom);
 3948:     }
 3949:     return;
 3950: }
 3951: 
 3952: sub get_course_adv_roles {
 3953:     my ($cid,$codes) = @_;
 3954:     $cid=$env{'request.course.id'} unless (defined($cid));
 3955:     my %coursehash=&coursedescription($cid);
 3956:     my $crstype = &Apache::loncommon::course_type($cid);
 3957:     my %nothide=();
 3958:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3959:         if ($user !~ /:/) {
 3960: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3961:         } else {
 3962:             $nothide{$user}=1;
 3963:         }
 3964:     }
 3965:     my @possdoms = ($coursehash{'domain'});
 3966:     if ($coursehash{'checkforpriv'}) {
 3967:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3968:     }
 3969:     my %returnhash=();
 3970:     my %dumphash=
 3971:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3972:     my $now=time;
 3973:     my %privileged;
 3974:     foreach my $entry (keys(%dumphash)) {
 3975: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3976:         if (($tstart) && ($tstart<0)) { next; }
 3977:         if (($tend) && ($tend<$now)) { next; }
 3978:         if (($tstart) && ($now<$tstart)) { next; }
 3979:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3980: 	if ($username eq '' || $domain eq '') { next; }
 3981:         if ((&privileged($username,$domain,\@possdoms)) &&
 3982:             (!$nothide{$username.':'.$domain})) { next; }
 3983: 	if ($role eq 'cr') { next; }
 3984:         if ($codes) {
 3985:             if ($section) { $role .= ':'.$section; }
 3986:             if ($returnhash{$role}) {
 3987:                 $returnhash{$role}.=','.$username.':'.$domain;
 3988:             } else {
 3989:                 $returnhash{$role}=$username.':'.$domain;
 3990:             }
 3991:         } else {
 3992:             my $key=&plaintext($role,$crstype);
 3993:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3994:             if ($returnhash{$key}) {
 3995: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3996:             } else {
 3997:                 $returnhash{$key}=$username.':'.$domain;
 3998:             }
 3999:         }
 4000:     }
 4001:     return %returnhash;
 4002: }
 4003: 
 4004: sub get_my_roles {
 4005:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4006:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4007:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4008:     my (%dumphash,%nothide);
 4009:     if ($context eq 'userroles') {
 4010:         %dumphash = &dump('roles',$udom,$uname);
 4011:     } else {
 4012:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4013:         if ($hidepriv) {
 4014:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4015:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4016:                 if ($user !~ /:/) {
 4017:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4018:                 } else {
 4019:                     $nothide{$user} = 1;
 4020:                 }
 4021:             }
 4022:         }
 4023:     }
 4024:     my %returnhash=();
 4025:     my $now=time;
 4026:     my %privileged;
 4027:     foreach my $entry (keys(%dumphash)) {
 4028:         my ($role,$tend,$tstart);
 4029:         if ($context eq 'userroles') {
 4030:             next if ($entry =~ /^rolesdef/);
 4031: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4032:         } else {
 4033:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4034:         }
 4035:         if (($tstart) && ($tstart<0)) { next; }
 4036:         my $status = 'active';
 4037:         if (($tend) && ($tend<=$now)) {
 4038:             $status = 'previous';
 4039:         } 
 4040:         if (($tstart) && ($now<$tstart)) {
 4041:             $status = 'future';
 4042:         }
 4043:         if (ref($types) eq 'ARRAY') {
 4044:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4045:                 next;
 4046:             } 
 4047:         } else {
 4048:             if ($status ne 'active') {
 4049:                 next;
 4050:             }
 4051:         }
 4052:         my ($rolecode,$username,$domain,$section,$area);
 4053:         if ($context eq 'userroles') {
 4054:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4055:             (undef,$domain,$username,$section) = split(/\//,$area);
 4056:         } else {
 4057:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4058:         }
 4059:         if (ref($roledoms) eq 'ARRAY') {
 4060:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4061:                 next;
 4062:             }
 4063:         }
 4064:         if (ref($roles) eq 'ARRAY') {
 4065:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4066:                 if ($role =~ /^cr\//) {
 4067:                     if (!grep(/^cr$/,@{$roles})) {
 4068:                         next;
 4069:                     }
 4070:                 } elsif ($role =~ /^gr\//) {
 4071:                     if (!grep(/^gr$/,@{$roles})) {
 4072:                         next;
 4073:                     }
 4074:                 } else {
 4075:                     next;
 4076:                 }
 4077:             }
 4078:         }
 4079:         if ($hidepriv) {
 4080:             my @privroles = ('dc','su');
 4081:             if ($context eq 'userroles') {
 4082:                 next if (grep(/^\Q$role\E$/,@privroles));
 4083:             } else {
 4084:                 my $possdoms = [$domain];
 4085:                 if (ref($roledoms) eq 'ARRAY') {
 4086:                    push(@{$possdoms},@{$roledoms}); 
 4087:                 }
 4088:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4089:                     if (!$nothide{$username.':'.$domain}) {
 4090:                         next;
 4091:                     }
 4092:                 }
 4093:             }
 4094:         }
 4095:         if ($withsec) {
 4096:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4097:                 $tstart.':'.$tend;
 4098:         } else {
 4099:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4100:         }
 4101:     }
 4102:     return %returnhash;
 4103: }
 4104: 
 4105: # ----------------------------------------------------- Frontpage Announcements
 4106: #
 4107: #
 4108: 
 4109: sub postannounce {
 4110:     my ($server,$text)=@_;
 4111:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4112:     unless ($text=~/\w/) { $text=''; }
 4113:     return &reply('setannounce:'.&escape($text),$server);
 4114: }
 4115: 
 4116: sub getannounce {
 4117: 
 4118:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4119: 	my $announcement='';
 4120: 	while (my $line = <$fh>) { $announcement .= $line; }
 4121: 	close($fh);
 4122: 	if ($announcement=~/\w/) { 
 4123: 	    return 
 4124:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4125:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4126: 	} else {
 4127: 	    return '';
 4128: 	}
 4129:     } else {
 4130: 	return '';
 4131:     }
 4132: }
 4133: 
 4134: # ---------------------------------------------------------- Course ID routines
 4135: # Deal with domain's nohist_courseid.db files
 4136: #
 4137: 
 4138: sub courseidput {
 4139:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4140:     return unless (ref($storehash) eq 'HASH');
 4141:     my $outcome;
 4142:     if ($caller eq 'timeonly') {
 4143:         my $cids = '';
 4144:         foreach my $item (keys(%$storehash)) {
 4145:             $cids.=&escape($item).'&';
 4146:         }
 4147:         $cids=~s/\&$//;
 4148:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4149:                           $coursehome);       
 4150:     } else {
 4151:         my $items = '';
 4152:         foreach my $item (keys(%$storehash)) {
 4153:             $items.= &escape($item).'='.
 4154:                      &freeze_escape($$storehash{$item}).'&';
 4155:         }
 4156:         $items=~s/\&$//;
 4157:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4158:                           $coursehome);
 4159:     }
 4160:     if ($outcome eq 'unknown_cmd') {
 4161:         my $what;
 4162:         foreach my $cid (keys(%$storehash)) {
 4163:             $what .= &escape($cid).'=';
 4164:             foreach my $item ('description','inst_code','owner','type') {
 4165:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4166:             }
 4167:             $what =~ s/\:$/&/;
 4168:         }
 4169:         $what =~ s/\&$//;  
 4170:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4171:     } else {
 4172:         return $outcome;
 4173:     }
 4174: }
 4175: 
 4176: sub courseiddump {
 4177:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4178:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4179:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4180:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4181:     my $as_hash = 1;
 4182:     my %returnhash;
 4183:     if (!$domfilter) { $domfilter=''; }
 4184:     my %libserv = &all_library();
 4185:     foreach my $tryserver (keys(%libserv)) {
 4186:         if ( (  $hostidflag == 1 
 4187: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4188: 	     || (!defined($hostidflag)) ) {
 4189: 
 4190: 	    if (($domfilter eq '') ||
 4191: 		(&host_domain($tryserver) eq $domfilter)) {
 4192:                 my $rep;
 4193:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4194:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4195:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4196:                                 &escape($descfilter), &escape($instcodefilter), 
 4197:                                 &escape($ownerfilter), &escape($coursefilter),
 4198:                                 &escape($typefilter), &escape($regexp_ok), 
 4199:                                 $as_hash, &escape($selfenrollonly), 
 4200:                                 &escape($catfilter), $showhidden, $caller, 
 4201:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4202:                                 &escape($createdbefore), &escape($createdafter), 
 4203:                                 &escape($creationcontext), $domcloner)));
 4204:                 } else {
 4205:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4206:                              $sincefilter.':'.&escape($descfilter).':'.
 4207:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4208:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4209:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4210:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4211:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4212:                              &escape($cc_clone).':'.$cloneonly.':'.
 4213:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4214:                              &escape($creationcontext).':'.$domcloner,
 4215:                              $tryserver);
 4216:                 }
 4217:                      
 4218:                 my @pairs=split(/\&/,$rep);
 4219:                 foreach my $item (@pairs) {
 4220:                     my ($key,$value)=split(/\=/,$item,2);
 4221:                     $key = &unescape($key);
 4222:                     next if ($key =~ /^error: 2 /);
 4223:                     my $result = &thaw_unescape($value);
 4224:                     if (ref($result) eq 'HASH') {
 4225:                         $returnhash{$key}=$result;
 4226:                     } else {
 4227:                         my @responses = split(/:/,$value);
 4228:                         my @items = ('description','inst_code','owner','type');
 4229:                         for (my $i=0; $i<@responses; $i++) {
 4230:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4231:                         }
 4232:                     }
 4233:                 }
 4234:             }
 4235:         }
 4236:     }
 4237:     return %returnhash;
 4238: }
 4239: 
 4240: sub courselastaccess {
 4241:     my ($cdom,$cnum,$hostidref) = @_;
 4242:     my %returnhash;
 4243:     if ($cdom && $cnum) {
 4244:         my $chome = &homeserver($cnum,$cdom);
 4245:         if ($chome ne 'no_host') {
 4246:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4247:             &extract_lastaccess(\%returnhash,$rep);
 4248:         }
 4249:     } else {
 4250:         if (!$cdom) { $cdom=''; }
 4251:         my %libserv = &all_library();
 4252:         foreach my $tryserver (keys(%libserv)) {
 4253:             if (ref($hostidref) eq 'ARRAY') {
 4254:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4255:             } 
 4256:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4257:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4258:                 &extract_lastaccess(\%returnhash,$rep);
 4259:             }
 4260:         }
 4261:     }
 4262:     return %returnhash;
 4263: }
 4264: 
 4265: sub extract_lastaccess {
 4266:     my ($returnhash,$rep) = @_;
 4267:     if (ref($returnhash) eq 'HASH') {
 4268:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4269:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4270:                  $rep eq '') {
 4271:             my @pairs=split(/\&/,$rep);
 4272:             foreach my $item (@pairs) {
 4273:                 my ($key,$value)=split(/\=/,$item,2);
 4274:                 $key = &unescape($key);
 4275:                 next if ($key =~ /^error: 2 /);
 4276:                 $returnhash->{$key} = &thaw_unescape($value);
 4277:             }
 4278:         }
 4279:     }
 4280:     return;
 4281: }
 4282: 
 4283: # ---------------------------------------------------------- DC e-mail
 4284: 
 4285: sub dcmailput {
 4286:     my ($domain,$msgid,$message,$server)=@_;
 4287:     my $status = &Apache::lonnet::critical(
 4288:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4289:        &escape($message),$server);
 4290:     return $status;
 4291: }
 4292: 
 4293: sub dcmaildump {
 4294:     my ($dom,$startdate,$enddate,$senders) = @_;
 4295:     my %returnhash=();
 4296: 
 4297:     if (defined(&domain($dom,'primary'))) {
 4298:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4299:                                                          &escape($enddate).':';
 4300: 	my @esc_senders=map { &escape($_)} @$senders;
 4301: 	$cmd.=&escape(join('&',@esc_senders));
 4302: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4303:             my ($key,$value) = split(/\=/,$line,2);
 4304:             if (($key) && ($value)) {
 4305:                 $returnhash{&unescape($key)} = &unescape($value);
 4306:             }
 4307:         }
 4308:     }
 4309:     return %returnhash;
 4310: }
 4311: # ---------------------------------------------------------- Domain roles
 4312: 
 4313: sub get_domain_roles {
 4314:     my ($dom,$roles,$startdate,$enddate)=@_;
 4315:     if ((!defined($startdate)) || ($startdate eq '')) {
 4316:         $startdate = '.';
 4317:     }
 4318:     if ((!defined($enddate)) || ($enddate eq '')) {
 4319:         $enddate = '.';
 4320:     }
 4321:     my $rolelist;
 4322:     if (ref($roles) eq 'ARRAY') {
 4323:         $rolelist = join('&',@{$roles});
 4324:     }
 4325:     my %personnel = ();
 4326: 
 4327:     my %servers = &get_servers($dom,'library');
 4328:     foreach my $tryserver (keys(%servers)) {
 4329: 	%{$personnel{$tryserver}}=();
 4330: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4331: 					    &escape($startdate).':'.
 4332: 					    &escape($enddate).':'.
 4333: 					    &escape($rolelist), $tryserver))) {
 4334: 	    my ($key,$value) = split(/\=/,$line,2);
 4335: 	    if (($key) && ($value)) {
 4336: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4337: 	    }
 4338: 	}
 4339:     }
 4340:     return %personnel;
 4341: }
 4342: 
 4343: # ----------------------------------------------------------- Interval timing 
 4344: 
 4345: {
 4346: # Caches needed for speedup of navmaps
 4347: # We don't want to cache this for very long at all (5 seconds at most)
 4348: # 
 4349: # The user for whom we cache
 4350: my $cachedkey='';
 4351: # The cached times for this user
 4352: my %cachedtimes=();
 4353: # When this was last done
 4354: my $cachedtime=();
 4355: 
 4356: sub load_all_first_access {
 4357:     my ($uname,$udom)=@_;
 4358:     if (($cachedkey eq $uname.':'.$udom) &&
 4359:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4360:         return;
 4361:     }
 4362:     $cachedtime=time;
 4363:     $cachedkey=$uname.':'.$udom;
 4364:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4365: }
 4366: 
 4367: sub get_first_access {
 4368:     my ($type,$argsymb,$argmap)=@_;
 4369:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4370:     if ($argsymb) { $symb=$argsymb; }
 4371:     my ($map,$id,$res)=&decode_symb($symb);
 4372:     if ($argmap) { $map = $argmap; }
 4373:     if ($type eq 'course') {
 4374: 	$res='course';
 4375:     } elsif ($type eq 'map') {
 4376: 	$res=&symbread($map);
 4377:     } else {
 4378: 	$res=$symb;
 4379:     }
 4380:     &load_all_first_access($uname,$udom);
 4381:     return $cachedtimes{"$courseid\0$res"};
 4382: }
 4383: 
 4384: sub set_first_access {
 4385:     my ($type,$interval)=@_;
 4386:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4387:     my ($map,$id,$res)=&decode_symb($symb);
 4388:     if ($type eq 'course') {
 4389: 	$res='course';
 4390:     } elsif ($type eq 'map') {
 4391: 	$res=&symbread($map);
 4392:     } else {
 4393: 	$res=$symb;
 4394:     }
 4395:     $cachedkey='';
 4396:     my $firstaccess=&get_first_access($type,$symb,$map);
 4397:     if (!$firstaccess) {
 4398:         my $start = time;
 4399: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4400:                           $udom,$uname);
 4401:         if ($putres eq 'ok') {
 4402:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4403:                  $udom,$uname); 
 4404:             &appenv(
 4405:                      {
 4406:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4407:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4408:                      }
 4409:                   );
 4410:         }
 4411:         return $putres;
 4412:     }
 4413:     return 'already_set';
 4414: }
 4415: }
 4416: # --------------------------------------------- Set Expire Date for Spreadsheet
 4417: 
 4418: sub expirespread {
 4419:     my ($uname,$udom,$stype,$usymb)=@_;
 4420:     my $cid=$env{'request.course.id'}; 
 4421:     if ($cid) {
 4422:        my $now=time;
 4423:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4424:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4425:                             $env{'course.'.$cid.'.num'}.
 4426: 	        	    ':nohist_expirationdates:'.
 4427:                             &escape($key).'='.$now,
 4428:                             $env{'course.'.$cid.'.home'})
 4429:     }
 4430:     return 'ok';
 4431: }
 4432: 
 4433: # ----------------------------------------------------- Devalidate Spreadsheets
 4434: 
 4435: sub devalidate {
 4436:     my ($symb,$uname,$udom)=@_;
 4437:     my $cid=$env{'request.course.id'}; 
 4438:     if ($cid) {
 4439:         # delete the stored spreadsheets for
 4440:         # - the student level sheet of this user in course's homespace
 4441:         # - the assessment level sheet for this resource 
 4442:         #   for this user in user's homespace
 4443: 	# - current conditional state info
 4444: 	my $key=$uname.':'.$udom.':';
 4445:         my $status=
 4446: 	    &del('nohist_calculatedsheets',
 4447: 		 [$key.'studentcalc:'],
 4448: 		 $env{'course.'.$cid.'.domain'},
 4449: 		 $env{'course.'.$cid.'.num'})
 4450: 		.' '.
 4451: 	    &del('nohist_calculatedsheets_'.$cid,
 4452: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4453:         unless ($status eq 'ok ok') {
 4454:            &logthis('Could not devalidate spreadsheet '.
 4455:                     $uname.' at '.$udom.' for '.
 4456: 		    $symb.': '.$status);
 4457:         }
 4458: 	&delenv('user.state.'.$cid);
 4459:     }
 4460: }
 4461: 
 4462: sub get_scalar {
 4463:     my ($string,$end) = @_;
 4464:     my $value;
 4465:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4466: 	$value = $1;
 4467:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4468: 	$value = $1;
 4469:     }
 4470:     return &unescape($value);
 4471: }
 4472: 
 4473: sub array2str {
 4474:   my (@array) = @_;
 4475:   my $result=&arrayref2str(\@array);
 4476:   $result=~s/^__ARRAY_REF__//;
 4477:   $result=~s/__END_ARRAY_REF__$//;
 4478:   return $result;
 4479: }
 4480: 
 4481: sub arrayref2str {
 4482:   my ($arrayref) = @_;
 4483:   my $result='__ARRAY_REF__';
 4484:   foreach my $elem (@$arrayref) {
 4485:     if(ref($elem) eq 'ARRAY') {
 4486:       $result.=&arrayref2str($elem).'&';
 4487:     } elsif(ref($elem) eq 'HASH') {
 4488:       $result.=&hashref2str($elem).'&';
 4489:     } elsif(ref($elem)) {
 4490:       #print("Got a ref of ".(ref($elem))." skipping.");
 4491:     } else {
 4492:       $result.=&escape($elem).'&';
 4493:     }
 4494:   }
 4495:   $result=~s/\&$//;
 4496:   $result .= '__END_ARRAY_REF__';
 4497:   return $result;
 4498: }
 4499: 
 4500: sub hash2str {
 4501:   my (%hash) = @_;
 4502:   my $result=&hashref2str(\%hash);
 4503:   $result=~s/^__HASH_REF__//;
 4504:   $result=~s/__END_HASH_REF__$//;
 4505:   return $result;
 4506: }
 4507: 
 4508: sub hashref2str {
 4509:   my ($hashref)=@_;
 4510:   my $result='__HASH_REF__';
 4511:   foreach my $key (sort(keys(%$hashref))) {
 4512:     if (ref($key) eq 'ARRAY') {
 4513:       $result.=&arrayref2str($key).'=';
 4514:     } elsif (ref($key) eq 'HASH') {
 4515:       $result.=&hashref2str($key).'=';
 4516:     } elsif (ref($key)) {
 4517:       $result.='=';
 4518:       #print("Got a ref of ".(ref($key))." skipping.");
 4519:     } else {
 4520: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4521:     }
 4522: 
 4523:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4524:       $result.=&arrayref2str($hashref->{$key}).'&';
 4525:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4526:       $result.=&hashref2str($hashref->{$key}).'&';
 4527:     } elsif(ref($hashref->{$key})) {
 4528:        $result.='&';
 4529:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4530:     } else {
 4531:       $result.=&escape($hashref->{$key}).'&';
 4532:     }
 4533:   }
 4534:   $result=~s/\&$//;
 4535:   $result .= '__END_HASH_REF__';
 4536:   return $result;
 4537: }
 4538: 
 4539: sub str2hash {
 4540:     my ($string)=@_;
 4541:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4542:     return %$hash;
 4543: }
 4544: 
 4545: sub str2hashref {
 4546:   my ($string) = @_;
 4547: 
 4548:   my %hash;
 4549: 
 4550:   if($string !~ /^__HASH_REF__/) {
 4551:       if (! ($string eq '' || !defined($string))) {
 4552: 	  $hash{'error'}='Not hash reference';
 4553:       }
 4554:       return (\%hash, $string);
 4555:   }
 4556: 
 4557:   $string =~ s/^__HASH_REF__//;
 4558: 
 4559:   while($string !~ /^__END_HASH_REF__/) {
 4560:       #key
 4561:       my $key='';
 4562:       if($string =~ /^__HASH_REF__/) {
 4563:           ($key, $string)=&str2hashref($string);
 4564:           if(defined($key->{'error'})) {
 4565:               $hash{'error'}='Bad data';
 4566:               return (\%hash, $string);
 4567:           }
 4568:       } elsif($string =~ /^__ARRAY_REF__/) {
 4569:           ($key, $string)=&str2arrayref($string);
 4570:           if($key->[0] eq 'Array reference error') {
 4571:               $hash{'error'}='Bad data';
 4572:               return (\%hash, $string);
 4573:           }
 4574:       } else {
 4575:           $string =~ s/^(.*?)=//;
 4576: 	  $key=&unescape($1);
 4577:       }
 4578:       $string =~ s/^=//;
 4579: 
 4580:       #value
 4581:       my $value='';
 4582:       if($string =~ /^__HASH_REF__/) {
 4583:           ($value, $string)=&str2hashref($string);
 4584:           if(defined($value->{'error'})) {
 4585:               $hash{'error'}='Bad data';
 4586:               return (\%hash, $string);
 4587:           }
 4588:       } elsif($string =~ /^__ARRAY_REF__/) {
 4589:           ($value, $string)=&str2arrayref($string);
 4590:           if($value->[0] eq 'Array reference error') {
 4591:               $hash{'error'}='Bad data';
 4592:               return (\%hash, $string);
 4593:           }
 4594:       } else {
 4595: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4596:       }
 4597:       $string =~ s/^&//;
 4598: 
 4599:       $hash{$key}=$value;
 4600:   }
 4601: 
 4602:   $string =~ s/^__END_HASH_REF__//;
 4603: 
 4604:   return (\%hash, $string);
 4605: }
 4606: 
 4607: sub str2array {
 4608:     my ($string)=@_;
 4609:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4610:     return @$array;
 4611: }
 4612: 
 4613: sub str2arrayref {
 4614:   my ($string) = @_;
 4615:   my @array;
 4616: 
 4617:   if($string !~ /^__ARRAY_REF__/) {
 4618:       if (! ($string eq '' || !defined($string))) {
 4619: 	  $array[0]='Array reference error';
 4620:       }
 4621:       return (\@array, $string);
 4622:   }
 4623: 
 4624:   $string =~ s/^__ARRAY_REF__//;
 4625: 
 4626:   while($string !~ /^__END_ARRAY_REF__/) {
 4627:       my $value='';
 4628:       if($string =~ /^__HASH_REF__/) {
 4629:           ($value, $string)=&str2hashref($string);
 4630:           if(defined($value->{'error'})) {
 4631:               $array[0] ='Array reference error';
 4632:               return (\@array, $string);
 4633:           }
 4634:       } elsif($string =~ /^__ARRAY_REF__/) {
 4635:           ($value, $string)=&str2arrayref($string);
 4636:           if($value->[0] eq 'Array reference error') {
 4637:               $array[0] ='Array reference error';
 4638:               return (\@array, $string);
 4639:           }
 4640:       } else {
 4641: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4642:       }
 4643:       $string =~ s/^&//;
 4644: 
 4645:       push(@array, $value);
 4646:   }
 4647: 
 4648:   $string =~ s/^__END_ARRAY_REF__//;
 4649: 
 4650:   return (\@array, $string);
 4651: }
 4652: 
 4653: # -------------------------------------------------------------------Temp Store
 4654: 
 4655: sub tmpreset {
 4656:   my ($symb,$namespace,$domain,$stuname) = @_;
 4657:   if (!$symb) {
 4658:     $symb=&symbread();
 4659:     if (!$symb) { $symb= $env{'request.url'}; }
 4660:   }
 4661:   $symb=escape($symb);
 4662: 
 4663:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4664:   $namespace=~s/\//\_/g;
 4665:   $namespace=~s/\W//g;
 4666: 
 4667:   if (!$domain) { $domain=$env{'user.domain'}; }
 4668:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4669:   if ($domain eq 'public' && $stuname eq 'public') {
 4670:       $stuname=$ENV{'REMOTE_ADDR'};
 4671:   }
 4672:   my $path=LONCAPA::tempdir();
 4673:   my %hash;
 4674:   if (tie(%hash,'GDBM_File',
 4675: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4676: 	  &GDBM_WRCREAT(),0640)) {
 4677:     foreach my $key (keys(%hash)) {
 4678:       if ($key=~ /:$symb/) {
 4679: 	delete($hash{$key});
 4680:       }
 4681:     }
 4682:   }
 4683: }
 4684: 
 4685: sub tmpstore {
 4686:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4687: 
 4688:   if (!$symb) {
 4689:     $symb=&symbread();
 4690:     if (!$symb) { $symb= $env{'request.url'}; }
 4691:   }
 4692:   $symb=escape($symb);
 4693: 
 4694:   if (!$namespace) {
 4695:     # I don't think we would ever want to store this for a course.
 4696:     # it seems this will only be used if we don't have a course.
 4697:     #$namespace=$env{'request.course.id'};
 4698:     #if (!$namespace) {
 4699:       $namespace=$env{'request.state'};
 4700:     #}
 4701:   }
 4702:   $namespace=~s/\//\_/g;
 4703:   $namespace=~s/\W//g;
 4704:   if (!$domain) { $domain=$env{'user.domain'}; }
 4705:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4706:   if ($domain eq 'public' && $stuname eq 'public') {
 4707:       $stuname=$ENV{'REMOTE_ADDR'};
 4708:   }
 4709:   my $now=time;
 4710:   my %hash;
 4711:   my $path=LONCAPA::tempdir();
 4712:   if (tie(%hash,'GDBM_File',
 4713: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4714: 	  &GDBM_WRCREAT(),0640)) {
 4715:     $hash{"version:$symb"}++;
 4716:     my $version=$hash{"version:$symb"};
 4717:     my $allkeys=''; 
 4718:     foreach my $key (keys(%$storehash)) {
 4719:       $allkeys.=$key.':';
 4720:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4721:     }
 4722:     $hash{"$version:$symb:timestamp"}=$now;
 4723:     $allkeys.='timestamp';
 4724:     $hash{"$version:keys:$symb"}=$allkeys;
 4725:     if (untie(%hash)) {
 4726:       return 'ok';
 4727:     } else {
 4728:       return "error:$!";
 4729:     }
 4730:   } else {
 4731:     return "error:$!";
 4732:   }
 4733: }
 4734: 
 4735: # -----------------------------------------------------------------Temp Restore
 4736: 
 4737: sub tmprestore {
 4738:   my ($symb,$namespace,$domain,$stuname) = @_;
 4739: 
 4740:   if (!$symb) {
 4741:     $symb=&symbread();
 4742:     if (!$symb) { $symb= $env{'request.url'}; }
 4743:   }
 4744:   $symb=escape($symb);
 4745: 
 4746:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4747: 
 4748:   if (!$domain) { $domain=$env{'user.domain'}; }
 4749:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4750:   if ($domain eq 'public' && $stuname eq 'public') {
 4751:       $stuname=$ENV{'REMOTE_ADDR'};
 4752:   }
 4753:   my %returnhash;
 4754:   $namespace=~s/\//\_/g;
 4755:   $namespace=~s/\W//g;
 4756:   my %hash;
 4757:   my $path=LONCAPA::tempdir();
 4758:   if (tie(%hash,'GDBM_File',
 4759: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4760: 	  &GDBM_READER(),0640)) {
 4761:     my $version=$hash{"version:$symb"};
 4762:     $returnhash{'version'}=$version;
 4763:     my $scope;
 4764:     for ($scope=1;$scope<=$version;$scope++) {
 4765:       my $vkeys=$hash{"$scope:keys:$symb"};
 4766:       my @keys=split(/:/,$vkeys);
 4767:       my $key;
 4768:       $returnhash{"$scope:keys"}=$vkeys;
 4769:       foreach $key (@keys) {
 4770: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4771: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4772:       }
 4773:     }
 4774:     if (!(untie(%hash))) {
 4775:       return "error:$!";
 4776:     }
 4777:   } else {
 4778:     return "error:$!";
 4779:   }
 4780:   return %returnhash;
 4781: }
 4782: 
 4783: # ----------------------------------------------------------------------- Store
 4784: 
 4785: sub store {
 4786:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4787:     my $home='';
 4788: 
 4789:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4790: 
 4791:     $symb=&symbclean($symb);
 4792:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4793: 
 4794:     if (!$domain) { $domain=$env{'user.domain'}; }
 4795:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4796: 
 4797:     &devalidate($symb,$stuname,$domain);
 4798: 
 4799:     $symb=escape($symb);
 4800:     if (!$namespace) { 
 4801:        unless ($namespace=$env{'request.course.id'}) { 
 4802:           return ''; 
 4803:        } 
 4804:     }
 4805:     if (!$home) { $home=$env{'user.home'}; }
 4806: 
 4807:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4808:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4809: 
 4810:     my $namevalue='';
 4811:     foreach my $key (keys(%$storehash)) {
 4812:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4813:     }
 4814:     $namevalue=~s/\&$//;
 4815:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4816:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4817: }
 4818: 
 4819: # -------------------------------------------------------------- Critical Store
 4820: 
 4821: sub cstore {
 4822:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4823:     my $home='';
 4824: 
 4825:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4826: 
 4827:     $symb=&symbclean($symb);
 4828:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4829: 
 4830:     if (!$domain) { $domain=$env{'user.domain'}; }
 4831:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4832: 
 4833:     &devalidate($symb,$stuname,$domain);
 4834: 
 4835:     $symb=escape($symb);
 4836:     if (!$namespace) { 
 4837:        unless ($namespace=$env{'request.course.id'}) { 
 4838:           return ''; 
 4839:        } 
 4840:     }
 4841:     if (!$home) { $home=$env{'user.home'}; }
 4842: 
 4843:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4844:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4845: 
 4846:     my $namevalue='';
 4847:     foreach my $key (keys(%$storehash)) {
 4848:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4849:     }
 4850:     $namevalue=~s/\&$//;
 4851:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4852:     return critical
 4853:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4854: }
 4855: 
 4856: # --------------------------------------------------------------------- Restore
 4857: 
 4858: sub restore {
 4859:     my ($symb,$namespace,$domain,$stuname) = @_;
 4860:     my $home='';
 4861: 
 4862:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4863: 
 4864:     if (!$symb) {
 4865:         return if ($namespace eq 'courserequests');
 4866:         unless ($symb=escape(&symbread())) { return ''; }
 4867:     } else {
 4868:         unless ($namespace eq 'courserequests') {
 4869:             $symb=&escape(&symbclean($symb));
 4870:         }
 4871:     }
 4872:     if (!$namespace) { 
 4873:        unless ($namespace=$env{'request.course.id'}) { 
 4874:           return ''; 
 4875:        } 
 4876:     }
 4877:     if (!$domain) { $domain=$env{'user.domain'}; }
 4878:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4879:     if (!$home) { $home=$env{'user.home'}; }
 4880:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4881: 
 4882:     my %returnhash=();
 4883:     foreach my $line (split(/\&/,$answer)) {
 4884: 	my ($name,$value)=split(/\=/,$line);
 4885:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4886:     }
 4887:     my $version;
 4888:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4889:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4890:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4891:        }
 4892:     }
 4893:     return %returnhash;
 4894: }
 4895: 
 4896: # ---------------------------------------------------------- Course Description
 4897: #
 4898: #  
 4899: 
 4900: sub coursedescription {
 4901:     my ($courseid,$args)=@_;
 4902:     $courseid=~s/^\///;
 4903:     $courseid=~s/\_/\//g;
 4904:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4905:     my $chome=&homeserver($cnum,$cdomain);
 4906:     my $normalid=$cdomain.'_'.$cnum;
 4907:     # need to always cache even if we get errors otherwise we keep 
 4908:     # trying and trying and trying to get the course description.
 4909:     my %envhash=();
 4910:     my %returnhash=();
 4911:     
 4912:     my $expiretime=600;
 4913:     if ($env{'request.course.id'} eq $normalid) {
 4914: 	$expiretime=120;
 4915:     }
 4916: 
 4917:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4918:     if (!$args->{'freshen_cache'}
 4919: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4920: 	foreach my $key (keys(%env)) {
 4921: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4922: 	    my ($setting) = $1;
 4923: 	    $returnhash{$setting} = $env{$key};
 4924: 	}
 4925: 	return %returnhash;
 4926:     }
 4927: 
 4928:     # get the data again
 4929: 
 4930:     if (!$args->{'one_time'}) {
 4931: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4932:     }
 4933: 
 4934:     if ($chome ne 'no_host') {
 4935:        %returnhash=&dump('environment',$cdomain,$cnum);
 4936:        if (!exists($returnhash{'con_lost'})) {
 4937: 	   my $username = $env{'user.name'}; # Defult username
 4938: 	   if(defined $args->{'user'}) {
 4939: 	       $username = $args->{'user'};
 4940: 	   }
 4941:            $returnhash{'home'}= $chome;
 4942: 	   $returnhash{'domain'} = $cdomain;
 4943: 	   $returnhash{'num'} = $cnum;
 4944:            if (!defined($returnhash{'type'})) {
 4945:                $returnhash{'type'} = 'Course';
 4946:            }
 4947:            while (my ($name,$value) = each %returnhash) {
 4948:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4949:            }
 4950:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4951:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4952: 	       $username.'_'.$cdomain.'_'.$cnum;
 4953:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4954:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4955:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4956:        }
 4957:     }
 4958:     if (!$args->{'one_time'}) {
 4959: 	&appenv(\%envhash);
 4960:     }
 4961:     return %returnhash;
 4962: }
 4963: 
 4964: sub update_released_required {
 4965:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4966:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4967:         $cid = $env{'request.course.id'};
 4968:         $cdom = $env{'course.'.$cid.'.domain'};
 4969:         $cnum = $env{'course.'.$cid.'.num'};
 4970:         $chome = $env{'course.'.$cid.'.home'};
 4971:     }
 4972:     if ($needsrelease) {
 4973:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4974:         my $needsupdate;
 4975:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4976:             $needsupdate = 1;
 4977:         } else {
 4978:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4979:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4980:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4981:                 $needsupdate = 1;
 4982:             }
 4983:         }
 4984:         if ($needsupdate) {
 4985:             my %needshash = (
 4986:                              'internal.releaserequired' => $needsrelease,
 4987:                             );
 4988:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4989:             if ($putresult eq 'ok') {
 4990:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4991:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4992:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4993:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4994:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4995:                 }
 4996:             }
 4997:         }
 4998:     }
 4999:     return;
 5000: }
 5001: 
 5002: # -------------------------------------------------See if a user is privileged
 5003: 
 5004: sub privileged {
 5005:     my ($username,$domain,$possdomains,$possroles)=@_;
 5006:     my $now = time;
 5007:     my $roles;
 5008:     if (ref($possroles) eq 'ARRAY') {
 5009:         $roles = $possroles; 
 5010:     } else {
 5011:         $roles = ['dc','su'];
 5012:     }
 5013:     if (ref($possdomains) eq 'ARRAY') {
 5014:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5015:         foreach my $dom (@{$possdomains}) {
 5016:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5017:                 (ref($privileged{$dom}) eq 'HASH')) {
 5018:                 foreach my $role (@{$roles}) {
 5019:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5020:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5021:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5022:                             return 1 unless (($end && $end < $now) ||
 5023:                                              ($start && $start > $now));
 5024:                         }
 5025:                     }
 5026:                 }
 5027:             }
 5028:         }
 5029:     } else {
 5030:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5031:         my $now = time;
 5032: 
 5033:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5034:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5035:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5036:                 return 1 unless ($tend && $tend < $now) 
 5037:                         or ($tstart && $tstart > $now);
 5038:             }
 5039:         }
 5040:     }
 5041:     return 0;
 5042: }
 5043: 
 5044: sub privileged_by_domain {
 5045:     my ($domains,$roles) = @_;
 5046:     my %privileged = ();
 5047:     my $cachetime = 60*60*24;
 5048:     my $now = time;
 5049:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5050:         return %privileged;
 5051:     }
 5052:     foreach my $dom (@{$domains}) {
 5053:         next if (ref($privileged{$dom}) eq 'HASH');
 5054:         my $needroles;
 5055:         foreach my $role (@{$roles}) {
 5056:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5057:             if (defined($cached)) {
 5058:                 if (ref($result) eq 'HASH') {
 5059:                     $privileged{$dom}{$role} = $result;
 5060:                 }
 5061:             } else {
 5062:                 $needroles = 1;
 5063:             }
 5064:         }
 5065:         if ($needroles) {
 5066:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5067:             $privileged{$dom} = {};
 5068:             foreach my $server (keys(%dompersonnel)) {
 5069:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5070:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5071:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5072:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5073:                         next if ($end && $end < $now);
 5074:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5075:                             $dompersonnel{$server}{$item};
 5076:                     }
 5077:                 }
 5078:             }
 5079:             if (ref($privileged{$dom}) eq 'HASH') {
 5080:                 foreach my $role (@{$roles}) {
 5081:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5082:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5083:                     } else {
 5084:                         my %hash = ();
 5085:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5086:                     }
 5087:                 }
 5088:             }
 5089:         }
 5090:     }
 5091:     return %privileged;
 5092: }
 5093: 
 5094: # -------------------------------------------------------- Get user privileges
 5095: 
 5096: sub rolesinit {
 5097:     my ($domain, $username) = @_;
 5098:     my %userroles = ('user.login.time' => time);
 5099:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5100: 
 5101:     # firstaccess and timerinterval are related to timed maps/resources. 
 5102:     # also, blocking can be triggered by an activating timer
 5103:     # it's saved in the user's %env.
 5104:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5105:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5106:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5107:         %timerintchk, %timerintenv);
 5108: 
 5109:     foreach my $key (keys(%firstaccess)) {
 5110:         my ($cid, $rest) = split(/\0/, $key);
 5111:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5112:     }
 5113: 
 5114:     foreach my $key (keys(%timerinterval)) {
 5115:         my ($cid,$rest) = split(/\0/,$key);
 5116:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5117:     }
 5118: 
 5119:     my %allroles=();
 5120:     my %allgroups=();
 5121: 
 5122:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5123:         my $role = $rolesdump{$area};
 5124:         $area =~ s/\_\w\w$//;
 5125: 
 5126:         my ($trole, $tend, $tstart, $group_privs);
 5127: 
 5128:         if ($role =~ /^cr/) {
 5129:         # Custom role, defined by a user 
 5130:         # e.g., user.role.cr/msu/smith/mynewrole
 5131:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5132:                 $trole = $1;
 5133:                 ($tend, $tstart) = split('_', $2);
 5134:             } else {
 5135:                 $trole = $role;
 5136:             }
 5137:         } elsif ($role =~ m|^gr/|) {
 5138:         # Role of member in a group, defined within a course/community
 5139:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5140:             ($trole, $tend, $tstart) = split(/_/, $role);
 5141:             next if $tstart eq '-1';
 5142:             ($trole, $group_privs) = split(/\//, $trole);
 5143:             $group_privs = &unescape($group_privs);
 5144:         } else {
 5145:         # Just a normal role, defined in roles.tab
 5146:             ($trole, $tend, $tstart) = split(/_/,$role);
 5147:         }
 5148: 
 5149:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5150:                  $username);
 5151:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5152: 
 5153:         # role expired or not available yet?
 5154:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5155:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5156: 
 5157:         next if $area eq '' or $trole eq '';
 5158: 
 5159:         my $spec = "$trole.$area";
 5160:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5161: 
 5162:         if ($trole =~ /^cr\//) {
 5163:         # Custom role, defined by a user
 5164:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5165:         } elsif ($trole eq 'gr') {
 5166:         # Role of a member in a group, defined within a course/community
 5167:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5168:             next;
 5169:         } else {
 5170:         # Normal role, defined in roles.tab
 5171:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5172:         }
 5173: 
 5174:         my $cid = $tdomain.'_'.$trest;
 5175:         unless ($firstaccchk{$cid}) {
 5176:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5177:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5178:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5179:                         $coursetimerstarts{$cid}{$item}; 
 5180:                 }
 5181:             }
 5182:             $firstaccchk{$cid} = 1;
 5183:         }
 5184:         unless ($timerintchk{$cid}) {
 5185:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5186:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5187:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5188:                        $coursetimerintervals{$cid}{$item};
 5189:                 }
 5190:             }
 5191:             $timerintchk{$cid} = 1;
 5192:         }
 5193:     }
 5194: 
 5195:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5196:         \%allroles, \%allgroups);
 5197:     $env{'user.adv'} = $userroles{'user.adv'};
 5198: 
 5199:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5200: }
 5201: 
 5202: sub set_arearole {
 5203:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5204:     unless ($nolog) {
 5205: # log the associated role with the area
 5206:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5207:     }
 5208:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5209: }
 5210: 
 5211: sub custom_roleprivs {
 5212:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5213:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5214:     my $homsvr=homeserver($rauthor,$rdomain);
 5215:     if (&hostname($homsvr) ne '') {
 5216:         my ($rdummy,$roledef)=
 5217:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5218:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5219:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5220:             if (defined($syspriv)) {
 5221:                 if ($trest =~ /^$match_community$/) {
 5222:                     $syspriv =~ s/bre\&S//; 
 5223:                 }
 5224:                 $$allroles{'cm./'}.=':'.$syspriv;
 5225:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5226:             }
 5227:             if ($tdomain ne '') {
 5228:                 if (defined($dompriv)) {
 5229:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5230:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5231:                 }
 5232:                 if (($trest ne '') && (defined($coursepriv))) {
 5233:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5234:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5235:                 }
 5236:             }
 5237:         }
 5238:     }
 5239: }
 5240: 
 5241: sub group_roleprivs {
 5242:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5243:     my $access = 1;
 5244:     my $now = time;
 5245:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5246:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5247:     if ($access) {
 5248:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5249:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5250:     }
 5251: }
 5252: 
 5253: sub standard_roleprivs {
 5254:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5255:     if (defined($pr{$trole.':s'})) {
 5256:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5257:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5258:     }
 5259:     if ($tdomain ne '') {
 5260:         if (defined($pr{$trole.':d'})) {
 5261:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5262:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5263:         }
 5264:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5265:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5266:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5267:         }
 5268:     }
 5269: }
 5270: 
 5271: sub set_userprivs {
 5272:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5273:     my $author=0;
 5274:     my $adv=0;
 5275:     my %grouproles = ();
 5276:     if (keys(%{$allgroups}) > 0) {
 5277:         my @groupkeys; 
 5278:         foreach my $role (keys(%{$allroles})) {
 5279:             push(@groupkeys,$role);
 5280:         }
 5281:         if (ref($groups_roles) eq 'HASH') {
 5282:             foreach my $key (keys(%{$groups_roles})) {
 5283:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5284:                     push(@groupkeys,$key);
 5285:                 }
 5286:             }
 5287:         }
 5288:         if (@groupkeys > 0) {
 5289:             foreach my $role (@groupkeys) {
 5290:                 my ($trole,$area,$sec,$extendedarea);
 5291:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5292:                     $trole = $1;
 5293:                     $area = $2;
 5294:                     $sec = $3;
 5295:                     $extendedarea = $area.$sec;
 5296:                     if (exists($$allgroups{$area})) {
 5297:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5298:                             my $spec = $trole.'.'.$extendedarea;
 5299:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5300:                                                 $$allgroups{$area}{$group};
 5301:                         }
 5302:                     }
 5303:                 }
 5304:             }
 5305:         }
 5306:     }
 5307:     foreach my $group (keys(%grouproles)) {
 5308:         $$allroles{$group} = $grouproles{$group};
 5309:     }
 5310:     foreach my $role (keys(%{$allroles})) {
 5311:         my %thesepriv;
 5312:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5313:         foreach my $item (split(/:/,$$allroles{$role})) {
 5314:             if ($item ne '') {
 5315:                 my ($privilege,$restrictions)=split(/&/,$item);
 5316:                 if ($restrictions eq '') {
 5317:                     $thesepriv{$privilege}='F';
 5318:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5319:                     $thesepriv{$privilege}.=$restrictions;
 5320:                 }
 5321:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5322:             }
 5323:         }
 5324:         my $thesestr='';
 5325:         foreach my $priv (sort(keys(%thesepriv))) {
 5326: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5327: 	}
 5328:         $userroles->{'user.priv.'.$role} = $thesestr;
 5329:     }
 5330:     return ($author,$adv);
 5331: }
 5332: 
 5333: sub role_status {
 5334:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5335:     my @pwhere = ();
 5336:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5337:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5338:         unless (!defined($$role) || $$role eq '') {
 5339:             $$where=join('.',@pwhere);
 5340:             $$trolecode=$$role.'.'.$$where;
 5341:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5342:             $$tstatus='is';
 5343:             if ($$tstart && $$tstart>$update) {
 5344:                 $$tstatus='future';
 5345:                 if ($$tstart<$now) {
 5346:                     if ($$tstart && $$tstart>$refresh) {
 5347:                         if (($$where ne '') && ($$role ne '')) {
 5348:                             my (%allroles,%allgroups,$group_privs,
 5349:                                 %groups_roles,@rolecodes);
 5350:                             my %userroles = (
 5351:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5352:                             );
 5353:                             @rolecodes = ('cm'); 
 5354:                             my $spec=$$role.'.'.$$where;
 5355:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5356:                             if ($$role =~ /^cr\//) {
 5357:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5358:                                 push(@rolecodes,'cr');
 5359:                             } elsif ($$role eq 'gr') {
 5360:                                 push(@rolecodes,$$role);
 5361:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5362:                                                     $env{'user.name'});
 5363:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5364:                                 (undef,my $group_privs) = split(/\//,$trole);
 5365:                                 $group_privs = &unescape($group_privs);
 5366:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5367:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5368:                                 &get_groups_roles($tdomain,$trest,
 5369:                                                   \%course_roles,\@rolecodes,
 5370:                                                   \%groups_roles);
 5371:                             } else {
 5372:                                 push(@rolecodes,$$role);
 5373:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5374:                             }
 5375:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5376:                             &appenv(\%userroles,\@rolecodes);
 5377:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5378:                         }
 5379:                     }
 5380:                     $$tstatus = 'is';
 5381:                 }
 5382:             }
 5383:             if ($$tend) {
 5384:                 if ($$tend<$update) {
 5385:                     $$tstatus='expired';
 5386:                 } elsif ($$tend<$now) {
 5387:                     $$tstatus='will_not';
 5388:                 }
 5389:             }
 5390:         }
 5391:     }
 5392: }
 5393: 
 5394: sub get_groups_roles {
 5395:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5396:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5397:                   (ref($rolecodes) eq 'ARRAY') && 
 5398:                   (ref($groups_roles) eq 'HASH')); 
 5399:     if (keys(%{$cdom_courseroles}) > 0) {
 5400:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5401:         if ($cdom ne '' && $cnum ne '') {
 5402:             foreach my $key (keys(%{$cdom_courseroles})) {
 5403:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5404:                     my $crsrole = $1;
 5405:                     my $crssec = $2;
 5406:                     if ($crsrole =~ /^cr/) {
 5407:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5408:                             push(@{$rolecodes},'cr');
 5409:                         }
 5410:                     } else {
 5411:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5412:                             push(@{$rolecodes},$crsrole);
 5413:                         }
 5414:                     }
 5415:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5416:                     if ($crssec ne '') {
 5417:                         $rolekey .= "/$crssec";
 5418:                     }
 5419:                     $rolekey .= './';
 5420:                     $groups_roles->{$rolekey} = $rolecodes;
 5421:                 }
 5422:             }
 5423:         }
 5424:     }
 5425:     return;
 5426: }
 5427: 
 5428: sub delete_env_groupprivs {
 5429:     my ($where,$courseroles,$possroles) = @_;
 5430:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5431:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5432:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5433:         %{$courseroles->{$udom}} =
 5434:             &get_my_roles('','','userroles',['active'],
 5435:                           $possroles,[$udom],1);
 5436:     }
 5437:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5438:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5439:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5440:             my $area = '/'.$cdom.'/'.$cnum;
 5441:             my $privkey = "user.priv.$crsrole.$area";
 5442:             if ($crssec ne '') {
 5443:                 $privkey .= '/'.$crssec;
 5444:             }
 5445:             $privkey .= ".$area/$group";
 5446:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5447:         }
 5448:     }
 5449:     return;
 5450: }
 5451: 
 5452: sub check_adhoc_privs {
 5453:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5454:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5455:     my $setprivs;
 5456:     if ($env{$cckey}) {
 5457:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5458:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5459:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5460:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5461:             $setprivs = 1;
 5462:         }
 5463:     } else {
 5464:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5465:         $setprivs = 1;
 5466:     }
 5467:     return $setprivs;
 5468: }
 5469: 
 5470: sub set_adhoc_privileges {
 5471: # role can be cc or ca
 5472:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5473:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5474:     my $spec = $role.'.'.$area;
 5475:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5476:                                   $env{'user.name'},1);
 5477:     my %ccrole = ();
 5478:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5479:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5480:     &appenv(\%userroles,[$role,'cm']);
 5481:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5482:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5483:         &appenv( {'request.role'        => $spec,
 5484:                   'request.role.domain' => $dcdom,
 5485:                   'request.course.sec'  => ''
 5486:                  }
 5487:                );
 5488:         my $tadv=0;
 5489:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5490:         &appenv({'request.role.adv'    => $tadv});
 5491:     }
 5492: }
 5493: 
 5494: # --------------------------------------------------------------- get interface
 5495: 
 5496: sub get {
 5497:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5498:    my $items='';
 5499:    foreach my $item (@$storearr) {
 5500:        $items.=&escape($item).'&';
 5501:    }
 5502:    $items=~s/\&$//;
 5503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5504:    if (!$uname) { $uname=$env{'user.name'}; }
 5505:    my $uhome=&homeserver($uname,$udomain);
 5506: 
 5507:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5508:    my @pairs=split(/\&/,$rep);
 5509:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5510:      return @pairs;
 5511:    }
 5512:    my %returnhash=();
 5513:    my $i=0;
 5514:    foreach my $item (@$storearr) {
 5515:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5516:       $i++;
 5517:    }
 5518:    return %returnhash;
 5519: }
 5520: 
 5521: # --------------------------------------------------------------- del interface
 5522: 
 5523: sub del {
 5524:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5525:    my $items='';
 5526:    foreach my $item (@$storearr) {
 5527:        $items.=&escape($item).'&';
 5528:    }
 5529: 
 5530:    $items=~s/\&$//;
 5531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5532:    if (!$uname) { $uname=$env{'user.name'}; }
 5533:    my $uhome=&homeserver($uname,$udomain);
 5534:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5535: }
 5536: 
 5537: # -------------------------------------------------------------- dump interface
 5538: 
 5539: sub unserialize {
 5540:     my ($rep, $escapedkeys) = @_;
 5541: 
 5542:     return {} if $rep =~ /^error/;
 5543: 
 5544:     my %returnhash=();
 5545: 	foreach my $item (split /\&/, $rep) {
 5546: 	    my ($key, $value) = split(/=/, $item, 2);
 5547: 	    $key = unescape($key) unless $escapedkeys;
 5548: 	    next if $key =~ /^error: 2 /;
 5549: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5550: 	}
 5551:     #return %returnhash;
 5552:     return \%returnhash;
 5553: }        
 5554: 
 5555: # see Lond::dump_with_regexp
 5556: # if $escapedkeys hash keys won't get unescaped.
 5557: sub dump {
 5558:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5559:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5560:     if (!$uname) { $uname=$env{'user.name'}; }
 5561:     my $uhome=&homeserver($uname,$udomain);
 5562: 
 5563:     my $reply;
 5564:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5565:         # user is hosted on this machine
 5566:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5567:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5568:         return %{unserialize($reply, $escapedkeys)};
 5569:     }
 5570:     if ($regexp) {
 5571: 	$regexp=&escape($regexp);
 5572:     } else {
 5573: 	$regexp='.';
 5574:     }
 5575:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5576:     my @pairs=split(/\&/,$rep);
 5577:     my %returnhash=();
 5578:     if (!($rep =~ /^error/ )) {
 5579: 	foreach my $item (@pairs) {
 5580: 	    my ($key,$value)=split(/=/,$item,2);
 5581:         $key = unescape($key) unless $escapedkeys;
 5582:         #$key = &unescape($key);
 5583: 	    next if ($key =~ /^error: 2 /);
 5584: 	    $returnhash{$key}=&thaw_unescape($value);
 5585: 	}
 5586:     }
 5587:     return %returnhash;
 5588: }
 5589: 
 5590: 
 5591: # --------------------------------------------------------- dumpstore interface
 5592: 
 5593: sub dumpstore {
 5594:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5595:    # same as dump but keys must be escaped. They may contain colon separated
 5596:    # lists of values that may themself contain colons (e.g. symbs).
 5597:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5598: }
 5599: 
 5600: # -------------------------------------------------------------- keys interface
 5601: 
 5602: sub getkeys {
 5603:    my ($namespace,$udomain,$uname)=@_;
 5604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5605:    if (!$uname) { $uname=$env{'user.name'}; }
 5606:    my $uhome=&homeserver($uname,$udomain);
 5607:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5608:    my @keyarray=();
 5609:    foreach my $key (split(/\&/,$rep)) {
 5610:       next if ($key =~ /^error: 2 /);
 5611:       push(@keyarray,&unescape($key));
 5612:    }
 5613:    return @keyarray;
 5614: }
 5615: 
 5616: # --------------------------------------------------------------- currentdump
 5617: sub currentdump {
 5618:    my ($courseid,$sdom,$sname)=@_;
 5619:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5620:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5621:    $sname    = $env{'user.name'}         if (! defined($sname));
 5622:    my $uhome = &homeserver($sname,$sdom);
 5623:    my $rep;
 5624: 
 5625:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5626:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5627:                    $courseid)));
 5628:    } else {
 5629:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5630:    }
 5631: 
 5632:    return if ($rep =~ /^(error:|no_such_host)/);
 5633:    #
 5634:    my %returnhash=();
 5635:    #
 5636:    if ($rep eq "unknown_cmd") { 
 5637:        # an old lond will not know currentdump
 5638:        # Do a dump and make it look like a currentdump
 5639:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5640:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5641:        my %hash = @tmp;
 5642:        @tmp=();
 5643:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5644:    } else {
 5645:        my @pairs=split(/\&/,$rep);
 5646:        foreach my $pair (@pairs) {
 5647:            my ($key,$value)=split(/=/,$pair,2);
 5648:            my ($symb,$param) = split(/:/,$key);
 5649:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5650:                                                         &thaw_unescape($value);
 5651:        }
 5652:    }
 5653:    return %returnhash;
 5654: }
 5655: 
 5656: sub convert_dump_to_currentdump{
 5657:     my %hash = %{shift()};
 5658:     my %returnhash;
 5659:     # Code ripped from lond, essentially.  The only difference
 5660:     # here is the unescaping done by lonnet::dump().  Conceivably
 5661:     # we might run in to problems with parameter names =~ /^v\./
 5662:     while (my ($key,$value) = each(%hash)) {
 5663:         my ($v,$symb,$param) = split(/:/,$key);
 5664: 	$symb  = &unescape($symb);
 5665: 	$param = &unescape($param);
 5666:         next if ($v eq 'version' || $symb eq 'keys');
 5667:         next if (exists($returnhash{$symb}) &&
 5668:                  exists($returnhash{$symb}->{$param}) &&
 5669:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5670:         $returnhash{$symb}->{$param}=$value;
 5671:         $returnhash{$symb}->{'v.'.$param}=$v;
 5672:     }
 5673:     #
 5674:     # Remove all of the keys in the hashes which keep track of
 5675:     # the version of the parameter.
 5676:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5677:         # use a foreach because we are going to delete from the hash.
 5678:         foreach my $key (keys(%$param_hash)) {
 5679:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5680:         }
 5681:     }
 5682:     return \%returnhash;
 5683: }
 5684: 
 5685: # ------------------------------------------------------ critical inc interface
 5686: 
 5687: sub cinc {
 5688:     return &inc(@_,'critical');
 5689: }
 5690: 
 5691: # --------------------------------------------------------------- inc interface
 5692: 
 5693: sub inc {
 5694:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5695:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5696:     if (!$uname) { $uname=$env{'user.name'}; }
 5697:     my $uhome=&homeserver($uname,$udomain);
 5698:     my $items='';
 5699:     if (! ref($store)) {
 5700:         # got a single value, so use that instead
 5701:         $items = &escape($store).'=&';
 5702:     } elsif (ref($store) eq 'SCALAR') {
 5703:         $items = &escape($$store).'=&';        
 5704:     } elsif (ref($store) eq 'ARRAY') {
 5705:         $items = join('=&',map {&escape($_);} @{$store});
 5706:     } elsif (ref($store) eq 'HASH') {
 5707:         while (my($key,$value) = each(%{$store})) {
 5708:             $items.= &escape($key).'='.&escape($value).'&';
 5709:         }
 5710:     }
 5711:     $items=~s/\&$//;
 5712:     if ($critical) {
 5713: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5714:     } else {
 5715: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5716:     }
 5717: }
 5718: 
 5719: # --------------------------------------------------------------- put interface
 5720: 
 5721: sub put {
 5722:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5724:    if (!$uname) { $uname=$env{'user.name'}; }
 5725:    my $uhome=&homeserver($uname,$udomain);
 5726:    my $items='';
 5727:    foreach my $item (keys(%$storehash)) {
 5728:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5729:    }
 5730:    $items=~s/\&$//;
 5731:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5732: }
 5733: 
 5734: # ------------------------------------------------------------ newput interface
 5735: 
 5736: sub newput {
 5737:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5738:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5739:    if (!$uname) { $uname=$env{'user.name'}; }
 5740:    my $uhome=&homeserver($uname,$udomain);
 5741:    my $items='';
 5742:    foreach my $key (keys(%$storehash)) {
 5743:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5744:    }
 5745:    $items=~s/\&$//;
 5746:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5747: }
 5748: 
 5749: # ---------------------------------------------------------  putstore interface
 5750: 
 5751: sub putstore {
 5752:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5754:    if (!$uname) { $uname=$env{'user.name'}; }
 5755:    my $uhome=&homeserver($uname,$udomain);
 5756:    my $items='';
 5757:    foreach my $key (keys(%$storehash)) {
 5758:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5759:    }
 5760:    $items=~s/\&$//;
 5761:    my $esc_symb=&escape($symb);
 5762:    my $esc_v=&escape($version);
 5763:    my $reply =
 5764:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5765: 	      $uhome);
 5766:    if ($reply eq 'unknown_cmd') {
 5767:        # gfall back to way things use to be done
 5768:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5769: 			    $uname);
 5770:    }
 5771:    return $reply;
 5772: }
 5773: 
 5774: sub old_putstore {
 5775:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5776:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5777:     if (!$uname) { $uname=$env{'user.name'}; }
 5778:     my $uhome=&homeserver($uname,$udomain);
 5779:     my %newstorehash;
 5780:     foreach my $item (keys(%$storehash)) {
 5781: 	my $key = $version.':'.&escape($symb).':'.$item;
 5782: 	$newstorehash{$key} = $storehash->{$item};
 5783:     }
 5784:     my $items='';
 5785:     my %allitems = ();
 5786:     foreach my $item (keys(%newstorehash)) {
 5787: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5788: 	    my $key = $1.':keys:'.$2;
 5789: 	    $allitems{$key} .= $3.':';
 5790: 	}
 5791: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5792:     }
 5793:     foreach my $item (keys(%allitems)) {
 5794: 	$allitems{$item} =~ s/\:$//;
 5795: 	$items.= $item.'='.$allitems{$item}.'&';
 5796:     }
 5797:     $items=~s/\&$//;
 5798:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5799: }
 5800: 
 5801: # ------------------------------------------------------ critical put interface
 5802: 
 5803: sub cput {
 5804:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5805:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5806:    if (!$uname) { $uname=$env{'user.name'}; }
 5807:    my $uhome=&homeserver($uname,$udomain);
 5808:    my $items='';
 5809:    foreach my $item (keys(%$storehash)) {
 5810:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5811:    }
 5812:    $items=~s/\&$//;
 5813:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5814: }
 5815: 
 5816: # -------------------------------------------------------------- eget interface
 5817: 
 5818: sub eget {
 5819:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5820:    my $items='';
 5821:    foreach my $item (@$storearr) {
 5822:        $items.=&escape($item).'&';
 5823:    }
 5824:    $items=~s/\&$//;
 5825:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5826:    if (!$uname) { $uname=$env{'user.name'}; }
 5827:    my $uhome=&homeserver($uname,$udomain);
 5828:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5829:    my @pairs=split(/\&/,$rep);
 5830:    my %returnhash=();
 5831:    my $i=0;
 5832:    foreach my $item (@$storearr) {
 5833:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5834:       $i++;
 5835:    }
 5836:    return %returnhash;
 5837: }
 5838: 
 5839: # ------------------------------------------------------------ tmpput interface
 5840: sub tmpput {
 5841:     my ($storehash,$server,$context)=@_;
 5842:     my $items='';
 5843:     foreach my $item (keys(%$storehash)) {
 5844: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5845:     }
 5846:     $items=~s/\&$//;
 5847:     if (defined($context)) {
 5848:         $items .= ':'.&escape($context);
 5849:     }
 5850:     return &reply("tmpput:$items",$server);
 5851: }
 5852: 
 5853: # ------------------------------------------------------------ tmpget interface
 5854: sub tmpget {
 5855:     my ($token,$server)=@_;
 5856:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5857:     my $rep=&reply("tmpget:$token",$server);
 5858:     my %returnhash;
 5859:     foreach my $item (split(/\&/,$rep)) {
 5860: 	my ($key,$value)=split(/=/,$item);
 5861:         next if ($key =~ /^error: 2 /);
 5862: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5863:     }
 5864:     return %returnhash;
 5865: }
 5866: 
 5867: # ------------------------------------------------------------ tmpdel interface
 5868: sub tmpdel {
 5869:     my ($token,$server)=@_;
 5870:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5871:     return &reply("tmpdel:$token",$server);
 5872: }
 5873: 
 5874: # ------------------------------------------------------------ get_timebased_id 
 5875: 
 5876: sub get_timebased_id {
 5877:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5878:         $maxtries) = @_;
 5879:     my ($newid,$error,$dellock);
 5880:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5881:         return ('','ok','invalid call to get suffix');
 5882:     }
 5883: 
 5884: # set defaults for any optional args for which values were not supplied
 5885:     if ($who eq '') {
 5886:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5887:     }
 5888:     if (!$locktries) {
 5889:         $locktries = 3;
 5890:     }
 5891:     if (!$maxtries) {
 5892:         $maxtries = 10;
 5893:     }
 5894:     
 5895:     if (($cdom eq '') || ($cnum eq '')) {
 5896:         if ($env{'request.course.id'}) {
 5897:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5898:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5899:         }
 5900:         if (($cdom eq '') || ($cnum eq '')) {
 5901:             return ('','ok','call to get suffix not in course context');
 5902:         }
 5903:     }
 5904: 
 5905: # construct locking item
 5906:     my $lockhash = {
 5907:                       $prefix."\0".'locked_'.$keyid => $who,
 5908:                    };
 5909:     my $tries = 0;
 5910: 
 5911: # attempt to get lock on nohist_$namespace file
 5912:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5913:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5914:         $tries ++;
 5915:         sleep 1;
 5916:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5917:     }
 5918: 
 5919: # attempt to get unique identifier, based on current timestamp
 5920:     if ($gotlock eq 'ok') {
 5921:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5922:         my $id = time;
 5923:         $newid = $id;
 5924:         my $idtries = 0;
 5925:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5926:             if ($idtype eq 'concat') {
 5927:                 $newid = $id.$idtries;
 5928:             } else {
 5929:                 $newid ++;
 5930:             }
 5931:             $idtries ++;
 5932:         }
 5933:         if (!exists($inuse{$prefix."\0".$newid})) {
 5934:             my %new_item =  (
 5935:                               $prefix."\0".$newid => $who,
 5936:                             );
 5937:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5938:                                                  $cdom,$cnum);
 5939:             if ($putresult ne 'ok') {
 5940:                 undef($newid);
 5941:                 $error = 'error saving new item: '.$putresult;
 5942:             }
 5943:         } else {
 5944:              $error = ('error: no unique suffix available for the new item ');
 5945:         }
 5946: #  remove lock
 5947:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5948:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5949:     } else {
 5950:         $error = "error: could not obtain lockfile\n";
 5951:         $dellock = 'ok';
 5952:     }
 5953:     return ($newid,$dellock,$error);
 5954: }
 5955: 
 5956: # -------------------------------------------------- portfolio access checking
 5957: 
 5958: sub portfolio_access {
 5959:     my ($requrl) = @_;
 5960:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5961:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5962:     if ($result) {
 5963:         my %setters;
 5964:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5965:             my ($startblock,$endblock) =
 5966:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5967:             if ($startblock && $endblock) {
 5968:                 return 'B';
 5969:             }
 5970:         } else {
 5971:             my ($startblock,$endblock) =
 5972:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5973:             if ($startblock && $endblock) {
 5974:                 return 'B';
 5975:             }
 5976:         }
 5977:     }
 5978:     if ($result eq 'ok') {
 5979:        return 'F';
 5980:     } elsif ($result =~ /^[^:]+:guest_/) {
 5981:        return 'A';
 5982:     }
 5983:     return '';
 5984: }
 5985: 
 5986: sub get_portfolio_access {
 5987:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5988: 
 5989:     if (!ref($access_hash)) {
 5990: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5991: 	my %access_controls = &get_access_controls($current_perms,$group,
 5992: 						   $file_name);
 5993: 	$access_hash = $access_controls{$file_name};
 5994:     }
 5995: 
 5996:     my ($public,$guest,@domains,@users,@courses,@groups);
 5997:     my $now = time;
 5998:     if (ref($access_hash) eq 'HASH') {
 5999:         foreach my $key (keys(%{$access_hash})) {
 6000:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6001:             if ($start > $now) {
 6002:                 next;
 6003:             }
 6004:             if ($end && $end<$now) {
 6005:                 next;
 6006:             }
 6007:             if ($scope eq 'public') {
 6008:                 $public = $key;
 6009:                 last;
 6010:             } elsif ($scope eq 'guest') {
 6011:                 $guest = $key;
 6012:             } elsif ($scope eq 'domains') {
 6013:                 push(@domains,$key);
 6014:             } elsif ($scope eq 'users') {
 6015:                 push(@users,$key);
 6016:             } elsif ($scope eq 'course') {
 6017:                 push(@courses,$key);
 6018:             } elsif ($scope eq 'group') {
 6019:                 push(@groups,$key);
 6020:             }
 6021:         }
 6022:         if ($public) {
 6023:             return 'ok';
 6024:         }
 6025:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6026:             if ($guest) {
 6027:                 return $guest;
 6028:             }
 6029:         } else {
 6030:             if (@domains > 0) {
 6031:                 foreach my $domkey (@domains) {
 6032:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6033:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6034:                             return 'ok';
 6035:                         }
 6036:                     }
 6037:                 }
 6038:             }
 6039:             if (@users > 0) {
 6040:                 foreach my $userkey (@users) {
 6041:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6042:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6043:                             if (ref($item) eq 'HASH') {
 6044:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6045:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6046:                                     return 'ok';
 6047:                                 }
 6048:                             }
 6049:                         }
 6050:                     } 
 6051:                 }
 6052:             }
 6053:             my %roleshash;
 6054:             my @courses_and_groups = @courses;
 6055:             push(@courses_and_groups,@groups); 
 6056:             if (@courses_and_groups > 0) {
 6057:                 my (%allgroups,%allroles); 
 6058:                 my ($start,$end,$role,$sec,$group);
 6059:                 foreach my $envkey (%env) {
 6060:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6061:                         my $cid = $2.'_'.$3; 
 6062:                         if ($1 eq 'gr') {
 6063:                             $group = $4;
 6064:                             $allgroups{$cid}{$group} = $env{$envkey};
 6065:                         } else {
 6066:                             if ($4 eq '') {
 6067:                                 $sec = 'none';
 6068:                             } else {
 6069:                                 $sec = $4;
 6070:                             }
 6071:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6072:                         }
 6073:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6074:                         my $cid = $2.'_'.$3;
 6075:                         if ($4 eq '') {
 6076:                             $sec = 'none';
 6077:                         } else {
 6078:                             $sec = $4;
 6079:                         }
 6080:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6081:                     }
 6082:                 }
 6083:                 if (keys(%allroles) == 0) {
 6084:                     return;
 6085:                 }
 6086:                 foreach my $key (@courses_and_groups) {
 6087:                     my %content = %{$$access_hash{$key}};
 6088:                     my $cnum = $content{'number'};
 6089:                     my $cdom = $content{'domain'};
 6090:                     my $cid = $cdom.'_'.$cnum;
 6091:                     if (!exists($allroles{$cid})) {
 6092:                         next;
 6093:                     }    
 6094:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6095:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6096:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6097:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6098:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6099:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6100:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6101:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6102:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6103:                                         if (grep/^all$/,@sections) {
 6104:                                             return 'ok';
 6105:                                         } else {
 6106:                                             if (grep/^$sec$/,@sections) {
 6107:                                                 return 'ok';
 6108:                                             }
 6109:                                         }
 6110:                                     }
 6111:                                 }
 6112:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6113:                                     if (grep/^none$/,@groups) {
 6114:                                         return 'ok';
 6115:                                     }
 6116:                                 } else {
 6117:                                     if (grep/^all$/,@groups) {
 6118:                                         return 'ok';
 6119:                                     } 
 6120:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6121:                                         if (grep/^$group$/,@groups) {
 6122:                                             return 'ok';
 6123:                                         }
 6124:                                     }
 6125:                                 } 
 6126:                             }
 6127:                         }
 6128:                     }
 6129:                 }
 6130:             }
 6131:             if ($guest) {
 6132:                 return $guest;
 6133:             }
 6134:         }
 6135:     }
 6136:     return;
 6137: }
 6138: 
 6139: sub course_group_datechecker {
 6140:     my ($dates,$now,$status) = @_;
 6141:     my ($start,$end) = split(/\./,$dates);
 6142:     if (!$start && !$end) {
 6143:         return 'ok';
 6144:     }
 6145:     if (grep/^active$/,@{$status}) {
 6146:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6147:             return 'ok';
 6148:         }
 6149:     }
 6150:     if (grep/^previous$/,@{$status}) {
 6151:         if ($end > $now ) {
 6152:             return 'ok';
 6153:         }
 6154:     }
 6155:     if (grep/^future$/,@{$status}) {
 6156:         if ($start > $now) {
 6157:             return 'ok';
 6158:         }
 6159:     }
 6160:     return; 
 6161: }
 6162: 
 6163: sub parse_portfolio_url {
 6164:     my ($url) = @_;
 6165: 
 6166:     my ($type,$udom,$unum,$group,$file_name);
 6167:     
 6168:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6169: 	$type = 1;
 6170:         $udom = $1;
 6171:         $unum = $2;
 6172:         $file_name = $3;
 6173:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6174: 	$type = 2;
 6175:         $udom = $1;
 6176:         $unum = $2;
 6177:         $group = $3;
 6178:         $file_name = $3.'/'.$4;
 6179:     }
 6180:     if (wantarray) {
 6181: 	return ($type,$udom,$unum,$file_name,$group);
 6182:     }
 6183:     return $type;
 6184: }
 6185: 
 6186: sub is_portfolio_url {
 6187:     my ($url) = @_;
 6188:     return scalar(&parse_portfolio_url($url));
 6189: }
 6190: 
 6191: sub is_portfolio_file {
 6192:     my ($file) = @_;
 6193:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6194:         return 1;
 6195:     }
 6196:     return;
 6197: }
 6198: 
 6199: sub usertools_access {
 6200:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6201:     my ($access,%tools);
 6202:     if ($context eq '') {
 6203:         $context = 'tools';
 6204:     }
 6205:     if ($context eq 'requestcourses') {
 6206:         %tools = (
 6207:                       official   => 1,
 6208:                       unofficial => 1,
 6209:                       community  => 1,
 6210:                  );
 6211:     } elsif ($context eq 'requestauthor') {
 6212:         %tools = (
 6213:                       requestauthor => 1,
 6214:                  );
 6215:     } else {
 6216:         %tools = (
 6217:                       aboutme   => 1,
 6218:                       blog      => 1,
 6219:                       webdav    => 1,
 6220:                       portfolio => 1,
 6221:                  );
 6222:     }
 6223:     return if (!defined($tools{$tool}));
 6224: 
 6225:     if (($udom eq '') || ($uname eq '')) {
 6226:         $udom = $env{'user.domain'};
 6227:         $uname = $env{'user.name'};
 6228:     }
 6229: 
 6230:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6231:         if ($action ne 'reload') {
 6232:             if ($context eq 'requestcourses') {
 6233:                 return $env{'environment.canrequest.'.$tool};
 6234:             } elsif ($context eq 'requestauthor') {
 6235:                 return $env{'environment.canrequest.author'};
 6236:             } else {
 6237:                 return $env{'environment.availabletools.'.$tool};
 6238:             }
 6239:         }
 6240:     }
 6241: 
 6242:     my ($toolstatus,$inststatus,$envkey);
 6243:     if ($context eq 'requestauthor') {
 6244:         $envkey = $context; 
 6245:     } else {
 6246:         $envkey = $context.'.'.$tool;
 6247:     }
 6248: 
 6249:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6250:          ($action ne 'reload')) {
 6251:         $toolstatus = $env{'environment.'.$envkey};
 6252:         $inststatus = $env{'environment.inststatus'};
 6253:     } else {
 6254:         if (ref($userenvref) eq 'HASH') {
 6255:             $toolstatus = $userenvref->{$envkey};
 6256:             $inststatus = $userenvref->{'inststatus'};
 6257:         } else {
 6258:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6259:             $toolstatus = $userenv{$envkey};
 6260:             $inststatus = $userenv{'inststatus'};
 6261:         }
 6262:     }
 6263: 
 6264:     if ($toolstatus ne '') {
 6265:         if ($toolstatus) {
 6266:             $access = 1;
 6267:         } else {
 6268:             $access = 0;
 6269:         }
 6270:         return $access;
 6271:     }
 6272: 
 6273:     my ($is_adv,%domdef);
 6274:     if (ref($is_advref) eq 'HASH') {
 6275:         $is_adv = $is_advref->{'is_adv'};
 6276:     } else {
 6277:         $is_adv = &is_advanced_user($udom,$uname);
 6278:     }
 6279:     if (ref($domdefref) eq 'HASH') {
 6280:         %domdef = %{$domdefref};
 6281:     } else {
 6282:         %domdef = &get_domain_defaults($udom);
 6283:     }
 6284:     if (ref($domdef{$tool}) eq 'HASH') {
 6285:         if ($is_adv) {
 6286:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6287:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6288:                     $access = 1;
 6289:                 } else {
 6290:                     $access = 0;
 6291:                 }
 6292:                 return $access;
 6293:             }
 6294:         }
 6295:         if ($inststatus ne '') {
 6296:             my ($hasaccess,$hasnoaccess);
 6297:             foreach my $affiliation (split(/:/,$inststatus)) {
 6298:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6299:                     if ($domdef{$tool}{$affiliation}) {
 6300:                         $hasaccess = 1;
 6301:                     } else {
 6302:                         $hasnoaccess = 1;
 6303:                     }
 6304:                 }
 6305:             }
 6306:             if ($hasaccess || $hasnoaccess) {
 6307:                 if ($hasaccess) {
 6308:                     $access = 1;
 6309:                 } elsif ($hasnoaccess) {
 6310:                     $access = 0; 
 6311:                 }
 6312:                 return $access;
 6313:             }
 6314:         } else {
 6315:             if ($domdef{$tool}{'default'} ne '') {
 6316:                 if ($domdef{$tool}{'default'}) {
 6317:                     $access = 1;
 6318:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6319:                     $access = 0;
 6320:                 }
 6321:                 return $access;
 6322:             }
 6323:         }
 6324:     } else {
 6325:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6326:             $access = 1;
 6327:         } else {
 6328:             $access = 0;
 6329:         }
 6330:         return $access;
 6331:     }
 6332: }
 6333: 
 6334: sub is_course_owner {
 6335:     my ($cdom,$cnum,$udom,$uname) = @_;
 6336:     if (($udom eq '') || ($uname eq '')) {
 6337:         $udom = $env{'user.domain'};
 6338:         $uname = $env{'user.name'};
 6339:     }
 6340:     unless (($udom eq '') || ($uname eq '')) {
 6341:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6342:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6343:                 return 1;
 6344:             } else {
 6345:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6346:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6347:                     return 1;
 6348:                 }
 6349:             }
 6350:         }
 6351:     }
 6352:     return;
 6353: }
 6354: 
 6355: sub is_advanced_user {
 6356:     my ($udom,$uname) = @_;
 6357:     if ($udom ne '' && $uname ne '') {
 6358:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6359:             if (wantarray) {
 6360:                 return ($env{'user.adv'},$env{'user.author'});
 6361:             } else {
 6362:                 return $env{'user.adv'};
 6363:             }
 6364:         }
 6365:     }
 6366:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6367:     my %allroles;
 6368:     my ($is_adv,$is_author);
 6369:     foreach my $role (keys(%roleshash)) {
 6370:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6371:         my $area = '/'.$tdomain.'/'.$trest;
 6372:         if ($sec ne '') {
 6373:             $area .= '/'.$sec;
 6374:         }
 6375:         if (($area ne '') && ($trole ne '')) {
 6376:             my $spec=$trole.'.'.$area;
 6377:             if ($trole =~ /^cr\//) {
 6378:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6379:             } elsif ($trole ne 'gr') {
 6380:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6381:             }
 6382:             if ($trole eq 'au') {
 6383:                 $is_author = 1;
 6384:             }
 6385:         }
 6386:     }
 6387:     foreach my $role (keys(%allroles)) {
 6388:         last if ($is_adv);
 6389:         foreach my $item (split(/:/,$allroles{$role})) {
 6390:             if ($item ne '') {
 6391:                 my ($privilege,$restrictions)=split(/&/,$item);
 6392:                 if ($privilege eq 'adv') {
 6393:                     $is_adv = 1;
 6394:                     last;
 6395:                 }
 6396:             }
 6397:         }
 6398:     }
 6399:     if (wantarray) {
 6400:         return ($is_adv,$is_author);
 6401:     }
 6402:     return $is_adv;
 6403: }
 6404: 
 6405: sub check_can_request {
 6406:     my ($dom,$can_request,$request_domains) = @_;
 6407:     my $canreq = 0;
 6408:     my ($types,$typename) = &Apache::loncommon::course_types();
 6409:     my @options = ('approval','validate','autolimit');
 6410:     my $optregex = join('|',@options);
 6411:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6412:         foreach my $type (@{$types}) {
 6413:             if (&usertools_access($env{'user.name'},
 6414:                                   $env{'user.domain'},
 6415:                                   $type,undef,'requestcourses')) {
 6416:                 $canreq ++;
 6417:                 if (ref($request_domains) eq 'HASH') {
 6418:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6419:                 }
 6420:                 if ($dom eq $env{'user.domain'}) {
 6421:                     $can_request->{$type} = 1;
 6422:                 }
 6423:             }
 6424:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6425:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6426:                 if (@curr > 0) {
 6427:                     foreach my $item (@curr) {
 6428:                         if (ref($request_domains) eq 'HASH') {
 6429:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6430:                             if ($otherdom ne '') {
 6431:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6432:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6433:                                         push(@{$request_domains->{$type}},$otherdom);
 6434:                                     }
 6435:                                 } else {
 6436:                                     push(@{$request_domains->{$type}},$otherdom);
 6437:                                 }
 6438:                             }
 6439:                         }
 6440:                     }
 6441:                     unless($dom eq $env{'user.domain'}) {
 6442:                         $canreq ++;
 6443:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6444:                             $can_request->{$type} = 1;
 6445:                         }
 6446:                     }
 6447:                 }
 6448:             }
 6449:         }
 6450:     }
 6451:     return $canreq;
 6452: }
 6453: 
 6454: # ---------------------------------------------- Custom access rule evaluation
 6455: 
 6456: sub customaccess {
 6457:     my ($priv,$uri)=@_;
 6458:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6459:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6460:     $udom = &LONCAPA::clean_domain($udom);
 6461:     $ucrs = &LONCAPA::clean_username($ucrs);
 6462:     my $access=0;
 6463:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6464: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6465: 	if ($type eq 'user') {
 6466: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6467: 		my ($tdom,$tuname)=split(m{/},$scope);
 6468: 		if ($tdom) {
 6469: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6470: 		}
 6471: 		if ($tuname) {
 6472: 		    if ($tuname ne $env{'user.name'}) { next; }
 6473: 		}
 6474: 		$access=($effect eq 'allow');
 6475: 		last;
 6476: 	    }
 6477: 	} else {
 6478: 	    if ($role) {
 6479: 		if ($role ne $urole) { next; }
 6480: 	    }
 6481: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6482: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6483: 		if ($tdom) {
 6484: 		    if ($tdom ne $udom) { next; }
 6485: 		}
 6486: 		if ($tcrs) {
 6487: 		    if ($tcrs ne $ucrs) { next; }
 6488: 		}
 6489: 		if ($tsec) {
 6490: 		    if ($tsec ne $usec) { next; }
 6491: 		}
 6492: 		$access=($effect eq 'allow');
 6493: 		last;
 6494: 	    }
 6495: 	    if ($realm eq '' && $role eq '') {
 6496: 		$access=($effect eq 'allow');
 6497: 	    }
 6498: 	}
 6499:     }
 6500:     return $access;
 6501: }
 6502: 
 6503: # ------------------------------------------------- Check for a user privilege
 6504: 
 6505: sub allowed {
 6506:     my ($priv,$uri,$symb,$role)=@_;
 6507:     my $ver_orguri=$uri;
 6508:     $uri=&deversion($uri);
 6509:     my $orguri=$uri;
 6510:     $uri=&declutter($uri);
 6511: 
 6512:     if ($priv eq 'evb') {
 6513: # Evade communication block restrictions for specified role in a course
 6514:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6515:             return $1;
 6516:         } else {
 6517:             return;
 6518:         }
 6519:     }
 6520: 
 6521:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6522: # Free bre access to adm and meta resources
 6523:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6524: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6525: 	&& ($priv eq 'bre')) {
 6526: 	return 'F';
 6527:     }
 6528: 
 6529: # Free bre access to user's own portfolio contents
 6530:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6531:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6532: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6533:         my %setters;
 6534:         my ($startblock,$endblock) = 
 6535:             &Apache::loncommon::blockcheck(\%setters,'port');
 6536:         if ($startblock && $endblock) {
 6537:             return 'B';
 6538:         } else {
 6539:             return 'F';
 6540:         }
 6541:     }
 6542: 
 6543: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6544:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6545:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6546:         if (exists($env{'request.course.id'})) {
 6547:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6548:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6549:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6550:                 my $courseprivid=$env{'request.course.id'};
 6551:                 $courseprivid=~s/\_/\//;
 6552:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6553:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6554:                     return $1; 
 6555:                 } else {
 6556:                     if ($env{'request.course.sec'}) {
 6557:                         $courseprivid.='/'.$env{'request.course.sec'};
 6558:                     }
 6559:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6560:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6561:                         return $2;
 6562:                     }
 6563:                 }
 6564:             }
 6565:         }
 6566:     }
 6567: 
 6568: # Free bre to public access
 6569: 
 6570:     if ($priv eq 'bre') {
 6571:         my $copyright=&metadata($uri,'copyright');
 6572: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6573:            return 'F'; 
 6574:         }
 6575:         if ($copyright eq 'priv') {
 6576:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6577: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6578: 		return '';
 6579:             }
 6580:         }
 6581:         if ($copyright eq 'domain') {
 6582:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6583: 	    unless (($env{'user.domain'} eq $1) ||
 6584:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6585: 		return '';
 6586:             }
 6587:         }
 6588:         if ($env{'request.role'}=~ /li\.\//) {
 6589:             # Library role, so allow browsing of resources in this domain.
 6590:             return 'F';
 6591:         }
 6592:         if ($copyright eq 'custom') {
 6593: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6594:         }
 6595:     }
 6596:     # Domain coordinator is trying to create a course
 6597:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6598:         # uri is the requested domain in this case.
 6599:         # comparison to 'request.role.domain' shows if the user has selected
 6600:         # a role of dc for the domain in question.
 6601:         return 'F' if ($uri eq $env{'request.role.domain'});
 6602:     }
 6603: 
 6604:     my $thisallowed='';
 6605:     my $statecond=0;
 6606:     my $courseprivid='';
 6607: 
 6608:     my $ownaccess;
 6609:     # Community Coordinator or Assistant Co-author browsing resource space.
 6610:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6611:         if ($uri eq '') {
 6612:             $ownaccess = 1;
 6613:         } else {
 6614:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6615:                 my $udom = $env{'user.domain'};
 6616:                 my $uname = $env{'user.name'};
 6617:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6618:                     $ownaccess = 1;
 6619:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6620:                     unless ($uri =~ m{\.\./}) {
 6621:                         $ownaccess = 1;
 6622:                     }
 6623:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6624:                     my $now = time;
 6625:                     if ($uri =~ m{^([^/]+)/?$}) {
 6626:                         my $adom = $1;
 6627:                         foreach my $key (keys(%env)) {
 6628:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6629:                                 my ($start,$end) = split('.',$env{$key});
 6630:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6631:                                     $ownaccess = 1;
 6632:                                     last;
 6633:                                 }
 6634:                             }
 6635:                         }
 6636:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6637:                         my $adom = $1;
 6638:                         my $aname = $2;
 6639:                         foreach my $role ('ca','aa') { 
 6640:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6641:                                 my ($start,$end) =
 6642:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6643:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6644:                                     $ownaccess = 1;
 6645:                                     last;
 6646:                                 }
 6647:                             }
 6648:                         }
 6649:                     }
 6650:                 }
 6651:             }
 6652:         }
 6653:     }
 6654: 
 6655: # Course
 6656: 
 6657:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6658:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6659:             $thisallowed.=$1;
 6660:         }
 6661:     }
 6662: 
 6663: # Domain
 6664: 
 6665:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6666:        =~/\Q$priv\E\&([^\:]*)/) {
 6667:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6668:             $thisallowed.=$1;
 6669:         }
 6670:     }
 6671: 
 6672: # User who is not author or co-author might still be able to edit
 6673: # resource of an author in the domain (e.g., if Domain Coordinator).
 6674:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6675:         (&allowed('mdc',$env{'request.course.id'}))) {
 6676:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6677:             $thisallowed.=$1;
 6678:         }
 6679:     }
 6680: 
 6681: # Course: uri itself is a course
 6682:     my $courseuri=$uri;
 6683:     $courseuri=~s/\_(\d)/\/$1/;
 6684:     $courseuri=~s/^([^\/])/\/$1/;
 6685: 
 6686:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6687:        =~/\Q$priv\E\&([^\:]*)/) {
 6688:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6689:             $thisallowed.=$1;
 6690:         }
 6691:     }
 6692: 
 6693: # URI is an uploaded document for this course, default permissions don't matter
 6694: # not allowing 'edit' access (editupload) to uploaded course docs
 6695:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6696: 	$thisallowed='';
 6697:         my ($match)=&is_on_map($uri);
 6698:         if ($match) {
 6699:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6700:                   =~/\Q$priv\E\&([^\:]*)/) {
 6701:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6702:                 if (@blockers > 0) {
 6703:                     $thisallowed = 'B';
 6704:                 } else {
 6705:                     $thisallowed.=$1;
 6706:                 }
 6707:             }
 6708:         } else {
 6709:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6710:             if ($refuri) {
 6711:                 if ($refuri =~ m|^/adm/|) {
 6712:                     $thisallowed='F';
 6713:                 } else {
 6714:                     $refuri=&declutter($refuri);
 6715:                     my ($match) = &is_on_map($refuri);
 6716:                     if ($match) {
 6717:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6718:                         if (@blockers > 0) {
 6719:                             $thisallowed = 'B';
 6720:                         } else {
 6721:                             $thisallowed='F';
 6722:                         }
 6723:                     }
 6724:                 }
 6725:             }
 6726:         }
 6727:     }
 6728: 
 6729:     if ($priv eq 'bre'
 6730: 	&& $thisallowed ne 'F' 
 6731: 	&& $thisallowed ne '2'
 6732: 	&& &is_portfolio_url($uri)) {
 6733: 	$thisallowed = &portfolio_access($uri);
 6734:     }
 6735:     
 6736: # Full access at system, domain or course-wide level? Exit.
 6737:     if ($thisallowed=~/F/) {
 6738: 	return 'F';
 6739:     }
 6740: 
 6741: # If this is generating or modifying users, exit with special codes
 6742: 
 6743:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6744: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6745: 	    my ($audom,$auname)=split('/',$uri);
 6746: # no author name given, so this just checks on the general right to make a co-author in this domain
 6747: 	    unless ($auname) { return $thisallowed; }
 6748: # an author name is given, so we are about to actually make a co-author for a certain account
 6749: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6750: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6751: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6752: 	}
 6753: 	return $thisallowed;
 6754:     }
 6755: #
 6756: # Gathered so far: system, domain and course wide privileges
 6757: #
 6758: # Course: See if uri or referer is an individual resource that is part of 
 6759: # the course
 6760: 
 6761:     if ($env{'request.course.id'}) {
 6762: 
 6763:        $courseprivid=$env{'request.course.id'};
 6764:        if ($env{'request.course.sec'}) {
 6765:           $courseprivid.='/'.$env{'request.course.sec'};
 6766:        }
 6767:        $courseprivid=~s/\_/\//;
 6768:        my $checkreferer=1;
 6769:        my ($match,$cond)=&is_on_map($uri);
 6770:        if ($match) {
 6771:            $statecond=$cond;
 6772:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6773:                =~/\Q$priv\E\&([^\:]*)/) {
 6774:                my $value = $1;
 6775:                if ($priv eq 'bre') {
 6776:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6777:                    if (@blockers > 0) {
 6778:                        $thisallowed = 'B';
 6779:                    } else {
 6780:                        $thisallowed.=$value;
 6781:                    }
 6782:                } else {
 6783:                    $thisallowed.=$value;
 6784:                }
 6785:                $checkreferer=0;
 6786:            }
 6787:        }
 6788:        
 6789:        if ($checkreferer) {
 6790: 	  my $refuri=$env{'httpref.'.$orguri};
 6791:             unless ($refuri) {
 6792:                 foreach my $key (keys(%env)) {
 6793: 		    if ($key=~/^httpref\..*\*/) {
 6794: 			my $pattern=$key;
 6795:                         $pattern=~s/^httpref\.\/res\///;
 6796:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6797:                         $pattern=~s/\//\\\//g;
 6798:                         if ($orguri=~/$pattern/) {
 6799: 			    $refuri=$env{$key};
 6800:                         }
 6801:                     }
 6802:                 }
 6803:             }
 6804: 
 6805:          if ($refuri) { 
 6806: 	  $refuri=&declutter($refuri);
 6807:           my ($match,$cond)=&is_on_map($refuri);
 6808:             if ($match) {
 6809:               my $refstatecond=$cond;
 6810:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6811:                   =~/\Q$priv\E\&([^\:]*)/) {
 6812:                   my $value = $1;
 6813:                   if ($priv eq 'bre') {
 6814:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6815:                       if (@blockers > 0) {
 6816:                           $thisallowed = 'B';
 6817:                       } else {
 6818:                           $thisallowed.=$value;
 6819:                       }
 6820:                   } else {
 6821:                       $thisallowed.=$value;
 6822:                   }
 6823:                   $uri=$refuri;
 6824:                   $statecond=$refstatecond;
 6825:               }
 6826:           }
 6827:         }
 6828:        }
 6829:    }
 6830: 
 6831: #
 6832: # Gathered now: all privileges that could apply, and condition number
 6833: # 
 6834: #
 6835: # Full or no access?
 6836: #
 6837: 
 6838:     if ($thisallowed=~/F/) {
 6839: 	return 'F';
 6840:     }
 6841: 
 6842:     unless ($thisallowed) {
 6843:         return '';
 6844:     }
 6845: 
 6846: # Restrictions exist, deal with them
 6847: #
 6848: #   C:according to course preferences
 6849: #   R:according to resource settings
 6850: #   L:unless locked
 6851: #   X:according to user session state
 6852: #
 6853: 
 6854: # Possibly locked functionality, check all courses
 6855: # Locks might take effect only after 10 minutes cache expiration for other
 6856: # courses, and 2 minutes for current course
 6857: 
 6858:     my $envkey;
 6859:     if ($thisallowed=~/L/) {
 6860:         foreach $envkey (keys(%env)) {
 6861:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6862:                my $courseid=$2;
 6863:                my $roleid=$1.'.'.$2;
 6864:                $courseid=~s/^\///;
 6865:                my $expiretime=600;
 6866:                if ($env{'request.role'} eq $roleid) {
 6867: 		  $expiretime=120;
 6868:                }
 6869: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6870:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6871:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6872: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6873:                }
 6874:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6875:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6876: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6877:                        &log($env{'user.domain'},$env{'user.name'},
 6878:                             $env{'user.home'},
 6879:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6880:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6881:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6882: 		       return '';
 6883:                    }
 6884:                }
 6885:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6886:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6887: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6888:                        &log($env{'user.domain'},$env{'user.name'},
 6889:                             $env{'user.home'},
 6890:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6891:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6892:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6893: 		       return '';
 6894:                    }
 6895:                }
 6896: 	   }
 6897:        }
 6898:     }
 6899:    
 6900: #
 6901: # Rest of the restrictions depend on selected course
 6902: #
 6903: 
 6904:     unless ($env{'request.course.id'}) {
 6905: 	if ($thisallowed eq 'A') {
 6906: 	    return 'A';
 6907:         } elsif ($thisallowed eq 'B') {
 6908:             return 'B';
 6909: 	} else {
 6910: 	    return '1';
 6911: 	}
 6912:     }
 6913: 
 6914: #
 6915: # Now user is definitely in a course
 6916: #
 6917: 
 6918: 
 6919: # Course preferences
 6920: 
 6921:    if ($thisallowed=~/C/) {
 6922:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6923:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6924:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6925: 	   =~/\Q$rolecode\E/) {
 6926: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6927: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6928: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6929: 			$env{'request.course.id'});
 6930: 	   }
 6931:            return '';
 6932:        }
 6933: 
 6934:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6935: 	   =~/\Q$unamedom\E/) {
 6936: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6937: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6938: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6939: 			$env{'request.course.id'});
 6940: 	   }
 6941:            return '';
 6942:        }
 6943:    }
 6944: 
 6945: # Resource preferences
 6946: 
 6947:    if ($thisallowed=~/R/) {
 6948:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6949:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6950: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6951: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6952: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6953: 	   }
 6954: 	   return '';
 6955:        }
 6956:    }
 6957: 
 6958: # Restricted by state or randomout?
 6959: 
 6960:    if ($thisallowed=~/X/) {
 6961:       if ($env{'acc.randomout'}) {
 6962: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6963:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6964:             return ''; 
 6965:          }
 6966:       }
 6967:       if (&condval($statecond)) {
 6968: 	 return '2';
 6969:       } else {
 6970:          return '';
 6971:       }
 6972:    }
 6973: 
 6974:     if ($thisallowed eq 'A') {
 6975: 	return 'A';
 6976:     } elsif ($thisallowed eq 'B') {
 6977:         return 'B';
 6978:     }
 6979:    return 'F';
 6980: }
 6981: 
 6982: # ------------------------------------------- Check construction space access
 6983: 
 6984: sub constructaccess {
 6985:     my ($url,$setpriv)=@_;
 6986: 
 6987: # We do not allow editing of previous versions of files
 6988:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6989: 
 6990: # Get username and domain from URL
 6991:     my ($ownername,$ownerdomain,$ownerhome);
 6992: 
 6993:     ($ownerdomain,$ownername) =
 6994:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6995: 
 6996: # The URL does not really point to any authorspace, forget it
 6997:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6998: 
 6999: # Now we need to see if the user has access to the authorspace of
 7000: # $ownername at $ownerdomain
 7001: 
 7002:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7003: # Real author for this?
 7004:        $ownerhome = $env{'user.home'};
 7005:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7006:           return ($ownername,$ownerdomain,$ownerhome);
 7007:        }
 7008:     } else {
 7009: # Co-author for this?
 7010:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7011:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7012:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7013:             return ($ownername,$ownerdomain,$ownerhome);
 7014:         }
 7015:     }
 7016: 
 7017: # We don't have any access right now. If we are not possibly going to do anything about this,
 7018: # we might as well leave
 7019:    unless ($setpriv) { return ''; }
 7020: 
 7021: # Backdoor access?
 7022:     my $allowed=&allowed('eco',$ownerdomain);
 7023: # Nope
 7024:     unless ($allowed) { return ''; }
 7025: # Looks like we may have access, but could be locked by the owner of the construction space
 7026:     if ($allowed eq 'U') {
 7027:         my %blocked=&get('environment',['domcoord.author'],
 7028:                          $ownerdomain,$ownername);
 7029: # Is blocked by owner
 7030:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7031:     }
 7032:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7033: # Grant temporary access
 7034:         my $then=$env{'user.login.time'};
 7035:         my $update=$env{'user.update.time'};
 7036:         if (!$update) { $update = $then; }
 7037:         my $refresh=$env{'user.refresh.time'};
 7038:         if (!$refresh) { $refresh = $update; }
 7039:         my $now = time;
 7040:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7041:                            $now,'ca','constructaccess');
 7042:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7043:         return($ownername,$ownerdomain,$ownerhome);
 7044:     }
 7045: # No business here
 7046:     return '';
 7047: }
 7048: 
 7049: sub get_comm_blocks {
 7050:     my ($cdom,$cnum) = @_;
 7051:     if ($cdom eq '' || $cnum eq '') {
 7052:         return unless ($env{'request.course.id'});
 7053:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7054:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7055:     }
 7056:     my %commblocks;
 7057:     my $hashid=$cdom.'_'.$cnum;
 7058:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7059:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7060:         %commblocks = %{$blocksref};
 7061:     } else {
 7062:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7063:         my $cachetime = 600;
 7064:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7065:     }
 7066:     return %commblocks;
 7067: }
 7068: 
 7069: sub has_comm_blocking {
 7070:     my ($priv,$symb,$uri,$blocks) = @_;
 7071:     return unless ($env{'request.course.id'});
 7072:     return unless ($priv eq 'bre');
 7073:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7074:     my %commblocks;
 7075:     if (ref($blocks) eq 'HASH') {
 7076:         %commblocks = %{$blocks};
 7077:     } else {
 7078:         %commblocks = &get_comm_blocks();
 7079:     }
 7080:     return unless (keys(%commblocks) > 0);
 7081:     if (!$symb) { $symb=&symbread($uri,1); }
 7082:     my ($map,$resid,undef)=&decode_symb($symb);
 7083:     my %tocheck = (
 7084:                     maps      => $map,
 7085:                     resources => $symb,
 7086:                   );
 7087:     my @blockers;
 7088:     my $now = time;
 7089:     my $navmap = Apache::lonnavmaps::navmap->new();
 7090:     foreach my $block (keys(%commblocks)) {
 7091:         if ($block =~ /^(\d+)____(\d+)$/) {
 7092:             my ($start,$end) = ($1,$2);
 7093:             if ($start <= $now && $end >= $now) {
 7094:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7095:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7096:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7097:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7098:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7099:                                     push(@blockers,$block);
 7100:                                 }
 7101:                             }
 7102:                         }
 7103:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7104:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7105:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7106:                                     push(@blockers,$block);
 7107:                                 }
 7108:                             }
 7109:                         }
 7110:                     }
 7111:                 }
 7112:             }
 7113:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7114:             my $item = $1;
 7115:             my @to_test;
 7116:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7117:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7118:                     my $check_interval;
 7119:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7120:                         my @interval;
 7121:                         my $type = 'map';
 7122:                         if ($item eq 'course') {
 7123:                             $type = 'course';
 7124:                             @interval=&EXT("resource.0.interval");
 7125:                         } else {
 7126:                             if ($item =~ /___\d+___/) {
 7127:                                 $type = 'resource';
 7128:                                 @interval=&EXT("resource.0.interval",$item);
 7129:                                 if (ref($navmap)) {                        
 7130:                                     my $res = $navmap->getBySymb($item); 
 7131:                                     push(@to_test,$res);
 7132:                                 }
 7133:                             } else {
 7134:                                 my $mapsymb = &symbread($item,1);
 7135:                                 if ($mapsymb) {
 7136:                                     if (ref($navmap)) {
 7137:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7138:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7139:                                         foreach my $res (@to_test) {
 7140:                                             my $symb = $res->symb();
 7141:                                             next if ($symb eq $mapsymb);
 7142:                                             if ($symb ne '') {
 7143:                                                 @interval=&EXT("resource.0.interval",$symb);
 7144:                                                 last;
 7145:                                             }
 7146:                                         }
 7147:                                     }
 7148:                                 }
 7149:                             }
 7150:                         }
 7151:                         if ($interval[0] =~ /\d+/) {
 7152:                             my $first_access;
 7153:                             if ($type eq 'resource') {
 7154:                                 $first_access=&get_first_access($interval[1],$item);
 7155:                             } elsif ($type eq 'map') {
 7156:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7157:                             } else {
 7158:                                 $first_access=&get_first_access($interval[1]);
 7159:                             }
 7160:                             if ($first_access) {
 7161:                                 my $timesup = $first_access+$interval[0];
 7162:                                 if ($timesup > $now) {
 7163:                                     foreach my $res (@to_test) {
 7164:                                         if ($res->is_problem()) {
 7165:                                             if ($res->completable()) {
 7166:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7167:                                                     push(@blockers,$block);
 7168:                                                 }
 7169:                                                 last;
 7170:                                             }
 7171:                                         }
 7172:                                     }
 7173:                                 }
 7174:                             }
 7175:                         }
 7176:                     }
 7177:                 }
 7178:             }
 7179:         }
 7180:     }
 7181:     return @blockers;
 7182: }
 7183: 
 7184: sub check_docs_block {
 7185:     my ($docsblock,$tocheck) =@_;
 7186:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7187:         return;
 7188:     }
 7189:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7190:         if ($tocheck->{'maps'}) {
 7191:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7192:                 return 1;
 7193:             }
 7194:         }
 7195:     }
 7196:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7197:         if ($tocheck->{'resources'}) {
 7198:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7199:                 return 1;
 7200:             }
 7201:         }
 7202:     }
 7203:     return;
 7204: }
 7205: 
 7206: #
 7207: #   Removes the versino from a URI and
 7208: #   splits it in to its filename and path to the filename.
 7209: #   Seems like File::Basename could have done this more clearly.
 7210: #   Parameters:
 7211: #      $uri   - input URI
 7212: #   Returns:
 7213: #     Two element list consisting of 
 7214: #     $pathname  - the URI up to and excluding the trailing /
 7215: #     $filename  - The part of the URI following the last /
 7216: #  NOTE:
 7217: #    Another realization of this is simply:
 7218: #    use File::Basename;
 7219: #    ...
 7220: #    $uri = shift;
 7221: #    $filename = basename($uri);
 7222: #    $path     = dirname($uri);
 7223: #    return ($filename, $path);
 7224: #
 7225: #     The implementation below is probably faster however.
 7226: #
 7227: sub split_uri_for_cond {
 7228:     my $uri=&deversion(&declutter(shift));
 7229:     my @uriparts=split(/\//,$uri);
 7230:     my $filename=pop(@uriparts);
 7231:     my $pathname=join('/',@uriparts);
 7232:     return ($pathname,$filename);
 7233: }
 7234: # --------------------------------------------------- Is a resource on the map?
 7235: 
 7236: sub is_on_map {
 7237:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7238:     #Trying to find the conditional for the file
 7239:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7240: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7241:     if ($match) {
 7242: 	return (1,$1);
 7243:     } else {
 7244: 	return (0,0);
 7245:     }
 7246: }
 7247: 
 7248: # --------------------------------------------------------- Get symb from alias
 7249: 
 7250: sub get_symb_from_alias {
 7251:     my $symb=shift;
 7252:     my ($map,$resid,$url)=&decode_symb($symb);
 7253: # Already is a symb
 7254:     if ($url) { return $symb; }
 7255: # Must be an alias
 7256:     my $aliassymb='';
 7257:     my %bighash;
 7258:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7259:                             &GDBM_READER(),0640)) {
 7260:         my $rid=$bighash{'mapalias_'.$symb};
 7261: 	if ($rid) {
 7262: 	    my ($mapid,$resid)=split(/\./,$rid);
 7263: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7264: 				    $resid,$bighash{'src_'.$rid});
 7265: 	}
 7266:         untie %bighash;
 7267:     }
 7268:     return $aliassymb;
 7269: }
 7270: 
 7271: # ----------------------------------------------------------------- Define Role
 7272: 
 7273: sub definerole {
 7274:   if (allowed('mcr','/')) {
 7275:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7276:     foreach my $role (split(':',$sysrole)) {
 7277: 	my ($crole,$cqual)=split(/\&/,$role);
 7278:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7279:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7280: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7281:                return "refused:s:$crole&$cqual"; 
 7282:             }
 7283:         }
 7284:     }
 7285:     foreach my $role (split(':',$domrole)) {
 7286: 	my ($crole,$cqual)=split(/\&/,$role);
 7287:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7288:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7289: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7290:                return "refused:d:$crole&$cqual"; 
 7291:             }
 7292:         }
 7293:     }
 7294:     foreach my $role (split(':',$courole)) {
 7295: 	my ($crole,$cqual)=split(/\&/,$role);
 7296:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7297:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7298: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7299:                return "refused:c:$crole&$cqual"; 
 7300:             }
 7301:         }
 7302:     }
 7303:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7304:                 "$env{'user.domain'}:$env{'user.name'}:".
 7305: 	        "rolesdef_$rolename=".
 7306:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7307:     return reply($command,$env{'user.home'});
 7308:   } else {
 7309:     return 'refused';
 7310:   }
 7311: }
 7312: 
 7313: # ---------------- Make a metadata query against the network of library servers
 7314: 
 7315: sub metadata_query {
 7316:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7317:     my %rhash;
 7318:     my %libserv = &all_library();
 7319:     my @server_list = (defined($server_array) ? @$server_array
 7320:                                               : keys(%libserv) );
 7321:     for my $server (@server_list) {
 7322:         my $domains = ''; 
 7323:         if (ref($domains_hash) eq 'HASH') {
 7324:             $domains = $domains_hash->{$server}; 
 7325:         }
 7326: 	unless ($custom or $customshow) {
 7327: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7328: 	    $rhash{$server}=$reply;
 7329: 	}
 7330: 	else {
 7331: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7332: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7333: 			     $server);
 7334: 	    $rhash{$server}=$reply;
 7335: 	}
 7336:     }
 7337:     return \%rhash;
 7338: }
 7339: 
 7340: # ----------------------------------------- Send log queries and wait for reply
 7341: 
 7342: sub log_query {
 7343:     my ($uname,$udom,$query,%filters)=@_;
 7344:     my $uhome=&homeserver($uname,$udom);
 7345:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7346:     my $uhost=&hostname($uhome);
 7347:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7348:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7349:                        $uhome);
 7350:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7351:     return get_query_reply($queryid);
 7352: }
 7353: 
 7354: # -------------------------- Update MySQL table for portfolio file
 7355: 
 7356: sub update_portfolio_table {
 7357:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7358:     if ($group ne '') {
 7359:         $file_name =~s /^\Q$group\E//;
 7360:     }
 7361:     my $homeserver = &homeserver($uname,$udom);
 7362:     my $queryid=
 7363:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7364:                ':'.&escape($file_name).':'.$action,$homeserver);
 7365:     my $reply = &get_query_reply($queryid);
 7366:     return $reply;
 7367: }
 7368: 
 7369: # -------------------------- Update MySQL allusers table
 7370: 
 7371: sub update_allusers_table {
 7372:     my ($uname,$udom,$names) = @_;
 7373:     my $homeserver = &homeserver($uname,$udom);
 7374:     my $queryid=
 7375:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7376:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7377:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7378:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7379:                'generation='.&escape($names->{'generation'}).'%%'.
 7380:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7381:                'id='.&escape($names->{'id'}),$homeserver);
 7382:     return;
 7383: }
 7384: 
 7385: # ------- Request retrieval of institutional classlists for course(s)
 7386: 
 7387: sub fetch_enrollment_query {
 7388:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7389:     my $homeserver;
 7390:     my $maxtries = 1;
 7391:     if ($context eq 'automated') {
 7392:         $homeserver = $perlvar{'lonHostID'};
 7393:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7394:     } else {
 7395:         $homeserver = &homeserver($cnum,$dom);
 7396:     }
 7397:     my $host=&hostname($homeserver);
 7398:     my $cmd = '';
 7399:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7400:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7401:     }
 7402:     $cmd =~ s/%%$//;
 7403:     $cmd = &escape($cmd);
 7404:     my $query = 'fetchenrollment';
 7405:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7406:     unless ($queryid=~/^\Q$host\E\_/) { 
 7407:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7408:         return 'error: '.$queryid;
 7409:     }
 7410:     my $reply = &get_query_reply($queryid);
 7411:     my $tries = 1;
 7412:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7413:         $reply = &get_query_reply($queryid);
 7414:         $tries ++;
 7415:     }
 7416:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7417:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7418:     } else {
 7419:         my @responses = split(/:/,$reply);
 7420:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7421:             foreach my $line (@responses) {
 7422:                 my ($key,$value) = split(/=/,$line,2);
 7423:                 $$replyref{$key} = $value;
 7424:             }
 7425:         } else {
 7426:             my $pathname = LONCAPA::tempdir();
 7427:             foreach my $line (@responses) {
 7428:                 my ($key,$value) = split(/=/,$line);
 7429:                 $$replyref{$key} = $value;
 7430:                 if ($value > 0) {
 7431:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7432:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7433:                         my $destname = $pathname.'/'.$filename;
 7434:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7435:                         if ($xml_classlist =~ /^error/) {
 7436:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7437:                         } else {
 7438:                             if ( open(FILE,">$destname") ) {
 7439:                                 print FILE &unescape($xml_classlist);
 7440:                                 close(FILE);
 7441:                             } else {
 7442:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7443:                             }
 7444:                         }
 7445:                     }
 7446:                 }
 7447:             }
 7448:         }
 7449:         return 'ok';
 7450:     }
 7451:     return 'error';
 7452: }
 7453: 
 7454: sub get_query_reply {
 7455:     my $queryid=shift;
 7456:     my $replyfile=LONCAPA::tempdir().$queryid;
 7457:     my $reply='';
 7458:     for (1..100) {
 7459: 	sleep 2;
 7460:         if (-e $replyfile.'.end') {
 7461: 	    if (open(my $fh,$replyfile)) {
 7462: 		$reply = join('',<$fh>);
 7463: 		close($fh);
 7464: 	   } else { return 'error: reply_file_error'; }
 7465:            return &unescape($reply);
 7466: 	}
 7467:     }
 7468:     return 'timeout:'.$queryid;
 7469: }
 7470: 
 7471: sub courselog_query {
 7472: #
 7473: # possible filters:
 7474: # url: url or symb
 7475: # username
 7476: # domain
 7477: # action: view, submit, grade
 7478: # start: timestamp
 7479: # end: timestamp
 7480: #
 7481:     my (%filters)=@_;
 7482:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7483:     if ($filters{'url'}) {
 7484: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7485:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7486:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7487:     }
 7488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7490:     return &log_query($cname,$cdom,'courselog',%filters);
 7491: }
 7492: 
 7493: sub userlog_query {
 7494: #
 7495: # possible filters:
 7496: # action: log check role
 7497: # start: timestamp
 7498: # end: timestamp
 7499: #
 7500:     my ($uname,$udom,%filters)=@_;
 7501:     return &log_query($uname,$udom,'userlog',%filters);
 7502: }
 7503: 
 7504: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7505: 
 7506: sub auto_run {
 7507:     my ($cnum,$cdom) = @_;
 7508:     my $response = 0;
 7509:     my $settings;
 7510:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7511:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7512:         $settings = $domconfig{'autoenroll'};
 7513:         if ($settings->{'run'} eq '1') {
 7514:             $response = 1;
 7515:         }
 7516:     } else {
 7517:         my $homeserver;
 7518:         if (&is_course($cdom,$cnum)) {
 7519:             $homeserver = &homeserver($cnum,$cdom);
 7520:         } else {
 7521:             $homeserver = &domain($cdom,'primary');
 7522:         }
 7523:         if ($homeserver ne 'no_host') {
 7524:             $response = &reply('autorun:'.$cdom,$homeserver);
 7525:         }
 7526:     }
 7527:     return $response;
 7528: }
 7529: 
 7530: sub auto_get_sections {
 7531:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7532:     my $homeserver;
 7533:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7534:         $homeserver = &homeserver($cnum,$cdom);
 7535:     }
 7536:     if (!defined($homeserver)) { 
 7537:         if ($cdom =~ /^$match_domain$/) {
 7538:             $homeserver = &domain($cdom,'primary');
 7539:         }
 7540:     }
 7541:     my @secs;
 7542:     if (defined($homeserver)) {
 7543:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7544:         unless ($response eq 'refused') {
 7545:             @secs = split(/:/,$response);
 7546:         }
 7547:     }
 7548:     return @secs;
 7549: }
 7550: 
 7551: sub auto_new_course {
 7552:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7553:     my $homeserver = &homeserver($cnum,$cdom);
 7554:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7555:     return $response;
 7556: }
 7557: 
 7558: sub auto_validate_courseID {
 7559:     my ($cnum,$cdom,$inst_course_id) = @_;
 7560:     my $homeserver = &homeserver($cnum,$cdom);
 7561:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7562:     return $response;
 7563: }
 7564: 
 7565: sub auto_validate_instcode {
 7566:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7567:     my ($homeserver,$response);
 7568:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7569:         $homeserver = &homeserver($cnum,$cdom);
 7570:     }
 7571:     if (!defined($homeserver)) {
 7572:         if ($cdom =~ /^$match_domain$/) {
 7573:             $homeserver = &domain($cdom,'primary');
 7574:         }
 7575:     }
 7576:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7577:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7578:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7579:     return ($outcome,$description,$defaultcredits);
 7580: }
 7581: 
 7582: sub auto_create_password {
 7583:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7584:     my ($homeserver,$response);
 7585:     my $create_passwd = 0;
 7586:     my $authchk = '';
 7587:     if ($udom =~ /^$match_domain$/) {
 7588:         $homeserver = &domain($udom,'primary');
 7589:     }
 7590:     if ($homeserver eq '') {
 7591:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7592:             $homeserver = &homeserver($cnum,$cdom);
 7593:         }
 7594:     }
 7595:     if ($homeserver eq '') {
 7596:         $authchk = 'nodomain';
 7597:     } else {
 7598:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7599:         if ($response eq 'refused') {
 7600:             $authchk = 'refused';
 7601:         } else {
 7602:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7603:         }
 7604:     }
 7605:     return ($authparam,$create_passwd,$authchk);
 7606: }
 7607: 
 7608: sub auto_photo_permission {
 7609:     my ($cnum,$cdom,$students) = @_;
 7610:     my $homeserver = &homeserver($cnum,$cdom);
 7611:     my ($outcome,$perm_reqd,$conditions) = 
 7612: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7613:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7614: 	return (undef,undef);
 7615:     }
 7616:     return ($outcome,$perm_reqd,$conditions);
 7617: }
 7618: 
 7619: sub auto_checkphotos {
 7620:     my ($uname,$udom,$pid) = @_;
 7621:     my $homeserver = &homeserver($uname,$udom);
 7622:     my ($result,$resulttype);
 7623:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7624: 				   &escape($uname).':'.&escape($pid),
 7625: 				   $homeserver));
 7626:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7627: 	return (undef,undef);
 7628:     }
 7629:     if ($outcome) {
 7630:         ($result,$resulttype) = split(/:/,$outcome);
 7631:     } 
 7632:     return ($result,$resulttype);
 7633: }
 7634: 
 7635: sub auto_photochoice {
 7636:     my ($cnum,$cdom) = @_;
 7637:     my $homeserver = &homeserver($cnum,$cdom);
 7638:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7639: 						       &escape($cdom),
 7640: 						       $homeserver)));
 7641:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7642: 	return (undef,undef);
 7643:     }
 7644:     return ($update,$comment);
 7645: }
 7646: 
 7647: sub auto_photoupdate {
 7648:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7649:     my $homeserver = &homeserver($cnum,$dom);
 7650:     my $host=&hostname($homeserver);
 7651:     my $cmd = '';
 7652:     my $maxtries = 1;
 7653:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7654:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7655:     }
 7656:     $cmd =~ s/%%$//;
 7657:     $cmd = &escape($cmd);
 7658:     my $query = 'institutionalphotos';
 7659:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7660:     unless ($queryid=~/^\Q$host\E\_/) {
 7661:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7662:         return 'error: '.$queryid;
 7663:     }
 7664:     my $reply = &get_query_reply($queryid);
 7665:     my $tries = 1;
 7666:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7667:         $reply = &get_query_reply($queryid);
 7668:         $tries ++;
 7669:     }
 7670:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7671:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7672:     } else {
 7673:         my @responses = split(/:/,$reply);
 7674:         my $outcome = shift(@responses); 
 7675:         foreach my $item (@responses) {
 7676:             my ($key,$value) = split(/=/,$item);
 7677:             $$photo{$key} = $value;
 7678:         }
 7679:         return $outcome;
 7680:     }
 7681:     return 'error';
 7682: }
 7683: 
 7684: sub auto_instcode_format {
 7685:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7686: 	$cat_order) = @_;
 7687:     my $courses = '';
 7688:     my @homeservers;
 7689:     if ($caller eq 'global') {
 7690: 	my %servers = &get_servers($codedom,'library');
 7691: 	foreach my $tryserver (keys(%servers)) {
 7692: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7693: 		push(@homeservers,$tryserver);
 7694: 	    }
 7695:         }
 7696:     } elsif ($caller eq 'requests') {
 7697:         if ($codedom =~ /^$match_domain$/) {
 7698:             my $chome = &domain($codedom,'primary');
 7699:             unless ($chome eq 'no_host') {
 7700:                 push(@homeservers,$chome);
 7701:             }
 7702:         }
 7703:     } else {
 7704:         push(@homeservers,&homeserver($caller,$codedom));
 7705:     }
 7706:     foreach my $code (keys(%{$instcodes})) {
 7707:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7708:     }
 7709:     chop($courses);
 7710:     my $ok_response = 0;
 7711:     my $response;
 7712:     while (@homeservers > 0 && $ok_response == 0) {
 7713:         my $server = shift(@homeservers); 
 7714:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7715:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7716:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7717: 		split(/:/,$response);
 7718:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7719:             push(@{$codetitles},&str2array($codetitles_str));
 7720:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7721:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7722:             $ok_response = 1;
 7723:         }
 7724:     }
 7725:     if ($ok_response) {
 7726:         return 'ok';
 7727:     } else {
 7728:         return $response;
 7729:     }
 7730: }
 7731: 
 7732: sub auto_instcode_defaults {
 7733:     my ($domain,$returnhash,$code_order) = @_;
 7734:     my @homeservers;
 7735: 
 7736:     my %servers = &get_servers($domain,'library');
 7737:     foreach my $tryserver (keys(%servers)) {
 7738: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7739: 	    push(@homeservers,$tryserver);
 7740: 	}
 7741:     }
 7742: 
 7743:     my $response;
 7744:     foreach my $server (@homeservers) {
 7745:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7746:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7747: 	
 7748: 	foreach my $pair (split(/\&/,$response)) {
 7749: 	    my ($name,$value)=split(/\=/,$pair);
 7750: 	    if ($name eq 'code_order') {
 7751: 		@{$code_order} = split(/\&/,&unescape($value));
 7752: 	    } else {
 7753: 		$returnhash->{&unescape($name)}=&unescape($value);
 7754: 	    }
 7755: 	}
 7756: 	return 'ok';
 7757:     }
 7758: 
 7759:     return $response;
 7760: }
 7761: 
 7762: sub auto_possible_instcodes {
 7763:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7764:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7765:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7766:         return;
 7767:     }
 7768:     my (@homeservers,$uhome);
 7769:     if (defined(&domain($domain,'primary'))) {
 7770:         $uhome=&domain($domain,'primary');
 7771:         push(@homeservers,&domain($domain,'primary'));
 7772:     } else {
 7773:         my %servers = &get_servers($domain,'library');
 7774:         foreach my $tryserver (keys(%servers)) {
 7775:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7776:                 push(@homeservers,$tryserver);
 7777:             }
 7778:         }
 7779:     }
 7780:     my $response;
 7781:     foreach my $server (@homeservers) {
 7782:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7783:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7784:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7785:             split(':',$response);
 7786:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7787:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7788:         foreach my $item (split('&',$cat_title)) {   
 7789:             my ($name,$value)=split('=',$item);
 7790:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7791:         }
 7792:         foreach my $item (split('&',$cat_order)) {
 7793:             my ($name,$value)=split('=',$item);
 7794:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7795:         }
 7796:         return 'ok';
 7797:     }
 7798:     return $response;
 7799: }
 7800: 
 7801: sub auto_courserequest_checks {
 7802:     my ($dom) = @_;
 7803:     my ($homeserver,%validations);
 7804:     if ($dom =~ /^$match_domain$/) {
 7805:         $homeserver = &domain($dom,'primary');
 7806:     }
 7807:     unless ($homeserver eq 'no_host') {
 7808:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7809:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7810:             my @items = split(/&/,$response);
 7811:             foreach my $item (@items) {
 7812:                 my ($key,$value) = split('=',$item);
 7813:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7814:             }
 7815:         }
 7816:     }
 7817:     return %validations; 
 7818: }
 7819: 
 7820: sub auto_courserequest_validation {
 7821:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7822:     my ($homeserver,$response);
 7823:     if ($dom =~ /^$match_domain$/) {
 7824:         $homeserver = &domain($dom,'primary');
 7825:     }
 7826:     unless ($homeserver eq 'no_host') {  
 7827:           
 7828:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7829:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7830:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7831:                                     $homeserver));
 7832:     }
 7833:     return $response;
 7834: }
 7835: 
 7836: sub auto_validate_class_sec {
 7837:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7838:     my $homeserver = &homeserver($cnum,$cdom);
 7839:     my $ownerlist;
 7840:     if (ref($owners) eq 'ARRAY') {
 7841:         $ownerlist = join(',',@{$owners});
 7842:     } else {
 7843:         $ownerlist = $owners;
 7844:     }
 7845:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7846:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7847:     return $response;
 7848: }
 7849: 
 7850: # ------------------------------------------------------- Course Group routines
 7851: 
 7852: sub get_coursegroups {
 7853:     my ($cdom,$cnum,$group,$namespace) = @_;
 7854:     return(&dump($namespace,$cdom,$cnum,$group));
 7855: }
 7856: 
 7857: sub modify_coursegroup {
 7858:     my ($cdom,$cnum,$groupsettings) = @_;
 7859:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7860: }
 7861: 
 7862: sub toggle_coursegroup_status {
 7863:     my ($cdom,$cnum,$group,$action) = @_;
 7864:     my ($from_namespace,$to_namespace);
 7865:     if ($action eq 'delete') {
 7866:         $from_namespace = 'coursegroups';
 7867:         $to_namespace = 'deleted_groups';
 7868:     } else {
 7869:         $from_namespace = 'deleted_groups';
 7870:         $to_namespace = 'coursegroups';
 7871:     }
 7872:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7873:     if (my $tmp = &error(%curr_group)) {
 7874:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7875:         return ('read error',$tmp);
 7876:     } else {
 7877:         my %savedsettings = %curr_group; 
 7878:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7879:         my $deloutcome;
 7880:         if ($result eq 'ok') {
 7881:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7882:         } else {
 7883:             return ('write error',$result);
 7884:         }
 7885:         if ($deloutcome eq 'ok') {
 7886:             return 'ok';
 7887:         } else {
 7888:             return ('delete error',$deloutcome);
 7889:         }
 7890:     }
 7891: }
 7892: 
 7893: sub modify_group_roles {
 7894:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7895:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7896:     my $role = 'gr/'.&escape($userprivs);
 7897:     my ($uname,$udom) = split(/:/,$user);
 7898:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7899:     if ($result eq 'ok') {
 7900:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7901:     }
 7902:     return $result;
 7903: }
 7904: 
 7905: sub modify_coursegroup_membership {
 7906:     my ($cdom,$cnum,$membership) = @_;
 7907:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7908:     return $result;
 7909: }
 7910: 
 7911: sub get_active_groups {
 7912:     my ($udom,$uname,$cdom,$cnum) = @_;
 7913:     my $now = time;
 7914:     my %groups = ();
 7915:     foreach my $key (keys(%env)) {
 7916:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7917:             my ($start,$end) = split(/\./,$env{$key});
 7918:             if (($end!=0) && ($end<$now)) { next; }
 7919:             if (($start!=0) && ($start>$now)) { next; }
 7920:             if ($1 eq $cdom && $2 eq $cnum) {
 7921:                 $groups{$3} = $env{$key} ;
 7922:             }
 7923:         }
 7924:     }
 7925:     return %groups;
 7926: }
 7927: 
 7928: sub get_group_membership {
 7929:     my ($cdom,$cnum,$group) = @_;
 7930:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7931: }
 7932: 
 7933: sub get_users_groups {
 7934:     my ($udom,$uname,$courseid) = @_;
 7935:     my @usersgroups;
 7936:     my $cachetime=1800;
 7937: 
 7938:     my $hashid="$udom:$uname:$courseid";
 7939:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7940:     if (defined($cached)) {
 7941:         @usersgroups = split(/:/,$grouplist);
 7942:     } else {  
 7943:         $grouplist = '';
 7944:         my $courseurl = &courseid_to_courseurl($courseid);
 7945:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7946:         my $access_end = $env{'course.'.$courseid.
 7947:                               '.default_enrollment_end_date'};
 7948:         my $now = time;
 7949:         foreach my $key (keys(%roleshash)) {
 7950:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7951:                 my $group = $1;
 7952:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7953:                     my $start = $2;
 7954:                     my $end = $1;
 7955:                     if ($start == -1) { next; } # deleted from group
 7956:                     if (($start!=0) && ($start>$now)) { next; }
 7957:                     if (($end!=0) && ($end<$now)) {
 7958:                         if ($access_end && $access_end < $now) {
 7959:                             if ($access_end - $end < 86400) {
 7960:                                 push(@usersgroups,$group);
 7961:                             }
 7962:                         }
 7963:                         next;
 7964:                     }
 7965:                     push(@usersgroups,$group);
 7966:                 }
 7967:             }
 7968:         }
 7969:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7970:         $grouplist = join(':',@usersgroups);
 7971:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7972:     }
 7973:     return @usersgroups;
 7974: }
 7975: 
 7976: sub devalidate_getgroups_cache {
 7977:     my ($udom,$uname,$cdom,$cnum)=@_;
 7978:     my $courseid = $cdom.'_'.$cnum;
 7979: 
 7980:     my $hashid="$udom:$uname:$courseid";
 7981:     &devalidate_cache_new('getgroups',$hashid);
 7982: }
 7983: 
 7984: # ------------------------------------------------------------------ Plain Text
 7985: 
 7986: sub plaintext {
 7987:     my ($short,$type,$cid,$forcedefault) = @_;
 7988:     if ($short =~ m{^cr/}) {
 7989: 	return (split('/',$short))[-1];
 7990:     }
 7991:     if (!defined($cid)) {
 7992:         $cid = $env{'request.course.id'};
 7993:     }
 7994:     my %rolenames = (
 7995:                       Course    => 'std',
 7996:                       Community => 'alt1',
 7997:                     );
 7998:     if ($cid ne '') {
 7999:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8000:             unless ($forcedefault) {
 8001:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8002:                 &Apache::lonlocal::mt_escape(\$roletext);
 8003:                 return &Apache::lonlocal::mt($roletext);
 8004:             }
 8005:         }
 8006:     }
 8007:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8008:         (defined($rolenames{$type})) && 
 8009:         (defined($prp{$short}{$rolenames{$type}}))) {
 8010:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8011:     } elsif ($cid ne '') {
 8012:         my $crstype = $env{'course.'.$cid.'.type'};
 8013:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8014:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8015:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8016:         }
 8017:     }
 8018:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8019: }
 8020: 
 8021: # ----------------------------------------------------------------- Assign Role
 8022: 
 8023: sub assignrole {
 8024:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8025:         $context)=@_;
 8026:     my $mrole;
 8027:     if ($role =~ /^cr\//) {
 8028:         my $cwosec=$url;
 8029:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8030: 	unless (&allowed('ccr',$cwosec)) {
 8031:            my $refused = 1;
 8032:            if ($context eq 'requestcourses') {
 8033:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8034:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8035:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8036:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8037:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8038:                            if ($crsenv{'internal.courseowner'} eq
 8039:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8040:                                $refused = '';
 8041:                            }
 8042:                        }
 8043:                    }
 8044:                }
 8045:            }
 8046:            if ($refused) {
 8047:                &logthis('Refused custom assignrole: '.
 8048:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8049:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8050:                return 'refused';
 8051:            }
 8052:         }
 8053:         $mrole='cr';
 8054:     } elsif ($role =~ /^gr\//) {
 8055:         my $cwogrp=$url;
 8056:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8057:         unless (&allowed('mdg',$cwogrp)) {
 8058:             &logthis('Refused group assignrole: '.
 8059:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8060:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8061:             return 'refused';
 8062:         }
 8063:         $mrole='gr';
 8064:     } else {
 8065:         my $cwosec=$url;
 8066:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8067:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8068:             my $refused;
 8069:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8070:                 if (!(&allowed('c'.$role,$url))) {
 8071:                     $refused = 1;
 8072:                 }
 8073:             } else {
 8074:                 $refused = 1;
 8075:             }
 8076:             if ($refused) {
 8077:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8078:                 if (!$selfenroll && $context eq 'course') {
 8079:                     my %crsenv;
 8080:                     if ($role eq 'cc' || $role eq 'co') {
 8081:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8082:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8083:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8084:                                 if ($crsenv{'internal.courseowner'} eq 
 8085:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8086:                                     $refused = '';
 8087:                                 }
 8088:                             }
 8089:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8090:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8091:                                 if ($crsenv{'internal.courseowner'} eq 
 8092:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8093:                                     $refused = '';
 8094:                                 }
 8095:                             }
 8096:                         }
 8097:                     }
 8098:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8099:                     $refused = '';
 8100:                 } elsif ($context eq 'requestcourses') {
 8101:                     my @possroles = ('st','ta','ep','in','cc','co');
 8102:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8103:                         my $wrongcc;
 8104:                         if ($cnum =~ /^$match_community$/) {
 8105:                             $wrongcc = 1 if ($role eq 'cc');
 8106:                         } else {
 8107:                             $wrongcc = 1 if ($role eq 'co');
 8108:                         }
 8109:                         unless ($wrongcc) {
 8110:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8111:                             if ($crsenv{'internal.courseowner'} eq 
 8112:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8113:                                 $refused = '';
 8114:                             }
 8115:                         }
 8116:                     }
 8117:                 } elsif ($context eq 'requestauthor') {
 8118:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8119:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8120:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8121:                             $refused = '';
 8122:                         } else {
 8123:                             my %domdefaults = &get_domain_defaults($udom);
 8124:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8125:                                 my $checkbystatus;
 8126:                                 if ($env{'user.adv'}) { 
 8127:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8128:                                     if ($disposition eq 'automatic') {
 8129:                                         $refused = '';
 8130:                                     } elsif ($disposition eq '') {
 8131:                                         $checkbystatus = 1;
 8132:                                     } 
 8133:                                 } else {
 8134:                                     $checkbystatus = 1;
 8135:                                 }
 8136:                                 if ($checkbystatus) {
 8137:                                     if ($env{'environment.inststatus'}) {
 8138:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8139:                                         foreach my $type (@inststatuses) {
 8140:                                             if (($type ne '') &&
 8141:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8142:                                                 $refused = '';
 8143:                                             }
 8144:                                         }
 8145:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8146:                                         $refused = '';
 8147:                                     }
 8148:                                 }
 8149:                             }
 8150:                         }
 8151:                     }
 8152:                 }
 8153:                 if ($refused) {
 8154:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8155:                              ' '.$role.' '.$end.' '.$start.' by '.
 8156: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8157:                     return 'refused';
 8158:                 }
 8159:             }
 8160:         } elsif ($role eq 'au') {
 8161:             if ($url ne '/'.$udom.'/') {
 8162:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8163:                          ' to assign author role for '.$uname.':'.$udom.
 8164:                          ' in domain: '.$url.' refused (wrong domain).');
 8165:                 return 'refused';
 8166:             }
 8167:         }
 8168:         $mrole=$role;
 8169:     }
 8170:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8171:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8172:     if ($end) { $command.='_'.$end; }
 8173:     if ($start) {
 8174: 	if ($end) { 
 8175:            $command.='_'.$start; 
 8176:         } else {
 8177:            $command.='_0_'.$start;
 8178:         }
 8179:     }
 8180:     my $origstart = $start;
 8181:     my $origend = $end;
 8182:     my $delflag;
 8183: # actually delete
 8184:     if ($deleteflag) {
 8185: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8186: # modify command to delete the role
 8187:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8188:                 "$udom:$uname:$url".'_'."$mrole";
 8189: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8190: # set start and finish to negative values for userrolelog
 8191:            $start=-1;
 8192:            $end=-1;
 8193:            $delflag = 1;
 8194:         }
 8195:     }
 8196: # send command
 8197:     my $answer=&reply($command,&homeserver($uname,$udom));
 8198: # log new user role if status is ok
 8199:     if ($answer eq 'ok') {
 8200: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8201:         if (($role eq 'cc') || ($role eq 'in') ||
 8202:             ($role eq 'ep') || ($role eq 'ad') ||
 8203:             ($role eq 'ta') || ($role eq 'st') ||
 8204:             ($role=~/^cr/) || ($role eq 'gr') ||
 8205:             ($role eq 'co')) {
 8206: # for course roles, perform group memberships changes triggered by role change.
 8207:             unless ($role =~ /^gr/) {
 8208:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8209:                                                  $origstart,$selfenroll,$context);
 8210:             }
 8211:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8212:                            $selfenroll,$context);
 8213:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8214:                  ($role eq 'au') || ($role eq 'dc')) {
 8215:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8216:                            $context);
 8217:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8218:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8219:                              $context); 
 8220:         }
 8221:         if ($role eq 'cc') {
 8222:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8223:         }
 8224:     }
 8225:     return $answer;
 8226: }
 8227: 
 8228: sub autoupdate_coowners {
 8229:     my ($url,$end,$start,$uname,$udom) = @_;
 8230:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8231:     if (($cdom ne '') && ($cnum ne '')) {
 8232:         my $now = time;
 8233:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8234:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8235:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8236:             my $instcode = $coursehash{'internal.coursecode'};
 8237:             if ($instcode ne '') {
 8238:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8239:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8240:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8241:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8242:                         if ($result eq 'valid') {
 8243:                             if ($coursehash{'internal.co-owners'}) {
 8244:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8245:                                     push(@newcoowners,$coowner);
 8246:                                 }
 8247:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8248:                                     push(@newcoowners,$uname.':'.$udom);
 8249:                                 }
 8250:                                 @newcoowners = sort(@newcoowners);
 8251:                             } else {
 8252:                                 push(@newcoowners,$uname.':'.$udom);
 8253:                             }
 8254:                         } else {
 8255:                             if ($coursehash{'internal.co-owners'}) {
 8256:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8257:                                     unless ($coowner eq $uname.':'.$udom) {
 8258:                                         push(@newcoowners,$coowner);
 8259:                                     }
 8260:                                 }
 8261:                                 unless (@newcoowners > 0) {
 8262:                                     $delcoowners = 1;
 8263:                                     $coowners = '';
 8264:                                 }
 8265:                             }
 8266:                         }
 8267:                         if (@newcoowners || $delcoowners) {
 8268:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8269:                                             $delcoowners,@newcoowners);
 8270:                         }
 8271:                     }
 8272:                 }
 8273:             }
 8274:         }
 8275:     }
 8276: }
 8277: 
 8278: sub store_coowners {
 8279:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8280:     my $cid = $cdom.'_'.$cnum;
 8281:     my ($coowners,$delresult,$putresult);
 8282:     if (@newcoowners) {
 8283:         $coowners = join(',',@newcoowners);
 8284:         my %coownershash = (
 8285:                             'internal.co-owners' => $coowners,
 8286:                            );
 8287:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8288:         if ($putresult eq 'ok') {
 8289:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8290:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8291:             }
 8292:         }
 8293:     }
 8294:     if ($delcoowners) {
 8295:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8296:         if ($delresult eq 'ok') {
 8297:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8298:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8299:             }
 8300:         }
 8301:     }
 8302:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8303:         my %crsinfo =
 8304:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8305:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8306:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8307:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8308:         }
 8309:     }
 8310: }
 8311: 
 8312: # -------------------------------------------------- Modify user authentication
 8313: # Overrides without validation
 8314: 
 8315: sub modifyuserauth {
 8316:     my ($udom,$uname,$umode,$upass)=@_;
 8317:     my $uhome=&homeserver($uname,$udom);
 8318:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8319:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8320:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8321:              ' in domain '.$env{'request.role.domain'});  
 8322:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8323: 		     &escape($upass),$uhome);
 8324:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8325:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8326:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8327:     &log($udom,,$uname,$uhome,
 8328:         'Authentication changed by '.$env{'user.domain'}.', '.
 8329:                                      $env{'user.name'}.', '.$umode.
 8330:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8331:     unless ($reply eq 'ok') {
 8332:         &logthis('Authentication mode error: '.$reply);
 8333: 	return 'error: '.$reply;
 8334:     }   
 8335:     return 'ok';
 8336: }
 8337: 
 8338: # --------------------------------------------------------------- Modify a user
 8339: 
 8340: sub modifyuser {
 8341:     my ($udom,    $uname, $uid,
 8342:         $umode,   $upass, $first,
 8343:         $middle,  $last,  $gene,
 8344:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8345:     $udom= &LONCAPA::clean_domain($udom);
 8346:     $uname=&LONCAPA::clean_username($uname);
 8347:     my $showcandelete = 'none';
 8348:     if (ref($candelete) eq 'ARRAY') {
 8349:         if (@{$candelete} > 0) {
 8350:             $showcandelete = join(', ',@{$candelete});
 8351:         }
 8352:     }
 8353:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8354:              $umode.', '.$first.', '.$middle.', '.
 8355: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8356:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8357:                                      ' desiredhome not specified'). 
 8358:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8359:              ' in domain '.$env{'request.role.domain'});
 8360:     my $uhome=&homeserver($uname,$udom,'true');
 8361:     my $newuser;
 8362:     if ($uhome eq 'no_host') {
 8363:         $newuser = 1;
 8364:     }
 8365: # ----------------------------------------------------------------- Create User
 8366:     if (($uhome eq 'no_host') && 
 8367: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8368:         my $unhome='';
 8369:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8370:             $unhome = $desiredhome;
 8371: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8372: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8373:         } else { # load balancing routine for determining $unhome
 8374:             my $loadm=10000000;
 8375: 	    my %servers = &get_servers($udom,'library');
 8376: 	    foreach my $tryserver (keys(%servers)) {
 8377: 		my $answer=reply('load',$tryserver);
 8378: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8379: 		    $loadm=$answer;
 8380: 		    $unhome=$tryserver;
 8381: 		}
 8382: 	    }
 8383:         }
 8384:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8385: 	    return 'error: unable to find a home server for '.$uname.
 8386:                    ' in domain '.$udom;
 8387:         }
 8388:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8389:                          &escape($upass),$unhome);
 8390: 	unless ($reply eq 'ok') {
 8391:             return 'error: '.$reply;
 8392:         }   
 8393:         $uhome=&homeserver($uname,$udom,'true');
 8394:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8395: 	    return 'error: unable verify users home machine.';
 8396:         }
 8397:     }   # End of creation of new user
 8398: # ---------------------------------------------------------------------- Add ID
 8399:     if ($uid) {
 8400:        $uid=~tr/A-Z/a-z/;
 8401:        my %uidhash=&idrget($udom,$uname);
 8402:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8403:          && (!$forceid)) {
 8404: 	  unless ($uid eq $uidhash{$uname}) {
 8405: 	      return 'error: user id "'.$uid.'" does not match '.
 8406:                   'current user id "'.$uidhash{$uname}.'".';
 8407:           }
 8408:        } else {
 8409: 	  &idput($udom,($uname => $uid));
 8410:        }
 8411:     }
 8412: # -------------------------------------------------------------- Add names, etc
 8413:     my @tmp=&get('environment',
 8414: 		   ['firstname','middlename','lastname','generation','id',
 8415:                     'permanentemail','inststatus'],
 8416: 		   $udom,$uname);
 8417:     my (%names,%oldnames);
 8418:     if ($tmp[0] =~ m/^error:.*/) { 
 8419:         %names=(); 
 8420:     } else {
 8421:         %names = @tmp;
 8422:         %oldnames = %names;
 8423:     }
 8424: #
 8425: # If name, email and/or uid are blank (e.g., because an uploaded file
 8426: # of users did not contain them), do not overwrite existing values
 8427: # unless field is in $candelete array ref.  
 8428: #
 8429: 
 8430:     my @fields = ('firstname','middlename','lastname','generation',
 8431:                   'permanentemail','id');
 8432:     my %newvalues;
 8433:     if (ref($candelete) eq 'ARRAY') {
 8434:         foreach my $field (@fields) {
 8435:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8436:                 if ($field eq 'firstname') {
 8437:                     $names{$field} = $first;
 8438:                 } elsif ($field eq 'middlename') {
 8439:                     $names{$field} = $middle;
 8440:                 } elsif ($field eq 'lastname') {
 8441:                     $names{$field} = $last;
 8442:                 } elsif ($field eq 'generation') { 
 8443:                     $names{$field} = $gene;
 8444:                 } elsif ($field eq 'permanentemail') {
 8445:                     $names{$field} = $email;
 8446:                 } elsif ($field eq 'id') {
 8447:                     $names{$field}  = $uid;
 8448:                 }
 8449:             }
 8450:         }
 8451:     }
 8452:     if ($first)  { $names{'firstname'}  = $first; }
 8453:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8454:     if ($last)   { $names{'lastname'}   = $last; }
 8455:     if (defined($gene))   { $names{'generation'} = $gene; }
 8456:     if ($email) {
 8457:        $email=~s/[^\w\@\.\-\,]//gs;
 8458:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8459:     }
 8460:     if ($uid) { $names{'id'}  = $uid; }
 8461:     if (defined($inststatus)) {
 8462:         $names{'inststatus'} = '';
 8463:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8464:         if (ref($usertypes) eq 'HASH') {
 8465:             my @okstatuses; 
 8466:             foreach my $item (split(/:/,$inststatus)) {
 8467:                 if (defined($usertypes->{$item})) {
 8468:                     push(@okstatuses,$item);  
 8469:                 }
 8470:             }
 8471:             if (@okstatuses) {
 8472:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8473:             }
 8474:         }
 8475:     }
 8476:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8477:                  $umode.', '.$first.', '.$middle.', '.
 8478:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8479:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8480:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8481:     } else {
 8482:         $logmsg .= ' during self creation';
 8483:     }
 8484:     my $changed;
 8485:     if ($newuser) {
 8486:         $changed = 1;
 8487:     } else {
 8488:         foreach my $field (@fields) {
 8489:             if ($names{$field} ne $oldnames{$field}) {
 8490:                 $changed = 1;
 8491:                 last;
 8492:             }
 8493:         }
 8494:     }
 8495:     unless ($changed) {
 8496:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8497:         &logthis($logmsg);
 8498:         return 'ok';
 8499:     }
 8500:     my $reply = &put('environment', \%names, $udom,$uname);
 8501:     if ($reply ne 'ok') { 
 8502:         return 'error: '.$reply;
 8503:     }
 8504:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8505:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8506:     }
 8507:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8508:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8509:     $logmsg = 'Success modifying user '.$logmsg;
 8510:     &logthis($logmsg);
 8511:     return 'ok';
 8512: }
 8513: 
 8514: # -------------------------------------------------------------- Modify student
 8515: 
 8516: sub modifystudent {
 8517:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8518:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8519:         $selfenroll,$context,$inststatus,$credits)=@_;
 8520:     if (!$cid) {
 8521: 	unless ($cid=$env{'request.course.id'}) {
 8522: 	    return 'not_in_class';
 8523: 	}
 8524:     }
 8525: # --------------------------------------------------------------- Make the user
 8526:     my $reply=&modifyuser
 8527: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8528:          $desiredhome,$email,$inststatus);
 8529:     unless ($reply eq 'ok') { return $reply; }
 8530:     # This will cause &modify_student_enrollment to get the uid from the
 8531:     # student's environment
 8532:     $uid = undef if (!$forceid);
 8533:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8534:                                         $gene,$usec,$end,$start,$type,$locktype,
 8535:                                         $cid,$selfenroll,$context,$credits);
 8536:     return $reply;
 8537: }
 8538: 
 8539: sub modify_student_enrollment {
 8540:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8541:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8542:     my ($cdom,$cnum,$chome);
 8543:     if (!$cid) {
 8544: 	unless ($cid=$env{'request.course.id'}) {
 8545: 	    return 'not_in_class';
 8546: 	}
 8547: 	$cdom=$env{'course.'.$cid.'.domain'};
 8548: 	$cnum=$env{'course.'.$cid.'.num'};
 8549:     } else {
 8550: 	($cdom,$cnum)=split(/_/,$cid);
 8551:     }
 8552:     $chome=$env{'course.'.$cid.'.home'};
 8553:     if (!$chome) {
 8554: 	$chome=&homeserver($cnum,$cdom);
 8555:     }
 8556:     if (!$chome) { return 'unknown_course'; }
 8557:     # Make sure the user exists
 8558:     my $uhome=&homeserver($uname,$udom);
 8559:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8560: 	return 'error: no such user';
 8561:     }
 8562:     # Get student data if we were not given enough information
 8563:     if (!defined($first)  || $first  eq '' || 
 8564:         !defined($last)   || $last   eq '' || 
 8565:         !defined($uid)    || $uid    eq '' || 
 8566:         !defined($middle) || $middle eq '' || 
 8567:         !defined($gene)   || $gene   eq '') {
 8568:         # They did not supply us with enough data to enroll the student, so
 8569:         # we need to pick up more information.
 8570:         my %tmp = &get('environment',
 8571:                        ['firstname','middlename','lastname', 'generation','id']
 8572:                        ,$udom,$uname);
 8573: 
 8574:         #foreach my $key (keys(%tmp)) {
 8575:         #    &logthis("key $key = ".$tmp{$key});
 8576:         #}
 8577:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8578:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8579:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8580:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8581:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8582:     }
 8583:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8584:     my $user = "$uname:$udom";
 8585:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8586:     my $reply=cput('classlist',
 8587: 		   {$user => 
 8588: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8589: 		   $cdom,$cnum);
 8590:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8591:         &devalidate_getsection_cache($udom,$uname,$cid);
 8592:     } else { 
 8593: 	return 'error: '.$reply;
 8594:     }
 8595:     # Add student role to user
 8596:     my $uurl='/'.$cid;
 8597:     $uurl=~s/\_/\//g;
 8598:     if ($usec) {
 8599: 	$uurl.='/'.$usec;
 8600:     }
 8601:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8602:                              $selfenroll,$context);
 8603:     if ($result ne 'ok') {
 8604:         if ($old_entry{$user} ne '') {
 8605:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8606:         } else {
 8607:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8608:         }
 8609:     }
 8610:     return $result; 
 8611: }
 8612: 
 8613: sub format_name {
 8614:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8615:     my $name;
 8616:     if ($first ne 'lastname') {
 8617: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8618:     } else {
 8619: 	if ($lastname=~/\S/) {
 8620: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8621: 	    $name=~s/\s+,/,/;
 8622: 	} else {
 8623: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8624: 	}
 8625:     }
 8626:     $name=~s/^\s+//;
 8627:     $name=~s/\s+$//;
 8628:     $name=~s/\s+/ /g;
 8629:     return $name;
 8630: }
 8631: 
 8632: # ------------------------------------------------- Write to course preferences
 8633: 
 8634: sub writecoursepref {
 8635:     my ($courseid,%prefs)=@_;
 8636:     $courseid=~s/^\///;
 8637:     $courseid=~s/\_/\//g;
 8638:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8639:     my $chome=homeserver($cnum,$cdomain);
 8640:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8641: 	return 'error: no such course';
 8642:     }
 8643:     my $cstring='';
 8644:     foreach my $pref (keys(%prefs)) {
 8645: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8646:     }
 8647:     $cstring=~s/\&$//;
 8648:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8649: }
 8650: 
 8651: # ---------------------------------------------------------- Make/modify course
 8652: 
 8653: sub createcourse {
 8654:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8655:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8656:     $url=&declutter($url);
 8657:     my $cid='';
 8658:     if ($context eq 'requestcourses') {
 8659:         my $can_create = 0;
 8660:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8661:         if ($udom eq $ownerdom) {
 8662:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8663:                                   $context)) {
 8664:                 $can_create = 1;
 8665:             }
 8666:         } else {
 8667:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8668:                                            $category);
 8669:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8670:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8671:                 if (@curr > 0) {
 8672:                     my @options = qw(approval validate autolimit);
 8673:                     my $optregex = join('|',@options);
 8674:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8675:                         $can_create = 1;
 8676:                     }
 8677:                 }
 8678:             }
 8679:         }
 8680:         if ($can_create) {
 8681:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8682:                 unless (&allowed('ccc',$udom)) {
 8683:                     return 'refused'; 
 8684:                 }
 8685:             }
 8686:         } else {
 8687:             return 'refused';
 8688:         }
 8689:     } elsif (!&allowed('ccc',$udom)) {
 8690:         return 'refused';
 8691:     }
 8692: # --------------------------------------------------------------- Get Unique ID
 8693:     my $uname;
 8694:     if ($cnum =~ /^$match_courseid$/) {
 8695:         my $chome=&homeserver($cnum,$udom,'true');
 8696:         if (($chome eq '') || ($chome eq 'no_host')) {
 8697:             $uname = $cnum;
 8698:         } else {
 8699:             $uname = &generate_coursenum($udom,$crstype);
 8700:         }
 8701:     } else {
 8702:         $uname = &generate_coursenum($udom,$crstype);
 8703:     }
 8704:     return $uname if ($uname =~ /^error/);
 8705: # -------------------------------------------------- Check supplied server name
 8706:     if (!defined($course_server)) {
 8707:         if (defined(&domain($udom,'primary'))) {
 8708:             $course_server = &domain($udom,'primary');
 8709:         } else {
 8710:             $course_server = $env{'user.home'}; 
 8711:         }
 8712:     }
 8713:     my %host_servers =
 8714:         &Apache::lonnet::get_servers($udom,'library');
 8715:     unless ($host_servers{$course_server}) {
 8716:         return 'error: invalid home server for course: '.$course_server;
 8717:     }
 8718: # ------------------------------------------------------------- Make the course
 8719:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8720:                       $course_server);
 8721:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8722:     my $uhome=&homeserver($uname,$udom,'true');
 8723:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8724: 	return 'error: no such course';
 8725:     }
 8726: # ----------------------------------------------------------------- Course made
 8727: # log existence
 8728:     my $now = time;
 8729:     my $newcourse = {
 8730:                     $udom.'_'.$uname => {
 8731:                                      description => $description,
 8732:                                      inst_code   => $inst_code,
 8733:                                      owner       => $course_owner,
 8734:                                      type        => $crstype,
 8735:                                      creator     => $env{'user.name'}.':'.
 8736:                                                     $env{'user.domain'},
 8737:                                      created     => $now,
 8738:                                      context     => $context,
 8739:                                                 },
 8740:                     };
 8741:     &courseidput($udom,$newcourse,$uhome,'notime');
 8742: # set toplevel url
 8743:     my $topurl=$url;
 8744:     unless ($nonstandard) {
 8745: # ------------------------------------------ For standard courses, make top url
 8746:         my $mapurl=&clutter($url);
 8747:         if ($mapurl eq '/res/') { $mapurl=''; }
 8748:         $env{'form.initmap'}=(<<ENDINITMAP);
 8749: <map>
 8750: <resource id="1" type="start"></resource>
 8751: <resource id="2" src="$mapurl"></resource>
 8752: <resource id="3" type="finish"></resource>
 8753: <link index="1" from="1" to="2"></link>
 8754: <link index="2" from="2" to="3"></link>
 8755: </map>
 8756: ENDINITMAP
 8757:         $topurl=&declutter(
 8758:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8759:                           );
 8760:     }
 8761: # ----------------------------------------------------------- Write preferences
 8762:     &writecoursepref($udom.'_'.$uname,
 8763:                      ('description'              => $description,
 8764:                       'url'                      => $topurl,
 8765:                       'internal.creator'         => $env{'user.name'}.':'.
 8766:                                                     $env{'user.domain'},
 8767:                       'internal.created'         => $now,
 8768:                       'internal.creationcontext' => $context)
 8769:                     );
 8770:     return '/'.$udom.'/'.$uname;
 8771: }
 8772: 
 8773: # ------------------------------------------------------------------- Create ID
 8774: sub generate_coursenum {
 8775:     my ($udom,$crstype) = @_;
 8776:     my $domdesc = &domain($udom);
 8777:     return 'error: invalid domain' if ($domdesc eq '');
 8778:     my $first;
 8779:     if ($crstype eq 'Community') {
 8780:         $first = '0';
 8781:     } else {
 8782:         $first = int(1+rand(9)); 
 8783:     } 
 8784:     my $uname=$first.
 8785:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8786:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8787:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8788: # ----------------------------------------------- Make sure that does not exist
 8789:     my $uhome=&homeserver($uname,$udom,'true');
 8790:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8791:         if ($crstype eq 'Community') {
 8792:             $first = '0';
 8793:         } else {
 8794:             $first = int(1+rand(9));
 8795:         }
 8796:         $uname=$first.
 8797:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8798:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8799:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8800:         $uhome=&homeserver($uname,$udom,'true');
 8801:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8802:             return 'error: unable to generate unique course-ID';
 8803:         }
 8804:     }
 8805:     return $uname;
 8806: }
 8807: 
 8808: sub is_course {
 8809:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8810:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8811: 
 8812:     return unless $cdom and $cnum;
 8813: 
 8814:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8815:         '.');
 8816: 
 8817:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8818:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8819: }
 8820: 
 8821: sub store_userdata {
 8822:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8823:     my $result;
 8824:     if ($datakey ne '') {
 8825:         if (ref($storehash) eq 'HASH') {
 8826:             if ($udom eq '' || $uname eq '') {
 8827:                 $udom = $env{'user.domain'};
 8828:                 $uname = $env{'user.name'};
 8829:             }
 8830:             my $uhome=&homeserver($uname,$udom);
 8831:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8832:                 $result = 'error: no_host';
 8833:             } else {
 8834:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8835:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8836: 
 8837:                 my $namevalue='';
 8838:                 foreach my $key (keys(%{$storehash})) {
 8839:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8840:                 }
 8841:                 $namevalue=~s/\&$//;
 8842:                 unless ($namespace eq 'courserequests') {
 8843:                     $datakey = &escape($datakey);
 8844:                 }
 8845:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8846:                                   $namevalue,$uhome);
 8847:             }
 8848:         } else {
 8849:             $result = 'error: data to store was not a hash reference'; 
 8850:         }
 8851:     } else {
 8852:         $result= 'error: invalid requestkey'; 
 8853:     }
 8854:     return $result;
 8855: }
 8856: 
 8857: # ---------------------------------------------------------- Assign Custom Role
 8858: 
 8859: sub assigncustomrole {
 8860:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8861:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8862:                        $end,$start,$deleteflag,$selfenroll,$context);
 8863: }
 8864: 
 8865: # ----------------------------------------------------------------- Revoke Role
 8866: 
 8867: sub revokerole {
 8868:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8869:     my $now=time;
 8870:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8871: }
 8872: 
 8873: # ---------------------------------------------------------- Revoke Custom Role
 8874: 
 8875: sub revokecustomrole {
 8876:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8877:     my $now=time;
 8878:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8879:            $deleteflag,$selfenroll,$context);
 8880: }
 8881: 
 8882: # ------------------------------------------------------------ Disk usage
 8883: sub diskusage {
 8884:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8885:     $directorypath =~ s/\/$//;
 8886:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8887:                        .&escape($getpropath).':'.&escape($uname).':'
 8888:                        .&escape($udom),homeserver($uname,$udom));
 8889:     if ($listing eq 'unknown_cmd') {
 8890:         if ($getpropath) {
 8891:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8892:         }
 8893:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8894:     }
 8895:     return $listing;
 8896: }
 8897: 
 8898: sub is_locked {
 8899:     my ($file_name, $domain, $user, $which) = @_;
 8900:     my @check;
 8901:     my $is_locked;
 8902:     push (@check,$file_name);
 8903:     my %locked = &get('file_permissions',\@check,
 8904: 		      $env{'user.domain'},$env{'user.name'});
 8905:     my ($tmp)=keys(%locked);
 8906:     if ($tmp=~/^error:/) { undef(%locked); }
 8907:     
 8908:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8909:         $is_locked = 'false';
 8910:         foreach my $entry (@{$locked{$file_name}}) {
 8911:            if (ref($entry) eq 'ARRAY') {
 8912:                $is_locked = 'true';
 8913:                if (ref($which) eq 'ARRAY') {
 8914:                    push(@{$which},$entry);
 8915:                } else {
 8916:                    last;
 8917:                }
 8918:            }
 8919:        }
 8920:     } else {
 8921:         $is_locked = 'false';
 8922:     }
 8923:     return $is_locked;
 8924: }
 8925: 
 8926: sub declutter_portfile {
 8927:     my ($file) = @_;
 8928:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8929:     return $file;
 8930: }
 8931: 
 8932: # ------------------------------------------------------------- Mark as Read Only
 8933: 
 8934: sub mark_as_readonly {
 8935:     my ($domain,$user,$files,$what) = @_;
 8936:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8937:     my ($tmp)=keys(%current_permissions);
 8938:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8939:     foreach my $file (@{$files}) {
 8940: 	$file = &declutter_portfile($file);
 8941:         push(@{$current_permissions{$file}},$what);
 8942:     }
 8943:     &put('file_permissions',\%current_permissions,$domain,$user);
 8944:     return;
 8945: }
 8946: 
 8947: # ------------------------------------------------------------Save Selected Files
 8948: 
 8949: sub save_selected_files {
 8950:     my ($user, $path, @files) = @_;
 8951:     my $filename = $user."savedfiles";
 8952:     my @other_files = &files_not_in_path($user, $path);
 8953:     open (OUT, '>'.$tmpdir.$filename);
 8954:     foreach my $file (@files) {
 8955:         print (OUT $env{'form.currentpath'}.$file."\n");
 8956:     }
 8957:     foreach my $file (@other_files) {
 8958:         print (OUT $file."\n");
 8959:     }
 8960:     close (OUT);
 8961:     return 'ok';
 8962: }
 8963: 
 8964: sub clear_selected_files {
 8965:     my ($user) = @_;
 8966:     my $filename = $user."savedfiles";
 8967:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8968:     print (OUT undef);
 8969:     close (OUT);
 8970:     return ("ok");    
 8971: }
 8972: 
 8973: sub files_in_path {
 8974:     my ($user, $path) = @_;
 8975:     my $filename = $user."savedfiles";
 8976:     my %return_files;
 8977:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8978:     while (my $line_in = <IN>) {
 8979:         chomp ($line_in);
 8980:         my @paths_and_file = split (m!/!, $line_in);
 8981:         my $file_part = pop (@paths_and_file);
 8982:         my $path_part = join ('/', @paths_and_file);
 8983:         $path_part.='/';
 8984:         my $path_and_file = $path_part.$file_part;
 8985:         if ($path_part eq $path) {
 8986:             $return_files{$file_part}= 'selected';
 8987:         }
 8988:     }
 8989:     close (IN);
 8990:     return (\%return_files);
 8991: }
 8992: 
 8993: # called in portfolio select mode, to show files selected NOT in current directory
 8994: sub files_not_in_path {
 8995:     my ($user, $path) = @_;
 8996:     my $filename = $user."savedfiles";
 8997:     my @return_files;
 8998:     my $path_part;
 8999:     open(IN, '<'.LONCAPA::.$filename);
 9000:     while (my $line = <IN>) {
 9001:         #ok, I know it's clunky, but I want it to work
 9002:         my @paths_and_file = split(m|/|, $line);
 9003:         my $file_part = pop(@paths_and_file);
 9004:         chomp($file_part);
 9005:         my $path_part = join('/', @paths_and_file);
 9006:         $path_part .= '/';
 9007:         my $path_and_file = $path_part.$file_part;
 9008:         if ($path_part ne $path) {
 9009:             push(@return_files, ($path_and_file));
 9010:         }
 9011:     }
 9012:     close(OUT);
 9013:     return (@return_files);
 9014: }
 9015: 
 9016: #----------------------------------------------Get portfolio file permissions
 9017: 
 9018: sub get_portfile_permissions {
 9019:     my ($domain,$user) = @_;
 9020:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9021:     my ($tmp)=keys(%current_permissions);
 9022:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9023:     return \%current_permissions;
 9024: }
 9025: 
 9026: #---------------------------------------------Get portfolio file access controls
 9027: 
 9028: sub get_access_controls {
 9029:     my ($current_permissions,$group,$file) = @_;
 9030:     my %access;
 9031:     my $real_file = $file;
 9032:     $file =~ s/\.meta$//;
 9033:     if (defined($file)) {
 9034:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9035:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9036:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9037:             }
 9038:         }
 9039:     } else {
 9040:         foreach my $key (keys(%{$current_permissions})) {
 9041:             if ($key =~ /\0accesscontrol$/) {
 9042:                 if (defined($group)) {
 9043:                     if ($key !~ m-^\Q$group\E/-) {
 9044:                         next;
 9045:                     }
 9046:                 }
 9047:                 my ($fullpath) = split(/\0/,$key);
 9048:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9049:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9050:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9051:                     }
 9052:                 }
 9053:             }
 9054:         }
 9055:     }
 9056:     return %access;
 9057: }
 9058: 
 9059: sub modify_access_controls {
 9060:     my ($file_name,$changes,$domain,$user)=@_;
 9061:     my ($outcome,$deloutcome);
 9062:     my %store_permissions;
 9063:     my %new_values;
 9064:     my %new_control;
 9065:     my %translation;
 9066:     my @deletions = ();
 9067:     my $now = time;
 9068:     if (exists($$changes{'activate'})) {
 9069:         if (ref($$changes{'activate'}) eq 'HASH') {
 9070:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9071:             my $numnew = scalar(@newitems);
 9072:             for (my $i=0; $i<$numnew; $i++) {
 9073:                 my $newkey = $newitems[$i];
 9074:                 my $newid = &Apache::loncommon::get_cgi_id();
 9075:                 if ($newkey =~ /^\d+:/) { 
 9076:                     $newkey =~ s/^(\d+)/$newid/;
 9077:                     $translation{$1} = $newid;
 9078:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9079:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9080:                     $translation{$1} = $newid;
 9081:                 }
 9082:                 $new_values{$file_name."\0".$newkey} = 
 9083:                                           $$changes{'activate'}{$newitems[$i]};
 9084:                 $new_control{$newkey} = $now;
 9085:             }
 9086:         }
 9087:     }
 9088:     my %todelete;
 9089:     my %changed_items;
 9090:     foreach my $action ('delete','update') {
 9091:         if (exists($$changes{$action})) {
 9092:             if (ref($$changes{$action}) eq 'HASH') {
 9093:                 foreach my $key (keys(%{$$changes{$action}})) {
 9094:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9095:                     if ($action eq 'delete') { 
 9096:                         $todelete{$itemnum} = 1;
 9097:                     } else {
 9098:                         $changed_items{$itemnum} = $key;
 9099:                     }
 9100:                 }
 9101:             }
 9102:         }
 9103:     }
 9104:     # get lock on access controls for file.
 9105:     my $lockhash = {
 9106:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9107:                                                        ':'.$env{'user.domain'},
 9108:                    }; 
 9109:     my $tries = 0;
 9110:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9111:    
 9112:     while (($gotlock ne 'ok') && $tries <3) {
 9113:         $tries ++;
 9114:         sleep 1;
 9115:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9116:     }
 9117:     if ($gotlock eq 'ok') {
 9118:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9119:         my ($tmp)=keys(%curr_permissions);
 9120:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9121:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9122:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9123:             if (ref($curr_controls) eq 'HASH') {
 9124:                 foreach my $control_item (keys(%{$curr_controls})) {
 9125:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9126:                     if (defined($todelete{$itemnum})) {
 9127:                         push(@deletions,$file_name."\0".$control_item);
 9128:                     } else {
 9129:                         if (defined($changed_items{$itemnum})) {
 9130:                             $new_control{$changed_items{$itemnum}} = $now;
 9131:                             push(@deletions,$file_name."\0".$control_item);
 9132:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9133:                         } else {
 9134:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9135:                         }
 9136:                     }
 9137:                 }
 9138:             }
 9139:         }
 9140:         my ($group);
 9141:         if (&is_course($domain,$user)) {
 9142:             ($group,my $file) = split(/\//,$file_name,2);
 9143:         }
 9144:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9145:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9146:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9147:         #  remove lock
 9148:         my @del_lock = ($file_name."\0".'locked_access_records');
 9149:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9150:         my $sqlresult =
 9151:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9152:                                     $group);
 9153:     } else {
 9154:         $outcome = "error: could not obtain lockfile\n";  
 9155:     }
 9156:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9157: }
 9158: 
 9159: sub make_public_indefinitely {
 9160:     my ($requrl) = @_;
 9161:     my $now = time;
 9162:     my $action = 'activate';
 9163:     my $aclnum = 0;
 9164:     if (&is_portfolio_url($requrl)) {
 9165:         my (undef,$udom,$unum,$file_name,$group) =
 9166:             &parse_portfolio_url($requrl);
 9167:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9168:         my %access_controls = &get_access_controls($current_perms,
 9169:                                                    $group,$file_name);
 9170:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9171:             my ($num,$scope,$end,$start) = 
 9172:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9173:             if ($scope eq 'public') {
 9174:                 if ($start <= $now && $end == 0) {
 9175:                     $action = 'none';
 9176:                 } else {
 9177:                     $action = 'update';
 9178:                     $aclnum = $num;
 9179:                 }
 9180:                 last;
 9181:             }
 9182:         }
 9183:         if ($action eq 'none') {
 9184:              return 'ok';
 9185:         } else {
 9186:             my %changes;
 9187:             my $newend = 0;
 9188:             my $newstart = $now;
 9189:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9190:             $changes{$action}{$newkey} = {
 9191:                 type => 'public',
 9192:                 time => {
 9193:                     start => $newstart,
 9194:                     end   => $newend,
 9195:                 },
 9196:             };
 9197:             my ($outcome,$deloutcome,$new_values,$translation) =
 9198:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9199:             return $outcome;
 9200:         }
 9201:     } else {
 9202:         return 'invalid';
 9203:     }
 9204: }
 9205: 
 9206: #------------------------------------------------------Get Marked as Read Only
 9207: 
 9208: sub get_marked_as_readonly {
 9209:     my ($domain,$user,$what,$group) = @_;
 9210:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9211:     my @readonly_files;
 9212:     my $cmp1=$what;
 9213:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9214:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9215:         if (defined($group)) {
 9216:             if ($file_name !~ m-^\Q$group\E/-) {
 9217:                 next;
 9218:             }
 9219:         }
 9220:         if (ref($value) eq "ARRAY"){
 9221:             foreach my $stored_what (@{$value}) {
 9222:                 my $cmp2=$stored_what;
 9223:                 if (ref($stored_what) eq 'ARRAY') {
 9224:                     $cmp2=join('',@{$stored_what});
 9225:                 }
 9226:                 if ($cmp1 eq $cmp2) {
 9227:                     push(@readonly_files, $file_name);
 9228:                     last;
 9229:                 } elsif (!defined($what)) {
 9230:                     push(@readonly_files, $file_name);
 9231:                     last;
 9232:                 }
 9233:             }
 9234:         }
 9235:     }
 9236:     return @readonly_files;
 9237: }
 9238: #-----------------------------------------------------------Get Marked as Read Only Hash
 9239: 
 9240: sub get_marked_as_readonly_hash {
 9241:     my ($current_permissions,$group,$what) = @_;
 9242:     my %readonly_files;
 9243:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9244:         if (defined($group)) {
 9245:             if ($file_name !~ m-^\Q$group\E/-) {
 9246:                 next;
 9247:             }
 9248:         }
 9249:         if (ref($value) eq "ARRAY"){
 9250:             foreach my $stored_what (@{$value}) {
 9251:                 if (ref($stored_what) eq 'ARRAY') {
 9252:                     foreach my $lock_descriptor(@{$stored_what}) {
 9253:                         if ($lock_descriptor eq 'graded') {
 9254:                             $readonly_files{$file_name} = 'graded';
 9255:                         } elsif ($lock_descriptor eq 'handback') {
 9256:                             $readonly_files{$file_name} = 'handback';
 9257:                         } else {
 9258:                             if (!exists($readonly_files{$file_name})) {
 9259:                                 $readonly_files{$file_name} = 'locked';
 9260:                             }
 9261:                         }
 9262:                     }
 9263:                 } 
 9264:             }
 9265:         } 
 9266:     }
 9267:     return %readonly_files;
 9268: }
 9269: # ------------------------------------------------------------ Unmark as Read Only
 9270: 
 9271: sub unmark_as_readonly {
 9272:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9273:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9274:     my ($domain,$user,$what,$file_name,$group) = @_;
 9275:     $file_name = &declutter_portfile($file_name);
 9276:     my $symb_crs = $what;
 9277:     if (ref($what)) { $symb_crs=join('',@$what); }
 9278:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9279:     my ($tmp)=keys(%current_permissions);
 9280:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9281:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9282:     foreach my $file (@readonly_files) {
 9283: 	my $clean_file = &declutter_portfile($file);
 9284: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9285: 	my $current_locks = $current_permissions{$file};
 9286:         my @new_locks;
 9287:         my @del_keys;
 9288:         if (ref($current_locks) eq "ARRAY"){
 9289:             foreach my $locker (@{$current_locks}) {
 9290:                 my $compare=$locker;
 9291:                 if (ref($locker) eq 'ARRAY') {
 9292:                     $compare=join('',@{$locker});
 9293:                     if ($compare ne $symb_crs) {
 9294:                         push(@new_locks, $locker);
 9295:                     }
 9296:                 }
 9297:             }
 9298:             if (scalar(@new_locks) > 0) {
 9299:                 $current_permissions{$file} = \@new_locks;
 9300:             } else {
 9301:                 push(@del_keys, $file);
 9302:                 &del('file_permissions',\@del_keys, $domain, $user);
 9303:                 delete($current_permissions{$file});
 9304:             }
 9305:         }
 9306:     }
 9307:     &put('file_permissions',\%current_permissions,$domain,$user);
 9308:     return;
 9309: }
 9310: 
 9311: # ------------------------------------------------------------ Directory lister
 9312: 
 9313: sub dirlist {
 9314:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9315:     $uri=~s/^\///;
 9316:     $uri=~s/\/$//;
 9317:     my ($udom, $uname);
 9318:     if ($getuserdir) {
 9319:         $udom = $userdomain;
 9320:         $uname = $username;
 9321:     } else {
 9322:         (undef,$udom,$uname)=split(/\//,$uri);
 9323:         if(defined($userdomain)) {
 9324:             $udom = $userdomain;
 9325:         }
 9326:         if(defined($username)) {
 9327:             $uname = $username;
 9328:         }
 9329:     }
 9330:     my ($dirRoot,$listing,@listing_results);
 9331: 
 9332:     $dirRoot = $perlvar{'lonDocRoot'};
 9333:     if (defined($getpropath)) {
 9334:         $dirRoot = &propath($udom,$uname);
 9335:         $dirRoot =~ s/\/$//;
 9336:     } elsif (defined($getuserdir)) {
 9337:         my $subdir=$uname.'__';
 9338:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9339:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9340:                    ."/$udom/$subdir/$uname";
 9341:     } elsif (defined($alternateRoot)) {
 9342:         $dirRoot = $alternateRoot;
 9343:     }
 9344: 
 9345:     if($udom) {
 9346:         if($uname) {
 9347:             my $uhome = &homeserver($uname,$udom);
 9348:             if ($uhome eq 'no_host') {
 9349:                 return ([],'no_host');
 9350:             }
 9351:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9352:                               .$getuserdir.':'.&escape($dirRoot)
 9353:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9354:             if ($listing eq 'unknown_cmd') {
 9355:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9356:             } else {
 9357:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9358:             }
 9359:             if ($listing eq 'unknown_cmd') {
 9360:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9361:                 @listing_results = split(/:/,$listing);
 9362:             } else {
 9363:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9364:             }
 9365:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9366:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9367:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9368:                 return ([],$listing);
 9369:             } else {
 9370:                 return (\@listing_results);
 9371:             }
 9372:         } elsif(!$alternateRoot) {
 9373:             my (%allusers,%listerror);
 9374: 	    my %servers = &get_servers($udom,'library');
 9375:  	    foreach my $tryserver (keys(%servers)) {
 9376:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9377:                                   &escape($udom),$tryserver);
 9378:                 if ($listing eq 'unknown_cmd') {
 9379: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9380: 				      $udom, $tryserver);
 9381:                 } else {
 9382:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9383:                 }
 9384: 		if ($listing eq 'unknown_cmd') {
 9385: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9386: 				      $udom, $tryserver);
 9387: 		    @listing_results = split(/:/,$listing);
 9388: 		} else {
 9389: 		    @listing_results =
 9390: 			map { &unescape($_); } split(/:/,$listing);
 9391: 		}
 9392:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9393:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9394:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9395:                     $listerror{$tryserver} = $listing;
 9396:                 } else {
 9397: 		    foreach my $line (@listing_results) {
 9398: 			my ($entry) = split(/&/,$line,2);
 9399: 			$allusers{$entry} = 1;
 9400: 		    }
 9401: 		}
 9402:             }
 9403:             my @alluserslist=();
 9404:             foreach my $user (sort(keys(%allusers))) {
 9405:                 push(@alluserslist,$user.'&user');
 9406:             }
 9407:             return (\@alluserslist);
 9408:         } else {
 9409:             return ([],'missing username');
 9410:         }
 9411:     } elsif(!defined($getpropath)) {
 9412:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9413:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9414:         return (\@all_domains);
 9415:     } else {
 9416:         return ([],'missing domain');
 9417:     }
 9418: }
 9419: 
 9420: # --------------------------------------------- GetFileTimestamp
 9421: # This function utilizes dirlist and returns the date stamp for
 9422: # when it was last modified.  It will also return an error of -1
 9423: # if an error occurs
 9424: 
 9425: sub GetFileTimestamp {
 9426:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9427:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9428:     $studentName   = &LONCAPA::clean_username($studentName);
 9429:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9430:                                     undef,$getuserdir);
 9431:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9432:         return -1;
 9433:     }
 9434:     if (ref($fileref) eq 'ARRAY') {
 9435:         my @stats = split('&',$fileref->[0]);
 9436:         # @stats contains first the filename, then the stat output
 9437:         return $stats[10]; # so this is 10 instead of 9.
 9438:     } else {
 9439:         return -1;
 9440:     }
 9441: }
 9442: 
 9443: sub stat_file {
 9444:     my ($uri) = @_;
 9445:     $uri = &clutter_with_no_wrapper($uri);
 9446: 
 9447:     my ($udom,$uname,$file);
 9448:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9449: 	($udom,$uname,$file) =
 9450: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9451: 	$file = 'userfiles/'.$file;
 9452:     }
 9453:     if ($uri =~ m-^/res/-) {
 9454: 	($udom,$uname) = 
 9455: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9456: 	$file = $uri;
 9457:     }
 9458: 
 9459:     if (!$udom || !$uname || !$file) {
 9460: 	# unable to handle the uri
 9461: 	return ();
 9462:     }
 9463:     my $getpropath;
 9464:     if ($file =~ /^userfiles\//) {
 9465:         $getpropath = 1;
 9466:     }
 9467:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9468:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9469:         return ();
 9470:     } else {
 9471:         if (ref($listref) eq 'ARRAY') {
 9472:             my @stats = split('&',$listref->[0]);
 9473: 	    shift(@stats); #filename is first
 9474: 	    return @stats;
 9475:         }
 9476:     }
 9477:     return ();
 9478: }
 9479: 
 9480: # -------------------------------------------------------- Value of a Condition
 9481: 
 9482: # gets the value of a specific preevaluated condition
 9483: #    stored in the string  $env{user.state.<cid>}
 9484: # or looks up a condition reference in the bighash and if if hasn't
 9485: # already been evaluated recurses into docondval to get the value of
 9486: # the condition, then memoizing it to 
 9487: #   $env{user.state.<cid>.<condition>}
 9488: sub directcondval {
 9489:     my $number=shift;
 9490:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9491: 	&Apache::lonuserstate::evalstate();
 9492:     }
 9493:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9494: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9495:     } elsif ($number =~ /^_/) {
 9496: 	my $sub_condition;
 9497: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9498: 		&GDBM_READER(),0640)) {
 9499: 	    $sub_condition=$bighash{'conditions'.$number};
 9500: 	    untie(%bighash);
 9501: 	}
 9502: 	my $value = &docondval($sub_condition);
 9503: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9504: 	return $value;
 9505:     }
 9506:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9507:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9508:     } else {
 9509:        return 2;
 9510:     }
 9511: }
 9512: 
 9513: # get the collection of conditions for this resource
 9514: sub condval {
 9515:     my $condidx=shift;
 9516:     my $allpathcond='';
 9517:     foreach my $cond (split(/\|/,$condidx)) {
 9518: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9519: 	    $allpathcond.=
 9520: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9521: 	}
 9522:     }
 9523:     $allpathcond=~s/\|$//;
 9524:     return &docondval($allpathcond);
 9525: }
 9526: 
 9527: #evaluates an expression of conditions
 9528: sub docondval {
 9529:     my ($allpathcond) = @_;
 9530:     my $result=0;
 9531:     if ($env{'request.course.id'}
 9532: 	&& defined($allpathcond)) {
 9533: 	my $operand='|';
 9534: 	my @stack;
 9535: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9536: 	    if ($chunk eq '(') {
 9537: 		push @stack,($operand,$result);
 9538: 	    } elsif ($chunk eq ')') {
 9539: 		my $before=pop @stack;
 9540: 		if (pop @stack eq '&') {
 9541: 		    $result=$result>$before?$before:$result;
 9542: 		} else {
 9543: 		    $result=$result>$before?$result:$before;
 9544: 		}
 9545: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9546: 		$operand=$chunk;
 9547: 	    } else {
 9548: 		my $new=directcondval($chunk);
 9549: 		if ($operand eq '&') {
 9550: 		    $result=$result>$new?$new:$result;
 9551: 		} else {
 9552: 		    $result=$result>$new?$result:$new;
 9553: 		}
 9554: 	    }
 9555: 	}
 9556:     }
 9557:     return $result;
 9558: }
 9559: 
 9560: # ---------------------------------------------------- Devalidate courseresdata
 9561: 
 9562: sub devalidatecourseresdata {
 9563:     my ($coursenum,$coursedomain)=@_;
 9564:     my $hashid=$coursenum.':'.$coursedomain;
 9565:     &devalidate_cache_new('courseres',$hashid);
 9566: }
 9567: 
 9568: 
 9569: # --------------------------------------------------- Course Resourcedata Query
 9570: #
 9571: #  Parameters:
 9572: #      $coursenum    - Number of the course.
 9573: #      $coursedomain - Domain at which the course was created.
 9574: #  Returns:
 9575: #     A hash of the course parameters along (I think) with timestamps
 9576: #     and version info.
 9577: 
 9578: sub get_courseresdata {
 9579:     my ($coursenum,$coursedomain)=@_;
 9580:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9581:     my $hashid=$coursenum.':'.$coursedomain;
 9582:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9583:     my %dumpreply;
 9584:     unless (defined($cached)) {
 9585: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9586: 	$result=\%dumpreply;
 9587: 	my ($tmp) = keys(%dumpreply);
 9588: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9589: 	    &do_cache_new('courseres',$hashid,$result,600);
 9590: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9591: 	    return $tmp;
 9592: 	} elsif ($tmp =~ /^(error)/) {
 9593: 	    $result=undef;
 9594: 	    &do_cache_new('courseres',$hashid,$result,600);
 9595: 	}
 9596:     }
 9597:     return $result;
 9598: }
 9599: 
 9600: sub devalidateuserresdata {
 9601:     my ($uname,$udom)=@_;
 9602:     my $hashid="$udom:$uname";
 9603:     &devalidate_cache_new('userres',$hashid);
 9604: }
 9605: 
 9606: sub get_userresdata {
 9607:     my ($uname,$udom)=@_;
 9608:     #most student don\'t have any data set, check if there is some data
 9609:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9610: 
 9611:     my $hashid="$udom:$uname";
 9612:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9613:     if (!defined($cached)) {
 9614: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9615: 	$result=\%resourcedata;
 9616: 	&do_cache_new('userres',$hashid,$result,600);
 9617:     }
 9618:     my ($tmp)=keys(%$result);
 9619:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9620: 	return $result;
 9621:     }
 9622:     #error 2 occurs when the .db doesn't exist
 9623:     if ($tmp!~/error: 2 /) {
 9624: 	&logthis("<font color=\"blue\">WARNING:".
 9625: 		 " Trying to get resource data for ".
 9626: 		 $uname." at ".$udom.": ".
 9627: 		 $tmp."</font>");
 9628:     } elsif ($tmp=~/error: 2 /) {
 9629: 	#&EXT_cache_set($udom,$uname);
 9630: 	&do_cache_new('userres',$hashid,undef,600);
 9631: 	undef($tmp); # not really an error so don't send it back
 9632:     }
 9633:     return $tmp;
 9634: }
 9635: #----------------------------------------------- resdata - return resource data
 9636: #  Purpose:
 9637: #    Return resource data for either users or for a course.
 9638: #  Parameters:
 9639: #     $name      - Course/user name.
 9640: #     $domain    - Name of the domain the user/course is registered on.
 9641: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9642: #     @which     - Array of names of resources desired.
 9643: #  Returns:
 9644: #     The value of the first reasource in @which that is found in the
 9645: #     resource hash.
 9646: #  Exceptional Conditions:
 9647: #     If the $type passed in is not valid (not the string 'course' or 
 9648: #     'user', an undefined  reference is returned.
 9649: #     If none of the resources are found, an undef is returned
 9650: sub resdata {
 9651:     my ($name,$domain,$type,@which)=@_;
 9652:     my $result;
 9653:     if ($type eq 'course') {
 9654: 	$result=&get_courseresdata($name,$domain);
 9655:     } elsif ($type eq 'user') {
 9656: 	$result=&get_userresdata($name,$domain);
 9657:     }
 9658:     if (!ref($result)) { return $result; }    
 9659:     foreach my $item (@which) {
 9660: 	if (defined($result->{$item->[0]})) {
 9661: 	    return [$result->{$item->[0]},$item->[1]];
 9662: 	}
 9663:     }
 9664:     return undef;
 9665: }
 9666: 
 9667: sub get_numsuppfiles {
 9668:     my ($cnum,$cdom,$ignorecache)=@_;
 9669:     my $hashid=$cnum.':'.$cdom;
 9670:     my ($suppcount,$cached);
 9671:     unless ($ignorecache) {
 9672:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9673:     }
 9674:     unless (defined($cached)) {
 9675:         my $chome=&homeserver($cnum,$cdom);
 9676:         unless ($chome eq 'no_host') {
 9677:             ($suppcount,my $errors) = (0,0);
 9678:             my $suppmap = 'supplemental.sequence';
 9679:             ($suppcount,$errors) = 
 9680:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9681:         }
 9682:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9683:     }
 9684:     return $suppcount;
 9685: }
 9686: 
 9687: #
 9688: # EXT resource caching routines
 9689: #
 9690: 
 9691: sub clear_EXT_cache_status {
 9692:     &delenv('cache.EXT.');
 9693: }
 9694: 
 9695: sub EXT_cache_status {
 9696:     my ($target_domain,$target_user) = @_;
 9697:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9698:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9699:         # We know already the user has no data
 9700:         return 1;
 9701:     } else {
 9702:         return 0;
 9703:     }
 9704: }
 9705: 
 9706: sub EXT_cache_set {
 9707:     my ($target_domain,$target_user) = @_;
 9708:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9709:     #&appenv({$cachename => time});
 9710: }
 9711: 
 9712: # --------------------------------------------------------- Value of a Variable
 9713: sub EXT {
 9714: 
 9715:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9716:     unless ($varname) { return ''; }
 9717:     #get real user name/domain, courseid and symb
 9718:     my $courseid;
 9719:     my $publicuser;
 9720:     if ($symbparm) {
 9721: 	$symbparm=&get_symb_from_alias($symbparm);
 9722:     }
 9723:     if (!($uname && $udom)) {
 9724:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9725:       if (!$symbparm) {	$symbparm=$cursymb; }
 9726:     } else {
 9727: 	$courseid=$env{'request.course.id'};
 9728:     }
 9729:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9730:     my $rest;
 9731:     if (defined($therest[0])) {
 9732:        $rest=join('.',@therest);
 9733:     } else {
 9734:        $rest='';
 9735:     }
 9736: 
 9737:     my $qualifierrest=$qualifier;
 9738:     if ($rest) { $qualifierrest.='.'.$rest; }
 9739:     my $spacequalifierrest=$space;
 9740:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9741:     if ($realm eq 'user') {
 9742: # --------------------------------------------------------------- user.resource
 9743: 	if ($space eq 'resource') {
 9744: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9745: 		  || defined($Apache::lonhomework::parsing_a_task))
 9746: 		 &&
 9747: 		 ($symbparm eq &symbread()) ) {	
 9748: 		# if we are in the middle of processing the resource the
 9749: 		# get the value we are planning on committing
 9750:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9751:                     return $Apache::lonhomework::results{$qualifierrest};
 9752:                 } else {
 9753:                     return $Apache::lonhomework::history{$qualifierrest};
 9754:                 }
 9755: 	    } else {
 9756: 		my %restored;
 9757: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9758: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9759: 		} else {
 9760: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9761: 		}
 9762: 		return $restored{$qualifierrest};
 9763: 	    }
 9764: # ----------------------------------------------------------------- user.access
 9765:         } elsif ($space eq 'access') {
 9766: 	    # FIXME - not supporting calls for a specific user
 9767:             return &allowed($qualifier,$rest);
 9768: # ------------------------------------------ user.preferences, user.environment
 9769:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9770: 	    if (($uname eq $env{'user.name'}) &&
 9771: 		($udom eq $env{'user.domain'})) {
 9772: 		return $env{join('.',('environment',$qualifierrest))};
 9773: 	    } else {
 9774: 		my %returnhash;
 9775: 		if (!$publicuser) {
 9776: 		    %returnhash=&userenvironment($udom,$uname,
 9777: 						 $qualifierrest);
 9778: 		}
 9779: 		return $returnhash{$qualifierrest};
 9780: 	    }
 9781: # ----------------------------------------------------------------- user.course
 9782:         } elsif ($space eq 'course') {
 9783: 	    # FIXME - not supporting calls for a specific user
 9784:             return $env{join('.',('request.course',$qualifier))};
 9785: # ------------------------------------------------------------------- user.role
 9786:         } elsif ($space eq 'role') {
 9787: 	    # FIXME - not supporting calls for a specific user
 9788:             my ($role,$where)=split(/\./,$env{'request.role'});
 9789:             if ($qualifier eq 'value') {
 9790: 		return $role;
 9791:             } elsif ($qualifier eq 'extent') {
 9792:                 return $where;
 9793:             }
 9794: # ----------------------------------------------------------------- user.domain
 9795:         } elsif ($space eq 'domain') {
 9796:             return $udom;
 9797: # ------------------------------------------------------------------- user.name
 9798:         } elsif ($space eq 'name') {
 9799:             return $uname;
 9800: # ---------------------------------------------------- Any other user namespace
 9801:         } else {
 9802: 	    my %reply;
 9803: 	    if (!$publicuser) {
 9804: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9805: 	    }
 9806: 	    return $reply{$qualifierrest};
 9807:         }
 9808:     } elsif ($realm eq 'query') {
 9809: # ---------------------------------------------- pull stuff out of query string
 9810:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9811: 						[$spacequalifierrest]);
 9812: 	return $env{'form.'.$spacequalifierrest}; 
 9813:    } elsif ($realm eq 'request') {
 9814: # ------------------------------------------------------------- request.browser
 9815:         if ($space eq 'browser') {
 9816:             return $env{'browser.'.$qualifier};
 9817: # ------------------------------------------------------------ request.filename
 9818:         } else {
 9819:             return $env{'request.'.$spacequalifierrest};
 9820:         }
 9821:     } elsif ($realm eq 'course') {
 9822: # ---------------------------------------------------------- course.description
 9823:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9824:     } elsif ($realm eq 'resource') {
 9825: 
 9826: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9827: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9828: 	}
 9829: 
 9830:         if ($qualifier eq '') {
 9831: 	    if ($space eq 'title') {
 9832: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9833: 	        return &gettitle($symbparm);
 9834: 	    }
 9835: 	
 9836: 	    if ($space eq 'map') {
 9837: 	        my ($map) = &decode_symb($symbparm);
 9838: 	        return &symbread($map);
 9839: 	    }
 9840:             if ($space eq 'maptitle') {
 9841:                 my ($map) = &decode_symb($symbparm);
 9842:                 return &gettitle($map);
 9843:             }
 9844: 	    if ($space eq 'filename') {
 9845: 	        if ($symbparm) {
 9846: 		    return &clutter((&decode_symb($symbparm))[2]);
 9847: 	        }
 9848: 	        return &hreflocation('',$env{'request.filename'});
 9849: 	    }
 9850: 
 9851:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9852:                 if ($space eq 'visibleparts') {
 9853:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9854:                     my $item;
 9855:                     if (ref($navmap)) {
 9856:                         my $res = $navmap->getBySymb($symbparm);
 9857:                         my $parts = $res->parts();
 9858:                         if (ref($parts) eq 'ARRAY') {
 9859:                             $item = join(',',@{$parts});
 9860:                         }
 9861:                         undef($navmap);
 9862:                     }
 9863:                     return $item;
 9864:                 }
 9865:             }
 9866:         }
 9867: 
 9868: 	my ($section, $group, @groups);
 9869: 	my ($courselevelm,$courselevel);
 9870:         if (($courseid eq '') && ($cid)) {
 9871:             $courseid = $cid;
 9872:         }
 9873: 	if (($symbparm && $courseid) && 
 9874: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9875: 
 9876: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9877: 
 9878: # ----------------------------------------------------- Cascading lookup scheme
 9879: 	    my $symbp=$symbparm;
 9880: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9881: 
 9882: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9883: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9884: 
 9885: 	    if (($env{'user.name'} eq $uname) &&
 9886: 		($env{'user.domain'} eq $udom)) {
 9887: 		$section=$env{'request.course.sec'};
 9888:                 @groups = split(/:/,$env{'request.course.groups'});  
 9889:                 @groups=&sort_course_groups($courseid,@groups); 
 9890: 	    } else {
 9891: 		if (! defined($usection)) {
 9892: 		    $section=&getsection($udom,$uname,$courseid);
 9893: 		} else {
 9894: 		    $section = $usection;
 9895: 		}
 9896:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9897: 	    }
 9898: 
 9899: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9900: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9901: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9902: 
 9903: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9904: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9905: 	    $courselevelm=$courseid.'.'.$mapparm;
 9906: 
 9907: # ----------------------------------------------------------- first, check user
 9908: 
 9909: 	    my $userreply=&resdata($uname,$udom,'user',
 9910: 				       ([$courselevelr,'resource'],
 9911: 					[$courselevelm,'map'     ],
 9912: 					[$courselevel, 'course'  ]));
 9913: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9914: 
 9915: # ------------------------------------------------ second, check some of course
 9916:             my $coursereply;
 9917:             if (@groups > 0) {
 9918:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9919:                                        $mapparm,$spacequalifierrest);
 9920:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9921:             }
 9922: 
 9923: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9924: 				  $env{'course.'.$courseid.'.domain'},
 9925: 				  'course',
 9926: 				  ([$seclevelr,   'resource'],
 9927: 				   [$seclevelm,   'map'     ],
 9928: 				   [$seclevel,    'course'  ],
 9929: 				   [$courselevelr,'resource']));
 9930: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9931: 
 9932: # ------------------------------------------------------ third, check map parms
 9933: 	    my %parmhash=();
 9934: 	    my $thisparm='';
 9935: 	    if (tie(%parmhash,'GDBM_File',
 9936: 		    $env{'request.course.fn'}.'_parms.db',
 9937: 		    &GDBM_READER(),0640)) {
 9938: 		$thisparm=$parmhash{$symbparm};
 9939: 		untie(%parmhash);
 9940: 	    }
 9941: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9942: 	}
 9943: # ------------------------------------------ fourth, look in resource metadata
 9944: 
 9945: 	$spacequalifierrest=~s/\./\_/;
 9946: 	my $filename;
 9947: 	if (!$symbparm) { $symbparm=&symbread(); }
 9948: 	if ($symbparm) {
 9949: 	    $filename=(&decode_symb($symbparm))[2];
 9950: 	} else {
 9951: 	    $filename=$env{'request.filename'};
 9952: 	}
 9953: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9954: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9955: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9956: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9957: 
 9958: # ---------------------------------------------- fourth, look in rest of course
 9959: 	if ($symbparm && defined($courseid) && 
 9960: 	    $courseid eq $env{'request.course.id'}) {
 9961: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9962: 				     $env{'course.'.$courseid.'.domain'},
 9963: 				     'course',
 9964: 				     ([$courselevelm,'map'   ],
 9965: 				      [$courselevel, 'course']));
 9966: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9967: 	}
 9968: # ------------------------------------------------------------------ Cascade up
 9969: 	unless ($space eq '0') {
 9970: 	    my @parts=split(/_/,$space);
 9971: 	    my $id=pop(@parts);
 9972: 	    my $part=join('_',@parts);
 9973: 	    if ($part eq '') { $part='0'; }
 9974: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9975: 				 $symbparm,$udom,$uname,$section,1);
 9976: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9977: 	}
 9978: 	if ($recurse) { return undef; }
 9979: 	my $pack_def=&packages_tab_default($filename,$varname);
 9980: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9981: # ---------------------------------------------------- Any other user namespace
 9982:     } elsif ($realm eq 'environment') {
 9983: # ----------------------------------------------------------------- environment
 9984: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9985: 	    return $env{'environment.'.$spacequalifierrest};
 9986: 	} else {
 9987: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9988: 		return '';
 9989: 	    }
 9990: 	    my %returnhash=&userenvironment($udom,$uname,
 9991: 					    $spacequalifierrest);
 9992: 	    return $returnhash{$spacequalifierrest};
 9993: 	}
 9994:     } elsif ($realm eq 'system') {
 9995: # ----------------------------------------------------------------- system.time
 9996: 	if ($space eq 'time') {
 9997: 	    return time;
 9998:         }
 9999:     } elsif ($realm eq 'server') {
10000: # ----------------------------------------------------------------- system.time
10001: 	if ($space eq 'name') {
10002: 	    return $ENV{'SERVER_NAME'};
10003:         }
10004:     }
10005:     return '';
10006: }
10007: 
10008: sub get_reply {
10009:     my ($reply_value) = @_;
10010:     if (ref($reply_value) eq 'ARRAY') {
10011:         if (wantarray) {
10012: 	    return @$reply_value;
10013:         }
10014:         return $reply_value->[0];
10015:     } else {
10016:         return $reply_value;
10017:     }
10018: }
10019: 
10020: sub check_group_parms {
10021:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10022:     my @groupitems = ();
10023:     my $resultitem;
10024:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10025:     foreach my $group (@{$groups}) {
10026:         foreach my $level (@levels) {
10027:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10028:              push(@groupitems,[$item,$level->[1]]);
10029:         }
10030:     }
10031:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10032:                             $env{'course.'.$courseid.'.domain'},
10033:                                      'course',@groupitems);
10034:     return $coursereply;
10035: }
10036: 
10037: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10038:     my ($courseid,@groups) = @_;
10039:     @groups = sort(@groups);
10040:     return @groups;
10041: }
10042: 
10043: sub packages_tab_default {
10044:     my ($uri,$varname)=@_;
10045:     my (undef,$part,$name)=split(/\./,$varname);
10046: 
10047:     my (@extension,@specifics,$do_default);
10048:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10049: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10050: 	if ($pack_type eq 'default') {
10051: 	    $do_default=1;
10052: 	} elsif ($pack_type eq 'extension') {
10053: 	    push(@extension,[$package,$pack_type,$pack_part]);
10054: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10055: 	    # only look at packages defaults for packages that this id is
10056: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10057: 	}
10058:     }
10059:     # first look for a package that matches the requested part id
10060:     foreach my $package (@specifics) {
10061: 	my (undef,$pack_type,$pack_part)=@{$package};
10062: 	next if ($pack_part ne $part);
10063: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10064: 	    return $packagetab{"$pack_type&$name&default"};
10065: 	}
10066:     }
10067:     # look for any possible matching non extension_ package
10068:     foreach my $package (@specifics) {
10069: 	my (undef,$pack_type,$pack_part)=@{$package};
10070: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10071: 	    return $packagetab{"$pack_type&$name&default"};
10072: 	}
10073: 	if ($pack_type eq 'part') { $pack_part='0'; }
10074: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10075: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10076: 	}
10077:     }
10078:     # look for any posible extension_ match
10079:     foreach my $package (@extension) {
10080: 	my ($package,$pack_type)=@{$package};
10081: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10082: 	    return $packagetab{"$pack_type&$name&default"};
10083: 	}
10084: 	if (defined($packagetab{$package."&$name&default"})) {
10085: 	    return $packagetab{$package."&$name&default"};
10086: 	}
10087:     }
10088:     # look for a global default setting
10089:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10090: 	return $packagetab{"default&$name&default"};
10091:     }
10092:     return undef;
10093: }
10094: 
10095: sub add_prefix_and_part {
10096:     my ($prefix,$part)=@_;
10097:     my $keyroot;
10098:     if (defined($prefix) && $prefix !~ /^__/) {
10099: 	# prefix that has a part already
10100: 	$keyroot=$prefix;
10101:     } elsif (defined($prefix)) {
10102: 	# prefix that is missing a part
10103: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10104:     } else {
10105: 	# no prefix at all
10106: 	if (defined($part)) { $keyroot='_'.$part; }
10107:     }
10108:     return $keyroot;
10109: }
10110: 
10111: # ---------------------------------------------------------------- Get metadata
10112: 
10113: my %metaentry;
10114: my %importedpartids;
10115: sub metadata {
10116:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10117:     $uri=&declutter($uri);
10118:     # if it is a non metadata possible uri return quickly
10119:     if (($uri eq '') || 
10120: 	(($uri =~ m|^/*adm/|) && 
10121: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10122:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10123: 	return undef;
10124:     }
10125:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10126: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10127: 	return undef;
10128:     }
10129:     my $filename=$uri;
10130:     $uri=~s/\.meta$//;
10131: #
10132: # Is the metadata already cached?
10133: # Look at timestamp of caching
10134: # Everything is cached by the main uri, libraries are never directly cached
10135: #
10136:     if (!defined($liburi)) {
10137: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10138: 	if (defined($cached)) { return $result->{':'.$what}; }
10139:     }
10140:     {
10141: # Imported parts would go here
10142:         my %importedids=();
10143:         my @origfileimportpartids=();
10144:         my $importedparts=0;
10145: #
10146: # Is this a recursive call for a library?
10147: #
10148: #	if (! exists($metacache{$uri})) {
10149: #	    $metacache{$uri}={};
10150: #	}
10151: 	my $cachetime = 60*60;
10152:         if ($liburi) {
10153: 	    $liburi=&declutter($liburi);
10154:             $filename=$liburi;
10155:         } else {
10156: 	    &devalidate_cache_new('meta',$uri);
10157: 	    undef(%metaentry);
10158: 	}
10159:         my %metathesekeys=();
10160:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10161: 	my $metastring;
10162: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10163: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10164: 	    $metastring = 
10165: 		&Apache::lonnet::ssi_body($which,
10166: 					  ('grade_target' => 'meta'));
10167: 	    $cachetime = 1; # only want this cached in the child not long term
10168: 	} elsif (($uri !~ m -^(editupload)/-) && 
10169:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10170: 	    my $file=&filelocation('',&clutter($filename));
10171: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10172: 	    $metastring=&getfile($file);
10173: 	}
10174:         my $parser=HTML::LCParser->new(\$metastring);
10175:         my $token;
10176:         undef %metathesekeys;
10177:         while ($token=$parser->get_token) {
10178: 	    if ($token->[0] eq 'S') {
10179: 		if (defined($token->[2]->{'package'})) {
10180: #
10181: # This is a package - get package info
10182: #
10183: 		    my $package=$token->[2]->{'package'};
10184: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10185: 		    if (defined($token->[2]->{'id'})) { 
10186: 			$keyroot.='_'.$token->[2]->{'id'}; 
10187: 		    }
10188: 		    if ($metaentry{':packages'}) {
10189: 			$metaentry{':packages'}.=','.$package.$keyroot;
10190: 		    } else {
10191: 			$metaentry{':packages'}=$package.$keyroot;
10192: 		    }
10193: 		    foreach my $pack_entry (keys(%packagetab)) {
10194: 			my $part=$keyroot;
10195: 			$part=~s/^\_//;
10196: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10197: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10198: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10199: 			    # ignore package.tab specified default values
10200:                             # here &package_tab_default() will fetch those
10201: 			    if ($subp eq 'default') { next; }
10202: 			    my $value=$packagetab{$pack_entry};
10203: 			    my $unikey;
10204: 			    if ($pack =~ /_0$/) {
10205: 				$unikey='parameter_0_'.$name;
10206: 				$part=0;
10207: 			    } else {
10208: 				$unikey='parameter'.$keyroot.'_'.$name;
10209: 			    }
10210: 			    if ($subp eq 'display') {
10211: 				$value.=' [Part: '.$part.']';
10212: 			    }
10213: 			    $metaentry{':'.$unikey.'.part'}=$part;
10214: 			    $metathesekeys{$unikey}=1;
10215: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10216: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10217: 			    }
10218: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10219: 				$metaentry{':'.$unikey}=
10220: 				    $metaentry{':'.$unikey.'.default'};
10221: 			    }
10222: 			}
10223: 		    }
10224: 		} else {
10225: #
10226: # This is not a package - some other kind of start tag
10227: #
10228: 		    my $entry=$token->[1];
10229: 		    my $unikey='';
10230: 
10231: 		    if ($entry eq 'import') {
10232: #
10233: # Importing a library here
10234: #
10235:                         my $location=$parser->get_text('/import');
10236:                         my $dir=$filename;
10237:                         $dir=~s|[^/]*$||;
10238:                         $location=&filelocation($dir,$location);
10239:                        
10240:                         my $importmode=$token->[2]->{'importmode'};
10241:                         if ($importmode eq 'problem') {
10242: # Import as problem/response
10243:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10244:                         } elsif ($importmode eq 'part') {
10245: # Import as part(s)
10246:                            $importedparts=1;
10247: # We need to get the original file and the imported file to get the part order correct
10248: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10249: # Load and inspect original file
10250:                            if ($#origfileimportpartids<0) {
10251:                               undef(%importedpartids);
10252:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10253:                               my $origfile=&getfile($origfilelocation);
10254:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10255:                            }
10256: 
10257: # Load and inspect imported file
10258:                            my $impfile=&getfile($location);
10259:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10260:                            if ($#impfilepartids>=0) {
10261: # This problem had parts
10262:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10263:                            } else {
10264: # Importing by turning a single problem into a problem part
10265: # It gets the import-tags ID as part-ID
10266:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10267:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10268:                            }
10269:                         } else {
10270: # Normal import
10271:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10272:                            if (defined($token->[2]->{'id'})) {
10273:                               $unikey.='_'.$token->[2]->{'id'};
10274:                            }
10275:                         }
10276: 
10277: 			if ($depthcount<20) {
10278: 			    my $metadata = 
10279: 				&metadata($uri,'keys', $location,$unikey,
10280: 					  $depthcount+1);
10281: 			    foreach my $meta (split(',',$metadata)) {
10282: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10283: 				$metathesekeys{$meta}=1;
10284: 			    }
10285: 			
10286:                         }
10287: 		    } else {
10288: #
10289: # Not importing, some other kind of non-package, non-library start tag
10290: # 
10291:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10292:                         if (defined($token->[2]->{'id'})) {
10293:                             $unikey.='_'.$token->[2]->{'id'};
10294:                         }
10295: 			if (defined($token->[2]->{'name'})) { 
10296: 			    $unikey.='_'.$token->[2]->{'name'}; 
10297: 			}
10298: 			$metathesekeys{$unikey}=1;
10299: 			foreach my $param (@{$token->[3]}) {
10300: 			    $metaentry{':'.$unikey.'.'.$param} =
10301: 				$token->[2]->{$param};
10302: 			}
10303: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10304: 			my $default=$metaentry{':'.$unikey.'.default'};
10305: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10306: 		 # only ws inside the tag, and not in default, so use default
10307: 		 # as value
10308: 			    $metaentry{':'.$unikey}=$default;
10309: 			} elsif ( $internaltext =~ /\S/ ) {
10310: 		  # something interesting inside the tag
10311: 			    $metaentry{':'.$unikey}=$internaltext;
10312: 			} else {
10313: 		  # no interesting values, don't set a default
10314: 			}
10315: # end of not-a-package not-a-library import
10316: 		    }
10317: # end of not-a-package start tag
10318: 		}
10319: # the next is the end of "start tag"
10320: 	    }
10321: 	}
10322: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10323: 	$extension = lc($extension);
10324: 	if ($extension eq 'htm') { $extension='html'; }
10325: 
10326: 	foreach my $key (keys(%packagetab)) {
10327: 	    #no specific packages #how's our extension
10328: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10329: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10330: 					 \%metathesekeys);
10331: 	}
10332: 
10333: 	if (!exists($metaentry{':packages'})
10334: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10335: 	    foreach my $key (keys(%packagetab)) {
10336: 		#no specific packages well let's get default then
10337: 		if ($key!~/^default&/) { next; }
10338: 		&metadata_create_package_def($uri,$key,'default',
10339: 					     \%metathesekeys);
10340: 	    }
10341: 	}
10342: # are there custom rights to evaluate
10343: 	if ($metaentry{':copyright'} eq 'custom') {
10344: 
10345:     #
10346:     # Importing a rights file here
10347:     #
10348: 	    unless ($depthcount) {
10349: 		my $location=$metaentry{':customdistributionfile'};
10350: 		my $dir=$filename;
10351: 		$dir=~s|[^/]*$||;
10352: 		$location=&filelocation($dir,$location);
10353: 		my $rights_metadata =
10354: 		    &metadata($uri,'keys',$location,'_rights',
10355: 			      $depthcount+1);
10356: 		foreach my $rights (split(',',$rights_metadata)) {
10357: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10358: 		    $metathesekeys{$rights}=1;
10359: 		}
10360: 	    }
10361: 	}
10362: 	# uniqifiy package listing
10363: 	my %seen;
10364: 	my @uniq_packages =
10365: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10366: 	$metaentry{':packages'} = join(',',@uniq_packages);
10367: 
10368:         if ($importedparts) {
10369: # We had imported parts and need to rebuild partorder
10370:            $metaentry{':partorder'}='';
10371:            $metathesekeys{'partorder'}=1;
10372:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10373:                if ($origfileimportpartids[$index] eq 'part') {
10374: # original part, part of the problem
10375:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10376:                } else {
10377: # we have imported parts at this position
10378:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10379:                }
10380:            }
10381:            $metaentry{':partorder'}=~s/^\,//;
10382:         }
10383: 
10384: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10385: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10386: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10387: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10388: # this is the end of "was not already recently cached
10389:     }
10390:     return $metaentry{':'.$what};
10391: }
10392: 
10393: sub metadata_create_package_def {
10394:     my ($uri,$key,$package,$metathesekeys)=@_;
10395:     my ($pack,$name,$subp)=split(/\&/,$key);
10396:     if ($subp eq 'default') { next; }
10397:     
10398:     if (defined($metaentry{':packages'})) {
10399: 	$metaentry{':packages'}.=','.$package;
10400:     } else {
10401: 	$metaentry{':packages'}=$package;
10402:     }
10403:     my $value=$packagetab{$key};
10404:     my $unikey;
10405:     $unikey='parameter_0_'.$name;
10406:     $metaentry{':'.$unikey.'.part'}=0;
10407:     $$metathesekeys{$unikey}=1;
10408:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10409: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10410:     }
10411:     if (defined($metaentry{':'.$unikey.'.default'})) {
10412: 	$metaentry{':'.$unikey}=
10413: 	    $metaentry{':'.$unikey.'.default'};
10414:     }
10415: }
10416: 
10417: sub metadata_generate_part0 {
10418:     my ($metadata,$metacache,$uri) = @_;
10419:     my %allnames;
10420:     foreach my $metakey (keys(%$metadata)) {
10421: 	if ($metakey=~/^parameter\_(.*)/) {
10422: 	  my $part=$$metacache{':'.$metakey.'.part'};
10423: 	  my $name=$$metacache{':'.$metakey.'.name'};
10424: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10425: 	    $allnames{$name}=$part;
10426: 	  }
10427: 	}
10428:     }
10429:     foreach my $name (keys(%allnames)) {
10430:       $$metadata{"parameter_0_$name"}=1;
10431:       my $key=":parameter_0_$name";
10432:       $$metacache{"$key.part"}='0';
10433:       $$metacache{"$key.name"}=$name;
10434:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10435: 					   $allnames{$name}.'_'.$name.
10436: 					   '.type'};
10437:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10438: 			     '.display'};
10439:       my $expr='[Part: '.$allnames{$name}.']';
10440:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10441:       $$metacache{"$key.display"}=$olddis;
10442:     }
10443: }
10444: 
10445: # ------------------------------------------------------ Devalidate title cache
10446: 
10447: sub devalidate_title_cache {
10448:     my ($url)=@_;
10449:     if (!$env{'request.course.id'}) { return; }
10450:     my $symb=&symbread($url);
10451:     if (!$symb) { return; }
10452:     my $key=$env{'request.course.id'}."\0".$symb;
10453:     &devalidate_cache_new('title',$key);
10454: }
10455: 
10456: # ------------------------------------------------- Get the title of a course
10457: 
10458: sub current_course_title {
10459:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10460: }
10461: # ------------------------------------------------- Get the title of a resource
10462: 
10463: sub gettitle {
10464:     my $urlsymb=shift;
10465:     my $symb=&symbread($urlsymb);
10466:     if ($symb) {
10467: 	my $key=$env{'request.course.id'}."\0".$symb;
10468: 	my ($result,$cached)=&is_cached_new('title',$key);
10469: 	if (defined($cached)) { 
10470: 	    return $result;
10471: 	}
10472: 	my ($map,$resid,$url)=&decode_symb($symb);
10473: 	my $title='';
10474: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10475: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10476: 	} else {
10477: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10478: 		    &GDBM_READER(),0640)) {
10479: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10480: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10481: 		untie(%bighash);
10482: 	    }
10483: 	}
10484: 	$title=~s/\&colon\;/\:/gs;
10485: 	if ($title) {
10486: # Remember both $symb and $title for dynamic metadata
10487:             $accesshash{$symb.'___crstitle'}=$title;
10488:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10489: # Cache this title and then return it
10490: 	    return &do_cache_new('title',$key,$title,600);
10491: 	}
10492: 	$urlsymb=$url;
10493:     }
10494:     my $title=&metadata($urlsymb,'title');
10495:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10496:     return $title;
10497: }
10498: 
10499: sub get_slot {
10500:     my ($which,$cnum,$cdom)=@_;
10501:     if (!$cnum || !$cdom) {
10502: 	(undef,my $courseid)=&whichuser();
10503: 	$cdom=$env{'course.'.$courseid.'.domain'};
10504: 	$cnum=$env{'course.'.$courseid.'.num'};
10505:     }
10506:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10507:     my %slotinfo;
10508:     if (exists($remembered{$key})) {
10509: 	$slotinfo{$which} = $remembered{$key};
10510:     } else {
10511: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10512: 	&Apache::lonhomework::showhash(%slotinfo);
10513: 	my ($tmp)=keys(%slotinfo);
10514: 	if ($tmp=~/^error:/) { return (); }
10515: 	$remembered{$key} = $slotinfo{$which};
10516:     }
10517:     if (ref($slotinfo{$which}) eq 'HASH') {
10518: 	return %{$slotinfo{$which}};
10519:     }
10520:     return $slotinfo{$which};
10521: }
10522: 
10523: sub get_reservable_slots {
10524:     my ($cnum,$cdom,$uname,$udom) = @_;
10525:     my $now = time;
10526:     my $reservable_info;
10527:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10528:     if (exists($remembered{$key})) {
10529:         $reservable_info = $remembered{$key};
10530:     } else {
10531:         my %resv;
10532:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10533:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10534:         $reservable_info = \%resv;
10535:         $remembered{$key} = $reservable_info;
10536:     }
10537:     return $reservable_info;
10538: }
10539: 
10540: sub get_course_slots {
10541:     my ($cnum,$cdom) = @_;
10542:     my $hashid=$cnum.':'.$cdom;
10543:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10544:     if (defined($cached)) {
10545:         if (ref($result) eq 'HASH') {
10546:             return %{$result};
10547:         }
10548:     } else {
10549:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10550:         my ($tmp) = keys(%slots);
10551:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10552:             &do_cache_new('allslots',$hashid,\%slots,600);
10553:             return %slots;
10554:         }
10555:     }
10556:     return;
10557: }
10558: 
10559: sub devalidate_slots_cache {
10560:     my ($cnum,$cdom)=@_;
10561:     my $hashid=$cnum.':'.$cdom;
10562:     &devalidate_cache_new('allslots',$hashid);
10563: }
10564: 
10565: sub get_coursechange {
10566:     my ($cdom,$cnum) = @_;
10567:     if ($cdom eq '' || $cnum eq '') {
10568:         return unless ($env{'request.course.id'});
10569:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10570:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10571:     }
10572:     my $hashid=$cdom.'_'.$cnum;
10573:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10574:     if ((defined($cached)) && ($change ne '')) {
10575:         return $change;
10576:     } else {
10577:         my %crshash;
10578:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10579:         if ($crshash{'internal.contentchange'} eq '') {
10580:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10581:             if ($change eq '') {
10582:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10583:                 $change = $crshash{'internal.created'};
10584:             }
10585:         } else {
10586:             $change = $crshash{'internal.contentchange'};
10587:         }
10588:         my $cachetime = 600;
10589:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10590:     }
10591:     return $change;
10592: }
10593: 
10594: sub devalidate_coursechange_cache {
10595:     my ($cnum,$cdom)=@_;
10596:     my $hashid=$cnum.':'.$cdom;
10597:     &devalidate_cache_new('crschange',$hashid);
10598: }
10599: 
10600: # ------------------------------------------------- Update symbolic store links
10601: 
10602: sub symblist {
10603:     my ($mapname,%newhash)=@_;
10604:     $mapname=&deversion(&declutter($mapname));
10605:     my %hash;
10606:     if (($env{'request.course.fn'}) && (%newhash)) {
10607:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10608:                       &GDBM_WRCREAT(),0640)) {
10609: 	    foreach my $url (keys(%newhash)) {
10610: 		next if ($url eq 'last_known'
10611: 			 && $env{'form.no_update_last_known'});
10612: 		$hash{declutter($url)}=&encode_symb($mapname,
10613: 						    $newhash{$url}->[1],
10614: 						    $newhash{$url}->[0]);
10615:             }
10616:             if (untie(%hash)) {
10617: 		return 'ok';
10618:             }
10619:         }
10620:     }
10621:     return 'error';
10622: }
10623: 
10624: # --------------------------------------------------------------- Verify a symb
10625: 
10626: sub symbverify {
10627:     my ($symb,$thisurl,$encstate)=@_;
10628:     my $thisfn=$thisurl;
10629:     $thisfn=&declutter($thisfn);
10630: # direct jump to resource in page or to a sequence - will construct own symbs
10631:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10632: # check URL part
10633:     my ($map,$resid,$url)=&decode_symb($symb);
10634: 
10635:     unless ($url eq $thisfn) { return 0; }
10636: 
10637:     $symb=&symbclean($symb);
10638:     $thisurl=&deversion($thisurl);
10639:     $thisfn=&deversion($thisfn);
10640: 
10641:     my %bighash;
10642:     my $okay=0;
10643: 
10644:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10645:                             &GDBM_READER(),0640)) {
10646:         my $noclutter;
10647:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10648:             $thisurl =~ s/\?.+$//;
10649:             if ($map =~ m{^uploaded/.+\.page$}) {
10650:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10651:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10652:                 $noclutter = 1;
10653:             }
10654:         }
10655:         my $ids;
10656:         if ($noclutter) {
10657:             $ids=$bighash{'ids_'.$thisurl};
10658:         } else {
10659:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10660:         }
10661:         unless ($ids) {
10662:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10663:             $ids=$bighash{$idkey};
10664:         }
10665:         if ($ids) {
10666: # ------------------------------------------------------------------- Has ID(s)
10667:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10668:                 $symb =~ s/\?.+$//;
10669:             }
10670: 	    foreach my $id (split(/\,/,$ids)) {
10671: 	       my ($mapid,$resid)=split(/\./,$id);
10672:                if (
10673:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10674:    eq $symb) {
10675:                    if (ref($encstate)) {
10676:                        $$encstate = $bighash{'encrypted_'.$id};
10677:                    }
10678: 		   if (($env{'request.role.adv'}) ||
10679: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10680:                        ($thisurl eq '/adm/navmaps')) {
10681: 		       $okay=1;
10682:                        last;
10683: 		   }
10684: 	       }
10685: 	   }
10686:         }
10687: 	untie(%bighash);
10688:     }
10689:     return $okay;
10690: }
10691: 
10692: # --------------------------------------------------------------- Clean-up symb
10693: 
10694: sub symbclean {
10695:     my $symb=shift;
10696:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10697: # remove version from map
10698:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10699: 
10700: # remove version from URL
10701:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10702: 
10703: # remove wrapper
10704: 
10705:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10706:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10707:     return $symb;
10708: }
10709: 
10710: # ---------------------------------------------- Split symb to find map and url
10711: 
10712: sub encode_symb {
10713:     my ($map,$resid,$url)=@_;
10714:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10715: }
10716: 
10717: sub decode_symb {
10718:     my $symb=shift;
10719:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10720:     my ($map,$resid,$url)=split(/___/,$symb);
10721:     return (&fixversion($map),$resid,&fixversion($url));
10722: }
10723: 
10724: sub fixversion {
10725:     my $fn=shift;
10726:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10727:     my %bighash;
10728:     my $uri=&clutter($fn);
10729:     my $key=$env{'request.course.id'}.'_'.$uri;
10730: # is this cached?
10731:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10732:     if (defined($cached)) { return $result; }
10733: # unfortunately not cached, or expired
10734:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10735: 	    &GDBM_READER(),0640)) {
10736:  	if ($bighash{'version_'.$uri}) {
10737:  	    my $version=$bighash{'version_'.$uri};
10738:  	    unless (($version eq 'mostrecent') || 
10739: 		    ($version==&getversion($uri))) {
10740:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10741:  	    }
10742:  	}
10743:  	untie %bighash;
10744:     }
10745:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10746: }
10747: 
10748: sub deversion {
10749:     my $url=shift;
10750:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10751:     return $url;
10752: }
10753: 
10754: # ------------------------------------------------------ Return symb list entry
10755: 
10756: sub symbread {
10757:     my ($thisfn,$donotrecurse)=@_;
10758:     my $cache_str;
10759:     if ($thisfn ne '') {
10760:         $cache_str='request.symbread.cached.'.$thisfn;
10761:         if ($env{$cache_str} ne '') {
10762:             return $env{$cache_str};
10763:         }
10764:     } else {
10765: # no filename provided? try from environment
10766:         if ($env{'request.symb'}) {
10767: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10768: 	}
10769: 	$thisfn=$env{'request.filename'};
10770:     }
10771:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10772: # is that filename actually a symb? Verify, clean, and return
10773:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10774: 	if (&symbverify($thisfn,$1)) {
10775: 	    return $env{$cache_str}=&symbclean($thisfn);
10776: 	}
10777:     }
10778:     $thisfn=declutter($thisfn);
10779:     my %hash;
10780:     my %bighash;
10781:     my $syval='';
10782:     if (($env{'request.course.fn'}) && ($thisfn)) {
10783:         my $targetfn = $thisfn;
10784:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10785:             $targetfn = 'adm/wrapper/'.$thisfn;
10786:         }
10787: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10788: 	    $targetfn=$1;
10789: 	}
10790:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10791:                       &GDBM_READER(),0640)) {
10792: 	    $syval=$hash{$targetfn};
10793:             untie(%hash);
10794:         }
10795: # ---------------------------------------------------------- There was an entry
10796:         if ($syval) {
10797: 	    #unless ($syval=~/\_\d+$/) {
10798: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10799: 		    #&appenv({'request.ambiguous' => $thisfn});
10800: 		    #return $env{$cache_str}='';
10801: 		#}    
10802: 		#$syval.=$1;
10803: 	    #}
10804:         } else {
10805: # ------------------------------------------------------- Was not in symb table
10806:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10807:                             &GDBM_READER(),0640)) {
10808: # ---------------------------------------------- Get ID(s) for current resource
10809:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10810:               unless ($ids) { 
10811:                  $ids=$bighash{'ids_/'.$thisfn};
10812:               }
10813:               unless ($ids) {
10814: # alias?
10815: 		  $ids=$bighash{'mapalias_'.$thisfn};
10816:               }
10817:               if ($ids) {
10818: # ------------------------------------------------------------------- Has ID(s)
10819:                  my @possibilities=split(/\,/,$ids);
10820:                  if ($#possibilities==0) {
10821: # ----------------------------------------------- There is only one possibility
10822: 		     my ($mapid,$resid)=split(/\./,$ids);
10823: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10824: 						    $resid,$thisfn);
10825:                  } elsif (!$donotrecurse) {
10826: # ------------------------------------------ There is more than one possibility
10827:                      my $realpossible=0;
10828:                      foreach my $id (@possibilities) {
10829: 			 my $file=$bighash{'src_'.$id};
10830:                          if (&allowed('bre',$file)) {
10831:          		    my ($mapid,$resid)=split(/\./,$id);
10832:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10833: 				$realpossible++;
10834:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10835: 						    $resid,$thisfn);
10836:                             }
10837: 			 }
10838:                      }
10839: 		     if ($realpossible!=1) { $syval=''; }
10840:                  } else {
10841:                      $syval='';
10842:                  }
10843: 	      }
10844:               untie(%bighash)
10845:            }
10846:         }
10847:         if ($syval) {
10848: 	    return $env{$cache_str}=$syval;
10849:         }
10850:     }
10851:     &appenv({'request.ambiguous' => $thisfn});
10852:     return $env{$cache_str}='';
10853: }
10854: 
10855: # ---------------------------------------------------------- Return random seed
10856: 
10857: sub numval {
10858:     my $txt=shift;
10859:     $txt=~tr/A-J/0-9/;
10860:     $txt=~tr/a-j/0-9/;
10861:     $txt=~tr/K-T/0-9/;
10862:     $txt=~tr/k-t/0-9/;
10863:     $txt=~tr/U-Z/0-5/;
10864:     $txt=~tr/u-z/0-5/;
10865:     $txt=~s/\D//g;
10866:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10867:     return int($txt);
10868: }
10869: 
10870: sub numval2 {
10871:     my $txt=shift;
10872:     $txt=~tr/A-J/0-9/;
10873:     $txt=~tr/a-j/0-9/;
10874:     $txt=~tr/K-T/0-9/;
10875:     $txt=~tr/k-t/0-9/;
10876:     $txt=~tr/U-Z/0-5/;
10877:     $txt=~tr/u-z/0-5/;
10878:     $txt=~s/\D//g;
10879:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10880:     my $total;
10881:     foreach my $val (@txts) { $total+=$val; }
10882:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10883:     return int($total);
10884: }
10885: 
10886: sub numval3 {
10887:     use integer;
10888:     my $txt=shift;
10889:     $txt=~tr/A-J/0-9/;
10890:     $txt=~tr/a-j/0-9/;
10891:     $txt=~tr/K-T/0-9/;
10892:     $txt=~tr/k-t/0-9/;
10893:     $txt=~tr/U-Z/0-5/;
10894:     $txt=~tr/u-z/0-5/;
10895:     $txt=~s/\D//g;
10896:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10897:     my $total;
10898:     foreach my $val (@txts) { $total+=$val; }
10899:     if ($_64bit) { $total=(($total<<32)>>32); }
10900:     return $total;
10901: }
10902: 
10903: sub digest {
10904:     my ($data)=@_;
10905:     my $digest=&Digest::MD5::md5($data);
10906:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10907:     my ($e,$f);
10908:     {
10909:         use integer;
10910:         $e=($a+$b);
10911:         $f=($c+$d);
10912:         if ($_64bit) {
10913:             $e=(($e<<32)>>32);
10914:             $f=(($f<<32)>>32);
10915:         }
10916:     }
10917:     if (wantarray) {
10918: 	return ($e,$f);
10919:     } else {
10920: 	my $g;
10921: 	{
10922: 	    use integer;
10923: 	    $g=($e+$f);
10924: 	    if ($_64bit) {
10925: 		$g=(($g<<32)>>32);
10926: 	    }
10927: 	}
10928: 	return $g;
10929:     }
10930: }
10931: 
10932: sub latest_rnd_algorithm_id {
10933:     return '64bit5';
10934: }
10935: 
10936: sub get_rand_alg {
10937:     my ($courseid)=@_;
10938:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10939:     if ($courseid) {
10940: 	return $env{"course.$courseid.rndseed"};
10941:     }
10942:     return &latest_rnd_algorithm_id();
10943: }
10944: 
10945: sub validCODE {
10946:     my ($CODE)=@_;
10947:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10948:     return 0;
10949: }
10950: 
10951: sub getCODE {
10952:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10953:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10954: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10955: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10956: 	return $Apache::lonhomework::history{'resource.CODE'};
10957:     }
10958:     return undef;
10959: }
10960: #
10961: #  Determines the random seed for a specific context:
10962: #
10963: # parameters:
10964: #   symb      - in course context the symb for the seed.
10965: #   course_id - The course id of the form domain_coursenum.
10966: #   domain    - Domain for the user.
10967: #   course    - Course for the user.
10968: #   cenv      - environment of the course.
10969: #
10970: # NOTE:
10971: #   All parameters are picked out of the environment if missing
10972: #   or not defined.
10973: #   If a symb cannot be determined the current time is used instead.
10974: #
10975: #  For a given well defined symb, courside, domain, username,
10976: #  and course environment, the seed is reproducible.
10977: #
10978: sub rndseed {
10979:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10980:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10981:     if (!defined($symb)) {
10982: 	unless ($symb=$wsymb) { return time; }
10983:     }
10984:     if (!defined $courseid) { 
10985: 	$courseid=$wcourseid; 
10986:     }
10987:     if (!defined $domain) { $domain=$wdomain; }
10988:     if (!defined $username) { $username=$wusername }
10989: 
10990:     my $which;
10991:     if (defined($cenv->{'rndseed'})) {
10992: 	$which = $cenv->{'rndseed'};
10993:     } else {
10994: 	$which =&get_rand_alg($courseid);
10995:     }
10996:     if (defined(&getCODE())) {
10997: 
10998: 	if ($which eq '64bit5') {
10999: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11000: 	} elsif ($which eq '64bit4') {
11001: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11002: 	} else {
11003: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11004: 	}
11005:     } elsif ($which eq '64bit5') {
11006: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11007:     } elsif ($which eq '64bit4') {
11008: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11009:     } elsif ($which eq '64bit3') {
11010: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11011:     } elsif ($which eq '64bit2') {
11012: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11013:     } elsif ($which eq '64bit') {
11014: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11015:     }
11016:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11017: }
11018: 
11019: sub rndseed_32bit {
11020:     my ($symb,$courseid,$domain,$username)=@_;
11021:     {
11022: 	use integer;
11023: 	my $symbchck=unpack("%32C*",$symb) << 27;
11024: 	my $symbseed=numval($symb) << 22;
11025: 	my $namechck=unpack("%32C*",$username) << 17;
11026: 	my $nameseed=numval($username) << 12;
11027: 	my $domainseed=unpack("%32C*",$domain) << 7;
11028: 	my $courseseed=unpack("%32C*",$courseid);
11029: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11031: 	#&logthis("rndseed :$num:$symb");
11032: 	if ($_64bit) { $num=(($num<<32)>>32); }
11033: 	return $num;
11034:     }
11035: }
11036: 
11037: sub rndseed_64bit {
11038:     my ($symb,$courseid,$domain,$username)=@_;
11039:     {
11040: 	use integer;
11041: 	my $symbchck=unpack("%32S*",$symb) << 21;
11042: 	my $symbseed=numval($symb) << 10;
11043: 	my $namechck=unpack("%32S*",$username);
11044: 	
11045: 	my $nameseed=numval($username) << 21;
11046: 	my $domainseed=unpack("%32S*",$domain) << 10;
11047: 	my $courseseed=unpack("%32S*",$courseid);
11048: 	
11049: 	my $num1=$symbchck+$symbseed+$namechck;
11050: 	my $num2=$nameseed+$domainseed+$courseseed;
11051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11052: 	#&logthis("rndseed :$num:$symb");
11053: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11054: 	return "$num1,$num2";
11055:     }
11056: }
11057: 
11058: sub rndseed_64bit2 {
11059:     my ($symb,$courseid,$domain,$username)=@_;
11060:     {
11061: 	use integer;
11062: 	# strings need to be an even # of cahracters long, it it is odd the
11063:         # last characters gets thrown away
11064: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11065: 	my $symbseed=numval($symb) << 10;
11066: 	my $namechck=unpack("%32S*",$username.' ');
11067: 	
11068: 	my $nameseed=numval($username) << 21;
11069: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11070: 	my $courseseed=unpack("%32S*",$courseid.' ');
11071: 	
11072: 	my $num1=$symbchck+$symbseed+$namechck;
11073: 	my $num2=$nameseed+$domainseed+$courseseed;
11074: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11075: 	#&logthis("rndseed :$num:$symb");
11076: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11077: 	return "$num1,$num2";
11078:     }
11079: }
11080: 
11081: sub rndseed_64bit3 {
11082:     my ($symb,$courseid,$domain,$username)=@_;
11083:     {
11084: 	use integer;
11085: 	# strings need to be an even # of cahracters long, it it is odd the
11086:         # last characters gets thrown away
11087: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11088: 	my $symbseed=numval2($symb) << 10;
11089: 	my $namechck=unpack("%32S*",$username.' ');
11090: 	
11091: 	my $nameseed=numval2($username) << 21;
11092: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11093: 	my $courseseed=unpack("%32S*",$courseid.' ');
11094: 	
11095: 	my $num1=$symbchck+$symbseed+$namechck;
11096: 	my $num2=$nameseed+$domainseed+$courseseed;
11097: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11098: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11099: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11100: 	
11101: 	return "$num1:$num2";
11102:     }
11103: }
11104: 
11105: sub rndseed_64bit4 {
11106:     my ($symb,$courseid,$domain,$username)=@_;
11107:     {
11108: 	use integer;
11109: 	# strings need to be an even # of cahracters long, it it is odd the
11110:         # last characters gets thrown away
11111: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11112: 	my $symbseed=numval3($symb) << 10;
11113: 	my $namechck=unpack("%32S*",$username.' ');
11114: 	
11115: 	my $nameseed=numval3($username) << 21;
11116: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11117: 	my $courseseed=unpack("%32S*",$courseid.' ');
11118: 	
11119: 	my $num1=$symbchck+$symbseed+$namechck;
11120: 	my $num2=$nameseed+$domainseed+$courseseed;
11121: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11122: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11123: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11124: 	
11125: 	return "$num1:$num2";
11126:     }
11127: }
11128: 
11129: sub rndseed_64bit5 {
11130:     my ($symb,$courseid,$domain,$username)=@_;
11131:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11132:     return "$num1:$num2";
11133: }
11134: 
11135: sub rndseed_CODE_64bit {
11136:     my ($symb,$courseid,$domain,$username)=@_;
11137:     {
11138: 	use integer;
11139: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11140: 	my $symbseed=numval2($symb);
11141: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11142: 	my $CODEseed=numval(&getCODE());
11143: 	my $courseseed=unpack("%32S*",$courseid.' ');
11144: 	my $num1=$symbseed+$CODEchck;
11145: 	my $num2=$CODEseed+$courseseed+$symbchck;
11146: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11147: 	#&logthis("rndseed :$num1:$num2:$symb");
11148: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11149: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11150: 	return "$num1:$num2";
11151:     }
11152: }
11153: 
11154: sub rndseed_CODE_64bit4 {
11155:     my ($symb,$courseid,$domain,$username)=@_;
11156:     {
11157: 	use integer;
11158: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11159: 	my $symbseed=numval3($symb);
11160: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11161: 	my $CODEseed=numval3(&getCODE());
11162: 	my $courseseed=unpack("%32S*",$courseid.' ');
11163: 	my $num1=$symbseed+$CODEchck;
11164: 	my $num2=$CODEseed+$courseseed+$symbchck;
11165: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11166: 	#&logthis("rndseed :$num1:$num2:$symb");
11167: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11168: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11169: 	return "$num1:$num2";
11170:     }
11171: }
11172: 
11173: sub rndseed_CODE_64bit5 {
11174:     my ($symb,$courseid,$domain,$username)=@_;
11175:     my $code = &getCODE();
11176:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11177:     return "$num1:$num2";
11178: }
11179: 
11180: sub setup_random_from_rndseed {
11181:     my ($rndseed)=@_;
11182:     if ($rndseed =~/([,:])/) {
11183: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11184: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11185:     } else {
11186: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11187:     }
11188: }
11189: 
11190: sub latest_receipt_algorithm_id {
11191:     return 'receipt3';
11192: }
11193: 
11194: sub recunique {
11195:     my $fucourseid=shift;
11196:     my $unique;
11197:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11198: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11199: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11200:     } else {
11201: 	$unique=$perlvar{'lonReceipt'};
11202:     }
11203:     return unpack("%32C*",$unique);
11204: }
11205: 
11206: sub recprefix {
11207:     my $fucourseid=shift;
11208:     my $prefix;
11209:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11210: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11211: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11212:     } else {
11213: 	$prefix=$perlvar{'lonHostID'};
11214:     }
11215:     return unpack("%32C*",$prefix);
11216: }
11217: 
11218: sub ireceipt {
11219:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11220: 
11221:     my $return =&recprefix($fucourseid).'-';
11222: 
11223:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11224: 	$env{'request.state'} eq 'construct') {
11225: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11226: 	return $return;
11227:     }
11228: 
11229:     my $cuname=unpack("%32C*",$funame);
11230:     my $cudom=unpack("%32C*",$fudom);
11231:     my $cucourseid=unpack("%32C*",$fucourseid);
11232:     my $cusymb=unpack("%32C*",$fusymb);
11233:     my $cunique=&recunique($fucourseid);
11234:     my $cpart=unpack("%32S*",$part);
11235:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11236: 
11237: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11238: 			       
11239: 	$return.= ($cunique%$cuname+
11240: 		   $cunique%$cudom+
11241: 		   $cusymb%$cuname+
11242: 		   $cusymb%$cudom+
11243: 		   $cucourseid%$cuname+
11244: 		   $cucourseid%$cudom+
11245: 		   $cpart%$cuname+
11246: 		   $cpart%$cudom);
11247:     } else {
11248: 	$return.= ($cunique%$cuname+
11249: 		   $cunique%$cudom+
11250: 		   $cusymb%$cuname+
11251: 		   $cusymb%$cudom+
11252: 		   $cucourseid%$cuname+
11253: 		   $cucourseid%$cudom);
11254:     }
11255:     return $return;
11256: }
11257: 
11258: sub receipt {
11259:     my ($part)=@_;
11260:     my ($symb,$courseid,$domain,$name) = &whichuser();
11261:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11262: }
11263: 
11264: sub whichuser {
11265:     my ($passedsymb)=@_;
11266:     my ($symb,$courseid,$domain,$name,$publicuser);
11267:     if (defined($env{'form.grade_symb'})) {
11268: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11269: 	my $allowed=&allowed('vgr',$tmp_courseid);
11270: 	if (!$allowed &&
11271: 	    exists($env{'request.course.sec'}) &&
11272: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11273: 	    $allowed=&allowed('vgr',$tmp_courseid.
11274: 			      '/'.$env{'request.course.sec'});
11275: 	}
11276: 	if ($allowed) {
11277: 	    ($symb)=&get_env_multiple('form.grade_symb');
11278: 	    $courseid=$tmp_courseid;
11279: 	    ($domain)=&get_env_multiple('form.grade_domain');
11280: 	    ($name)=&get_env_multiple('form.grade_username');
11281: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11282: 	}
11283:     }
11284:     if (!$passedsymb) {
11285: 	$symb=&symbread();
11286:     } else {
11287: 	$symb=$passedsymb;
11288:     }
11289:     $courseid=$env{'request.course.id'};
11290:     $domain=$env{'user.domain'};
11291:     $name=$env{'user.name'};
11292:     if ($name eq 'public' && $domain eq 'public') {
11293: 	if (!defined($env{'form.username'})) {
11294: 	    $env{'form.username'}.=time.rand(10000000);
11295: 	}
11296: 	$name.=$env{'form.username'};
11297:     }
11298:     return ($symb,$courseid,$domain,$name,$publicuser);
11299: 
11300: }
11301: 
11302: # ------------------------------------------------------------ Serves up a file
11303: # returns either the contents of the file or 
11304: # -1 if the file doesn't exist
11305: #
11306: # if the target is a file that was uploaded via DOCS, 
11307: # a check will be made to see if a current copy exists on the local server,
11308: # if it does this will be served, otherwise a copy will be retrieved from
11309: # the home server for the course and stored in /home/httpd/html/userfiles on
11310: # the local server.   
11311: 
11312: sub getfile {
11313:     my ($file) = @_;
11314:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11315:     &repcopy($file);
11316:     return &readfile($file);
11317: }
11318: 
11319: sub repcopy_userfile {
11320:     my ($file)=@_;
11321:     my $londocroot = $perlvar{'lonDocRoot'};
11322:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11323:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11324:     my ($cdom,$cnum,$filename) = 
11325: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11326:     my $uri="/uploaded/$cdom/$cnum/$filename";
11327:     if (-e "$file") {
11328: # we already have a local copy, check it out
11329: 	my @fileinfo = stat($file);
11330: 	my $rtncode;
11331: 	my $info;
11332: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11333: 	if ($lwpresp ne 'ok') {
11334: # there is no such file anymore, even though we had a local copy
11335: 	    if ($rtncode eq '404') {
11336: 		unlink($file);
11337: 	    }
11338: 	    return -1;
11339: 	}
11340: 	if ($info < $fileinfo[9]) {
11341: # nice, the file we have is up-to-date, just say okay
11342: 	    return 'ok';
11343: 	} else {
11344: # the file is outdated, get rid of it
11345: 	    unlink($file);
11346: 	}
11347:     }
11348: # one way or the other, at this point, we don't have the file
11349: # construct the correct path for the file
11350:     my @parts = ($cdom,$cnum); 
11351:     if ($filename =~ m|^(.+)/[^/]+$|) {
11352: 	push @parts, split(/\//,$1);
11353:     }
11354:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11355:     foreach my $part (@parts) {
11356: 	$path .= '/'.$part;
11357: 	if (!-e $path) {
11358: 	    mkdir($path,0770);
11359: 	}
11360:     }
11361: # now the path exists for sure
11362: # get a user agent
11363:     my $ua=new LWP::UserAgent;
11364:     my $transferfile=$file.'.in.transfer';
11365: # FIXME: this should flock
11366:     if (-e $transferfile) { return 'ok'; }
11367:     my $request;
11368:     $uri=~s/^\///;
11369:     my $homeserver = &homeserver($cnum,$cdom);
11370:     my $protocol = $protocol{$homeserver};
11371:     $protocol = 'http' if ($protocol ne 'https');
11372:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11373:     my $response=$ua->request($request,$transferfile);
11374: # did it work?
11375:     if ($response->is_error()) {
11376: 	unlink($transferfile);
11377: 	&logthis("Userfile repcopy failed for $uri");
11378: 	return -1;
11379:     }
11380: # worked, rename the transfer file
11381:     rename($transferfile,$file);
11382:     return 'ok';
11383: }
11384: 
11385: sub tokenwrapper {
11386:     my $uri=shift;
11387:     $uri=~s|^https?\://([^/]+)||;
11388:     $uri=~s|^/||;
11389:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11390:     my $token=$1;
11391:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11392:     if ($udom && $uname && $file) {
11393: 	$file=~s|(\?\.*)*$||;
11394:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11395:         my $homeserver = &homeserver($uname,$udom);
11396:         my $protocol = $protocol{$homeserver};
11397:         $protocol = 'http' if ($protocol ne 'https');
11398:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11399:                (($uri=~/\?/)?'&':'?').'token='.$token.
11400:                                '&tokenissued='.$perlvar{'lonHostID'};
11401:     } else {
11402:         return '/adm/notfound.html';
11403:     }
11404: }
11405: 
11406: # call with reqtype HEAD: get last modification time
11407: # call with reqtype GET: get the file contents
11408: # Do not call this with reqtype GET for large files! It loads everything into memory
11409: #
11410: sub getuploaded {
11411:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11412:     $uri=~s/^\///;
11413:     my $homeserver = &homeserver($cnum,$cdom);
11414:     my $protocol = $protocol{$homeserver};
11415:     $protocol = 'http' if ($protocol ne 'https');
11416:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11417:     my $ua=new LWP::UserAgent;
11418:     my $request=new HTTP::Request($reqtype,$uri);
11419:     my $response=$ua->request($request);
11420:     $$rtncode = $response->code;
11421:     if (! $response->is_success()) {
11422: 	return 'failed';
11423:     }      
11424:     if ($reqtype eq 'HEAD') {
11425: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11426:     } elsif ($reqtype eq 'GET') {
11427: 	$$info = $response->content;
11428:     }
11429:     return 'ok';
11430: }
11431: 
11432: sub readfile {
11433:     my $file = shift;
11434:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11435:     my $fh;
11436:     open($fh,"<$file");
11437:     my $a='';
11438:     while (my $line = <$fh>) { $a .= $line; }
11439:     return $a;
11440: }
11441: 
11442: sub filelocation {
11443:     my ($dir,$file) = @_;
11444:     my $location;
11445:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11446: 
11447:     if ($file =~ m-^/adm/-) {
11448: 	$file=~s-^/adm/wrapper/-/-;
11449: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11450:     }
11451: 
11452:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11453:         $location = $file;
11454:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11455:         my ($udom,$uname,$filename)=
11456:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11457:         my $home=&homeserver($uname,$udom);
11458:         my $is_me=0;
11459:         my @ids=&current_machine_ids();
11460:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11461:         if ($is_me) {
11462:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11463:         } else {
11464:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11465:   	      $udom.'/'.$uname.'/'.$filename;
11466:         }
11467:     } elsif ($file =~ m-^/adm/-) {
11468: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11469:     } else {
11470:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11471:         $file=~s:^/(res|priv)/:/:;
11472:         my $space=$1;
11473:         if ( !( $file =~ m:^/:) ) {
11474:             $location = $dir. '/'.$file;
11475:         } else {
11476:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11477:         }
11478:     }
11479:     $location=~s://+:/:g; # remove duplicate /
11480:     while ($location=~m{/\.\./}) {
11481: 	if ($location =~ m{/[^/]+/\.\./}) {
11482: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11483: 	} else {
11484: 	    $location=~ s{/\.\./}{/}g;
11485: 	}
11486:     } #remove dir/..
11487:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11488:     return $location;
11489: }
11490: 
11491: sub hreflocation {
11492:     my ($dir,$file)=@_;
11493:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11494: 	$file=filelocation($dir,$file);
11495:     } elsif ($file=~m-^/adm/-) {
11496: 	$file=~s-^/adm/wrapper/-/-;
11497: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11498:     }
11499:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11500: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11501:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11502: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11503: 	        {/uploaded/$1/$2/}x;
11504:     }
11505:     if ($file=~ m{^/userfiles/}) {
11506: 	$file =~ s{^/userfiles/}{/uploaded/};
11507:     }
11508:     return $file;
11509: }
11510: 
11511: 
11512: 
11513: 
11514: 
11515: sub current_machine_domains {
11516:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11517: }
11518: 
11519: sub machine_domains {
11520:     my ($hostname) = @_;
11521:     my @domains;
11522:     my %hostname = &all_hostnames();
11523:     while( my($id, $name) = each(%hostname)) {
11524: #	&logthis("-$id-$name-$hostname-");
11525: 	if ($hostname eq $name) {
11526: 	    push(@domains,&host_domain($id));
11527: 	}
11528:     }
11529:     return @domains;
11530: }
11531: 
11532: sub current_machine_ids {
11533:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11534: }
11535: 
11536: sub machine_ids {
11537:     my ($hostname) = @_;
11538:     $hostname ||= &hostname($perlvar{'lonHostID'});
11539:     my @ids;
11540:     my %name_to_host = &all_names();
11541:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11542: 	return @{ $name_to_host{$hostname} };
11543:     }
11544:     return;
11545: }
11546: 
11547: sub additional_machine_domains {
11548:     my @domains;
11549:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11550:     while( my $line = <$fh>) {
11551:         $line =~ s/\s//g;
11552:         push(@domains,$line);
11553:     }
11554:     return @domains;
11555: }
11556: 
11557: sub default_login_domain {
11558:     my $domain = $perlvar{'lonDefDomain'};
11559:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11560:     foreach my $posdom (&current_machine_domains(),
11561:                         &additional_machine_domains()) {
11562:         if (lc($posdom) eq lc($testdomain)) {
11563:             $domain=$posdom;
11564:             last;
11565:         }
11566:     }
11567:     return $domain;
11568: }
11569: 
11570: # ------------------------------------------------------------- Declutters URLs
11571: 
11572: sub declutter {
11573:     my $thisfn=shift;
11574:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11575:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11576:     $thisfn=~s/^\///;
11577:     $thisfn=~s|^adm/wrapper/||;
11578:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11579:     $thisfn=~s/^res\///;
11580:     $thisfn=~s/^priv\///;
11581:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11582:         $thisfn=~s/\?.+$//;
11583:     }
11584:     return $thisfn;
11585: }
11586: 
11587: # ------------------------------------------------------------- Clutter up URLs
11588: 
11589: sub clutter {
11590:     my $thisfn='/'.&declutter(shift);
11591:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11592: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11593:        $thisfn='/res'.$thisfn; 
11594:     }
11595:     if ($thisfn !~m|^/adm|) {
11596: 	if ($thisfn =~ m|^/ext/|) {
11597: 	    $thisfn='/adm/wrapper'.$thisfn;
11598: 	} else {
11599: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11600: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11601: 	    if ($embstyle eq 'ssi'
11602: 		|| ($embstyle eq 'hdn')
11603: 		|| ($embstyle eq 'rat')
11604: 		|| ($embstyle eq 'prv')
11605: 		|| ($embstyle eq 'ign')) {
11606: 		#do nothing with these
11607: 	    } elsif (($embstyle eq 'img') 
11608: 		|| ($embstyle eq 'emb')
11609: 		|| ($embstyle eq 'wrp')) {
11610: 		$thisfn='/adm/wrapper'.$thisfn;
11611: 	    } elsif ($embstyle eq 'unk'
11612: 		     && $thisfn!~/\.(sequence|page)$/) {
11613: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11614: 	    } else {
11615: #		&logthis("Got a blank emb style");
11616: 	    }
11617: 	}
11618:     }
11619:     return $thisfn;
11620: }
11621: 
11622: sub clutter_with_no_wrapper {
11623:     my $uri = &clutter(shift);
11624:     if ($uri =~ m-^/adm/-) {
11625: 	$uri =~ s-^/adm/wrapper/-/-;
11626: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11627:     }
11628:     return $uri;
11629: }
11630: 
11631: sub freeze_escape {
11632:     my ($value)=@_;
11633:     if (ref($value)) {
11634: 	$value=&nfreeze($value);
11635: 	return '__FROZEN__'.&escape($value);
11636:     }
11637:     return &escape($value);
11638: }
11639: 
11640: 
11641: sub thaw_unescape {
11642:     my ($value)=@_;
11643:     if ($value =~ /^__FROZEN__/) {
11644: 	substr($value,0,10,undef);
11645: 	$value=&unescape($value);
11646: 	return &thaw($value);
11647:     }
11648:     return &unescape($value);
11649: }
11650: 
11651: sub correct_line_ends {
11652:     my ($result)=@_;
11653:     $$result =~s/\r\n/\n/mg;
11654:     $$result =~s/\r/\n/mg;
11655: }
11656: # ================================================================ Main Program
11657: 
11658: sub goodbye {
11659:    &logthis("Starting Shut down");
11660: #not converted to using infrastruture and probably shouldn't be
11661:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11662: #converted
11663: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11664:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11665: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11666: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11667: #1.1 only
11668: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11669: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11670: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11671: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11672:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11673:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11674:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11675:    &flushcourselogs();
11676:    &logthis("Shutting down");
11677: }
11678: 
11679: sub get_dns {
11680:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11681:     if (!$ignore_cache) {
11682: 	my ($content,$cached)=
11683: 	    &Apache::lonnet::is_cached_new('dns',$url);
11684: 	if ($cached) {
11685: 	    &$func($content,$hashref);
11686: 	    return;
11687: 	}
11688:     }
11689: 
11690:     my %alldns;
11691:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11692:     foreach my $dns (<$config>) {
11693: 	next if ($dns !~ /^\^(\S*)/x);
11694:         my $line = $1;
11695:         my ($host,$protocol) = split(/:/,$line);
11696:         if ($protocol ne 'https') {
11697:             $protocol = 'http';
11698:         }
11699: 	$alldns{$host} = $protocol;
11700:     }
11701:     while (%alldns) {
11702: 	my ($dns) = keys(%alldns);
11703: 	my $ua=new LWP::UserAgent;
11704:         $ua->timeout(30);
11705: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11706: 	my $response=$ua->request($request);
11707:         delete($alldns{$dns});
11708: 	next if ($response->is_error());
11709: 	my @content = split("\n",$response->content);
11710: 	unless ($nocache) {
11711: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11712: 	}
11713: 	&$func(\@content,$hashref);
11714: 	return;
11715:     }
11716:     close($config);
11717:     my $which = (split('/',$url))[3];
11718:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11719:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11720:     my @content = <$config>;
11721:     &$func(\@content,$hashref);
11722:     return;
11723: }
11724: 
11725: # ------------------------------------------------------Get DNS checksums file
11726: sub parse_dns_checksums_tab {
11727:     my ($lines,$hashref) = @_;
11728:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11729:     my $loncaparev = &get_server_loncaparev($machine_dom);
11730:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11731:     my (%chksum,%revnum);
11732:     if (ref($lines) eq 'ARRAY') {
11733:         chomp(@{$lines});
11734:         my $version = shift(@{$lines});
11735:         if ($version eq $release) {  
11736:             foreach my $line (@{$lines}) {
11737:                 my ($file,$version,$shasum) = split(/,/,$line);
11738:                 $chksum{$file} = $shasum;
11739:                 $revnum{$file} = $version;
11740:             }
11741:             if (ref($hashref) eq 'HASH') {
11742:                 %{$hashref} = (
11743:                                 sums     => \%chksum,
11744:                                 versions => \%revnum,
11745:                               );
11746:             }
11747:         }
11748:     }
11749:     return;
11750: }
11751: 
11752: sub fetch_dns_checksums {
11753:     my %checksums;
11754:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11755:     my $loncaparev = &get_server_loncaparev($machine_dom);
11756:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11757:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11758:              \%checksums);
11759:     return \%checksums;
11760: }
11761: 
11762: # ------------------------------------------------------------ Read domain file
11763: {
11764:     my $loaded;
11765:     my %domain;
11766: 
11767:     sub parse_domain_tab {
11768: 	my ($lines) = @_;
11769: 	foreach my $line (@$lines) {
11770: 	    next if ($line =~ /^(\#|\s*$ )/x);
11771: 
11772: 	    chomp($line);
11773: 	    my ($name,@elements) = split(/:/,$line,9);
11774: 	    my %this_domain;
11775: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11776: 			       'lang_def', 'city', 'longi', 'lati',
11777: 			       'primary') {
11778: 		$this_domain{$field} = shift(@elements);
11779: 	    }
11780: 	    $domain{$name} = \%this_domain;
11781: 	}
11782:     }
11783: 
11784:     sub reset_domain_info {
11785: 	undef($loaded);
11786: 	undef(%domain);
11787:     }
11788: 
11789:     sub load_domain_tab {
11790: 	my ($ignore_cache) = @_;
11791: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11792: 	my $fh;
11793: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11794: 	    my @lines = <$fh>;
11795: 	    &parse_domain_tab(\@lines);
11796: 	}
11797: 	close($fh);
11798: 	$loaded = 1;
11799:     }
11800: 
11801:     sub domain {
11802: 	&load_domain_tab() if (!$loaded);
11803: 
11804: 	my ($name,$what) = @_;
11805: 	return if ( !exists($domain{$name}) );
11806: 
11807: 	if (!$what) {
11808: 	    return $domain{$name}{'description'};
11809: 	}
11810: 	return $domain{$name}{$what};
11811:     }
11812: 
11813:     sub domain_info {
11814:         &load_domain_tab() if (!$loaded);
11815:         return %domain;
11816:     }
11817: 
11818: }
11819: 
11820: 
11821: # ------------------------------------------------------------- Read hosts file
11822: {
11823:     my %hostname;
11824:     my %hostdom;
11825:     my %libserv;
11826:     my $loaded;
11827:     my %name_to_host;
11828:     my %internetdom;
11829:     my %LC_dns_serv;
11830: 
11831:     sub parse_hosts_tab {
11832: 	my ($file) = @_;
11833: 	foreach my $configline (@$file) {
11834: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11835:             chomp($configline);
11836: 	    if ($configline =~ /^\^/) {
11837:                 if ($configline =~ /^\^([\w.\-]+)/) {
11838:                     $LC_dns_serv{$1} = 1;
11839:                 }
11840:                 next;
11841:             }
11842: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11843: 	    $name=~s/\s//g;
11844: 	    if ($id && $domain && $role && $name) {
11845: 		$hostname{$id}=$name;
11846: 		push(@{$name_to_host{$name}}, $id);
11847: 		$hostdom{$id}=$domain;
11848: 		if ($role eq 'library') { $libserv{$id}=$name; }
11849:                 if (defined($protocol)) {
11850:                     if ($protocol eq 'https') {
11851:                         $protocol{$id} = $protocol;
11852:                     } else {
11853:                         $protocol{$id} = 'http'; 
11854:                     }
11855:                 } else {
11856:                     $protocol{$id} = 'http';
11857:                 }
11858:                 if (defined($intdom)) {
11859:                     $internetdom{$id} = $intdom;
11860:                 }
11861: 	    }
11862: 	}
11863:     }
11864:     
11865:     sub reset_hosts_info {
11866: 	&purge_remembered();
11867: 	&reset_domain_info();
11868: 	&reset_hosts_ip_info();
11869: 	undef(%name_to_host);
11870: 	undef(%hostname);
11871: 	undef(%hostdom);
11872: 	undef(%libserv);
11873: 	undef($loaded);
11874:     }
11875: 
11876:     sub load_hosts_tab {
11877: 	my ($ignore_cache) = @_;
11878: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11879: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11880: 	my @config = <$config>;
11881: 	&parse_hosts_tab(\@config);
11882: 	close($config);
11883: 	$loaded=1;
11884:     }
11885: 
11886:     sub hostname {
11887: 	&load_hosts_tab() if (!$loaded);
11888: 
11889: 	my ($lonid) = @_;
11890: 	return $hostname{$lonid};
11891:     }
11892: 
11893:     sub all_hostnames {
11894: 	&load_hosts_tab() if (!$loaded);
11895: 
11896: 	return %hostname;
11897:     }
11898: 
11899:     sub all_names {
11900: 	&load_hosts_tab() if (!$loaded);
11901: 
11902: 	return %name_to_host;
11903:     }
11904: 
11905:     sub all_host_domain {
11906:         &load_hosts_tab() if (!$loaded);
11907:         return %hostdom;
11908:     }
11909: 
11910:     sub is_library {
11911: 	&load_hosts_tab() if (!$loaded);
11912: 
11913: 	return exists($libserv{$_[0]});
11914:     }
11915: 
11916:     sub all_library {
11917: 	&load_hosts_tab() if (!$loaded);
11918: 
11919: 	return %libserv;
11920:     }
11921: 
11922:     sub unique_library {
11923: 	#2x reverse removes all hostnames that appear more than once
11924:         my %unique = reverse &all_library();
11925:         return reverse %unique;
11926:     }
11927: 
11928:     sub get_servers {
11929: 	&load_hosts_tab() if (!$loaded);
11930: 
11931: 	my ($domain,$type) = @_;
11932: 	my %possible_hosts = ($type eq 'library') ? %libserv
11933: 	                                          : %hostname;
11934: 	my %result;
11935: 	if (ref($domain) eq 'ARRAY') {
11936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11937: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11938: 		    $result{$host} = $hostname;
11939: 		}
11940: 	    }
11941: 	} else {
11942: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11943: 		if ($hostdom{$host} eq $domain) {
11944: 		    $result{$host} = $hostname;
11945: 		}
11946: 	    }
11947: 	}
11948: 	return %result;
11949:     }
11950: 
11951:     sub get_unique_servers {
11952:         my %unique = reverse &get_servers(@_);
11953: 	return reverse %unique;
11954:     }
11955: 
11956:     sub host_domain {
11957: 	&load_hosts_tab() if (!$loaded);
11958: 
11959: 	my ($lonid) = @_;
11960: 	return $hostdom{$lonid};
11961:     }
11962: 
11963:     sub all_domains {
11964: 	&load_hosts_tab() if (!$loaded);
11965: 
11966: 	my %seen;
11967: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11968: 	return @uniq;
11969:     }
11970: 
11971:     sub internet_dom {
11972:         &load_hosts_tab() if (!$loaded);
11973: 
11974:         my ($lonid) = @_;
11975:         return $internetdom{$lonid};
11976:     }
11977: 
11978:     sub is_LC_dns {
11979:         &load_hosts_tab() if (!$loaded);
11980: 
11981:         my ($hostname) = @_;
11982:         return exists($LC_dns_serv{$hostname});
11983:     }
11984: 
11985: }
11986: 
11987: { 
11988:     my %iphost;
11989:     my %name_to_ip;
11990:     my %lonid_to_ip;
11991: 
11992:     sub get_hosts_from_ip {
11993: 	my ($ip) = @_;
11994: 	my %iphosts = &get_iphost();
11995: 	if (ref($iphosts{$ip})) {
11996: 	    return @{$iphosts{$ip}};
11997: 	}
11998: 	return;
11999:     }
12000:     
12001:     sub reset_hosts_ip_info {
12002: 	undef(%iphost);
12003: 	undef(%name_to_ip);
12004: 	undef(%lonid_to_ip);
12005:     }
12006: 
12007:     sub get_host_ip {
12008: 	my ($lonid) = @_;
12009: 	if (exists($lonid_to_ip{$lonid})) {
12010: 	    return $lonid_to_ip{$lonid};
12011: 	}
12012: 	my $name=&hostname($lonid);
12013:    	my $ip = gethostbyname($name);
12014: 	return if (!$ip || length($ip) ne 4);
12015: 	$ip=inet_ntoa($ip);
12016: 	$name_to_ip{$name}   = $ip;
12017: 	$lonid_to_ip{$lonid} = $ip;
12018: 	return $ip;
12019:     }
12020:     
12021:     sub get_iphost {
12022: 	my ($ignore_cache) = @_;
12023: 
12024: 	if (!$ignore_cache) {
12025: 	    if (%iphost) {
12026: 		return %iphost;
12027: 	    }
12028: 	    my ($ip_info,$cached)=
12029: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12030: 	    if ($cached) {
12031: 		%iphost      = %{$ip_info->[0]};
12032: 		%name_to_ip  = %{$ip_info->[1]};
12033: 		%lonid_to_ip = %{$ip_info->[2]};
12034: 		return %iphost;
12035: 	    }
12036: 	}
12037: 
12038: 	# get yesterday's info for fallback
12039: 	my %old_name_to_ip;
12040: 	my ($ip_info,$cached)=
12041: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12042: 	if ($cached) {
12043: 	    %old_name_to_ip = %{$ip_info->[1]};
12044: 	}
12045: 
12046: 	my %name_to_host = &all_names();
12047: 	foreach my $name (keys(%name_to_host)) {
12048: 	    my $ip;
12049: 	    if (!exists($name_to_ip{$name})) {
12050: 		$ip = gethostbyname($name);
12051: 		if (!$ip || length($ip) ne 4) {
12052: 		    if (defined($old_name_to_ip{$name})) {
12053: 			$ip = $old_name_to_ip{$name};
12054: 			&logthis("Can't find $name defaulting to old $ip");
12055: 		    } else {
12056: 			&logthis("Name $name no IP found");
12057: 			next;
12058: 		    }
12059: 		} else {
12060: 		    $ip=inet_ntoa($ip);
12061: 		}
12062: 		$name_to_ip{$name} = $ip;
12063: 	    } else {
12064: 		$ip = $name_to_ip{$name};
12065: 	    }
12066: 	    foreach my $id (@{ $name_to_host{$name} }) {
12067: 		$lonid_to_ip{$id} = $ip;
12068: 	    }
12069: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12070: 	}
12071: 	&do_cache_new('iphost','iphost',
12072: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12073: 		      48*60*60);
12074: 
12075: 	return %iphost;
12076:     }
12077: 
12078:     #
12079:     #  Given a DNS returns the loncapa host name for that DNS 
12080:     # 
12081:     sub host_from_dns {
12082:         my ($dns) = @_;
12083:         my @hosts;
12084:         my $ip;
12085: 
12086:         if (exists($name_to_ip{$dns})) {
12087:             $ip = $name_to_ip{$dns};
12088:         }
12089:         if (!$ip) {
12090:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12091:             if (length($ip) == 4) { 
12092: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12093:             }
12094:         }
12095:         if ($ip) {
12096: 	    @hosts = get_hosts_from_ip($ip);
12097: 	    return $hosts[0];
12098:         }
12099:         return undef;
12100:     }
12101: 
12102:     sub get_internet_names {
12103:         my ($lonid) = @_;
12104:         return if ($lonid eq '');
12105:         my ($idnref,$cached)=
12106:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12107:         if ($cached) {
12108:             return $idnref;
12109:         }
12110:         my $ip = &get_host_ip($lonid);
12111:         my @hosts = &get_hosts_from_ip($ip);
12112:         my %iphost = &get_iphost();
12113:         my (@idns,%seen);
12114:         foreach my $id (@hosts) {
12115:             my $dom = &host_domain($id);
12116:             my $prim_id = &domain($dom,'primary');
12117:             my $prim_ip = &get_host_ip($prim_id);
12118:             next if ($seen{$prim_ip});
12119:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12120:                 foreach my $id (@{$iphost{$prim_ip}}) {
12121:                     my $intdom = &internet_dom($id);
12122:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12123:                         push(@idns,$intdom);
12124:                     }
12125:                 }
12126:             }
12127:             $seen{$prim_ip} = 1;
12128:         }
12129:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12130:     }
12131: 
12132: }
12133: 
12134: sub all_loncaparevs {
12135:     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);
12136: }
12137: 
12138: # ---------------------------------------------------------- Read loncaparev table
12139: {
12140:     sub load_loncaparevs { 
12141:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12142:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12143:                 while (my $configline=<$config>) {
12144:                     chomp($configline);
12145:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12146:                     $loncaparevs{$hostid}=$loncaparev;
12147:                 }
12148:                 close($config);
12149:             }
12150:         }
12151:     }
12152: }
12153: 
12154: # ---------------------------------------------------------- Read serverhostID table
12155: {
12156:     sub load_serverhomeIDs {
12157:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12158:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12159:                 while (my $configline=<$config>) {
12160:                     chomp($configline);
12161:                     my ($name,$id)=split(/:/,$configline);
12162:                     $serverhomeIDs{$name}=$id;
12163:                 }
12164:                 close($config);
12165:             }
12166:         }
12167:     }
12168: }
12169: 
12170: 
12171: BEGIN {
12172: 
12173: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12174:     unless ($readit) {
12175: {
12176:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12177:     %perlvar = (%perlvar,%{$configvars});
12178: }
12179: 
12180: 
12181: # ------------------------------------------------------ Read spare server file
12182: {
12183:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12184: 
12185:     while (my $configline=<$config>) {
12186:        chomp($configline);
12187:        if ($configline) {
12188: 	   my ($host,$type) = split(':',$configline,2);
12189: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12190: 	   push(@{ $spareid{$type} }, $host);
12191:        }
12192:     }
12193:     close($config);
12194: }
12195: # ------------------------------------------------------------ Read permissions
12196: {
12197:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12198: 
12199:     while (my $configline=<$config>) {
12200: 	chomp($configline);
12201: 	if ($configline) {
12202: 	    my ($role,$perm)=split(/ /,$configline);
12203: 	    if ($perm ne '') { $pr{$role}=$perm; }
12204: 	}
12205:     }
12206:     close($config);
12207: }
12208: 
12209: # -------------------------------------------- Read plain texts for permissions
12210: {
12211:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12212: 
12213:     while (my $configline=<$config>) {
12214: 	chomp($configline);
12215: 	if ($configline) {
12216: 	    my ($short,@plain)=split(/:/,$configline);
12217:             %{$prp{$short}} = ();
12218: 	    if (@plain > 0) {
12219:                 $prp{$short}{'std'} = $plain[0];
12220:                 for (my $i=1; $i<@plain; $i++) {
12221:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12222:                 }
12223:             }
12224: 	}
12225:     }
12226:     close($config);
12227: }
12228: 
12229: # ---------------------------------------------------------- Read package table
12230: {
12231:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12232: 
12233:     while (my $configline=<$config>) {
12234: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12235: 	chomp($configline);
12236: 	my ($short,$plain)=split(/:/,$configline);
12237: 	my ($pack,$name)=split(/\&/,$short);
12238: 	if ($plain ne '') {
12239: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12240: 	    $packagetab{$short}=$plain; 
12241: 	}
12242:     }
12243:     close($config);
12244: }
12245: 
12246: # ---------------------------------------------------------- Read loncaparev table
12247: 
12248: &load_loncaparevs();
12249: 
12250: # ---------------------------------------------------------- Read serverhostID table
12251: 
12252: &load_serverhomeIDs();
12253: 
12254: # ---------------------------------------------------------- Read releaseslist XML
12255: {
12256:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12257:     if (-e $file) {
12258:         my $parser = HTML::LCParser->new($file);
12259:         while (my $token = $parser->get_token()) {
12260:             if ($token->[0] eq 'S') {
12261:                 my $item = $token->[1];
12262:                 my $name = $token->[2]{'name'};
12263:                 my $value = $token->[2]{'value'};
12264:                 if ($item ne '' && $name ne '' && $value ne '') {
12265:                     my $release = $parser->get_text();
12266:                     $release =~ s/(^\s*|\s*$ )//gx;
12267:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12268:                 }
12269:             }
12270:         }
12271:     }
12272: }
12273: 
12274: # ---------------------------------------------------------- Read managers table
12275: {
12276:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12277:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12278:             while (my $configline=<$config>) {
12279:                 chomp($configline);
12280:                 next if ($configline =~ /^\#/);
12281:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12282:                     $managerstab{$configline} = 1;
12283:                 }
12284:             }
12285:             close($config);
12286:         }
12287:     }
12288: }
12289: 
12290: # ------------- set up temporary directory
12291: {
12292:     $tmpdir = LONCAPA::tempdir();
12293: 
12294: }
12295: 
12296: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12297: 				'compress_threshold'=> 20_000,
12298:  			        });
12299: 
12300: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12301: $dumpcount=0;
12302: $locknum=0;
12303: 
12304: &logtouch();
12305: &logthis('<font color="yellow">INFO: Read configuration</font>');
12306: $readit=1;
12307:     {
12308: 	use integer;
12309: 	my $test=(2**32)+1;
12310: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12311: 	&logthis(" Detected 64bit platform ($_64bit)");
12312:     }
12313: }
12314: }
12315: 
12316: 1;
12317: __END__
12318: 
12319: =pod
12320: 
12321: =head1 NAME
12322: 
12323: Apache::lonnet - Subroutines to ask questions about things in the network.
12324: 
12325: =head1 SYNOPSIS
12326: 
12327: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12328: 
12329:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12330: 
12331: Common parameters:
12332: 
12333: =over 4
12334: 
12335: =item *
12336: 
12337: $uname : an internal username (if $cname expecting a course Id specifically)
12338: 
12339: =item *
12340: 
12341: $udom : a domain (if $cdom expecting a course's domain specifically)
12342: 
12343: =item *
12344: 
12345: $symb : a resource instance identifier
12346: 
12347: =item *
12348: 
12349: $namespace : the name of a .db file that contains the data needed or
12350: being set.
12351: 
12352: =back
12353: 
12354: =head1 OVERVIEW
12355: 
12356: lonnet provides subroutines which interact with the
12357: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12358: about classes, users, and resources.
12359: 
12360: For many of these objects you can also use this to store data about
12361: them or modify them in various ways.
12362: 
12363: =head2 Symbs
12364: 
12365: To identify a specific instance of a resource, LON-CAPA uses symbols
12366: or "symbs"X<symb>. These identifiers are built from the URL of the
12367: map, the resource number of the resource in the map, and the URL of
12368: the resource itself. The latter is somewhat redundant, but might help
12369: if maps change.
12370: 
12371: An example is
12372: 
12373:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12374: 
12375: The respective map entry is
12376: 
12377:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12378:   title="Problem 2">
12379:  </resource>
12380: 
12381: Symbs are used by the random number generator, as well as to store and
12382: restore data specific to a certain instance of for example a problem.
12383: 
12384: =head2 Storing And Retrieving Data
12385: 
12386: X<store()>X<cstore()>X<restore()>Three of the most important functions
12387: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12388: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12389: is is the non-critical message twin of cstore. These functions are for
12390: handlers to store a perl hash to a user's permanent data space in an
12391: easy manner, and to retrieve it again on another call. It is expected
12392: that a handler would use this once at the beginning to retrieve data,
12393: and then again once at the end to send only the new data back.
12394: 
12395: The data is stored in the user's data directory on the user's
12396: homeserver under the ID of the course.
12397: 
12398: The hash that is returned by restore will have all of the previous
12399: value for all of the elements of the hash.
12400: 
12401: Example:
12402: 
12403:  #creating a hash
12404:  my %hash;
12405:  $hash{'foo'}='bar';
12406: 
12407:  #storing it
12408:  &Apache::lonnet::cstore(\%hash);
12409: 
12410:  #changing a value
12411:  $hash{'foo'}='notbar';
12412: 
12413:  #adding a new value
12414:  $hash{'bar'}='foo';
12415:  &Apache::lonnet::cstore(\%hash);
12416: 
12417:  #retrieving the hash
12418:  my %history=&Apache::lonnet::restore();
12419: 
12420:  #print the hash
12421:  foreach my $key (sort(keys(%history))) {
12422:    print("\%history{$key} = $history{$key}");
12423:  }
12424: 
12425: Will print out:
12426: 
12427:  %history{1:foo} = bar
12428:  %history{1:keys} = foo:timestamp
12429:  %history{1:timestamp} = 990455579
12430:  %history{2:bar} = foo
12431:  %history{2:foo} = notbar
12432:  %history{2:keys} = foo:bar:timestamp
12433:  %history{2:timestamp} = 990455580
12434:  %history{bar} = foo
12435:  %history{foo} = notbar
12436:  %history{timestamp} = 990455580
12437:  %history{version} = 2
12438: 
12439: Note that the special hash entries C<keys>, C<version> and
12440: C<timestamp> were added to the hash. C<version> will be equal to the
12441: total number of versions of the data that have been stored. The
12442: C<timestamp> attribute will be the UNIX time the hash was
12443: stored. C<keys> is available in every historical section to list which
12444: keys were added or changed at a specific historical revision of a
12445: hash.
12446: 
12447: B<Warning>: do not store the hash that restore returns directly. This
12448: will cause a mess since it will restore the historical keys as if the
12449: were new keys. I.E. 1:foo will become 1:1:foo etc.
12450: 
12451: Calling convention:
12452: 
12453:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12454:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12455: 
12456: For more detailed information, see lonnet specific documentation.
12457: 
12458: =head1 RETURN MESSAGES
12459: 
12460: =over 4
12461: 
12462: =item * B<con_lost>: unable to contact remote host
12463: 
12464: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12465: when the connection is brought back up
12466: 
12467: =item * B<con_failed>: unable to contact remote host and unable to save message
12468: for later delivery
12469: 
12470: =item * B<error:>: an error a occurred, a description of the error follows the :
12471: 
12472: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12473: that was requested
12474: 
12475: =back
12476: 
12477: =head1 PUBLIC SUBROUTINES
12478: 
12479: =head2 Session Environment Functions
12480: 
12481: =over 4
12482: 
12483: =item * 
12484: X<appenv()>
12485: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12486: the user envirnoment file, and will be restored for each access this
12487: user makes during this session, also modifies the %env for the current
12488: process. Optional rolesarrayref - if defined contains a reference to an array
12489: of roles which are exempt from the restriction on modifying user.role entries 
12490: in the user's environment.db and in %env.    
12491: 
12492: =item *
12493: X<delenv()>
12494: B<delenv($delthis,$regexp)>: removes all items from the session
12495: environment file that begin with $delthis. If the 
12496: optional second arg - $regexp - is true, $delthis is treated as a 
12497: regular expression, otherwise \Q$delthis\E is used. 
12498: The values are also deleted from the current processes %env.
12499: 
12500: =item * get_env_multiple($name) 
12501: 
12502: gets $name from the %env hash, it seemlessly handles the cases where multiple
12503: values may be defined and end up as an array ref.
12504: 
12505: returns an array of values
12506: 
12507: =back
12508: 
12509: =head2 User Information
12510: 
12511: =over 4
12512: 
12513: =item *
12514: X<queryauthenticate()>
12515: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12516: authentication scheme
12517: 
12518: =item *
12519: X<authenticate()>
12520: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12521: authenticate user from domain's lib servers (first use the current
12522: one). C<$upass> should be the users password.
12523: $checkdefauth is optional (value is 1 if a check should be made to
12524:    authenticate user using default authentication method, and allow
12525:    account creation if username does not have account in the domain).
12526: $clientcancheckhost is optional (value is 1 if checking whether the
12527:    server can host will occur on the client side in lonauth.pm).   
12528: 
12529: =item *
12530: X<homeserver()>
12531: B<homeserver($uname,$udom)>: find the server which has
12532: the user's directory and files (there must be only one), this caches
12533: the answer, and also caches if there is a borken connection.
12534: 
12535: =item *
12536: X<idget()>
12537: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12538: (IDs are a unique resource in a domain, there must be only 1 ID per
12539: username, and only 1 username per ID in a specific domain) (returns
12540: hash: id=>name,id=>name)
12541: 
12542: =item *
12543: X<idrget()>
12544: B<idrget($udom,@unames)>: find the IDs behind a list of
12545: usernames (returns hash: name=>id,name=>id)
12546: 
12547: =item *
12548: X<idput()>
12549: B<idput($udom,%ids)>: store away a list of names and associated IDs
12550: 
12551: =item *
12552: X<rolesinit()>
12553: B<rolesinit($udom,$username)>: get user privileges.
12554: returns user role, first access and timer interval hashes
12555: 
12556: =item *
12557: X<privileged()>
12558: B<privileged($username,$domain)>: returns a true if user has a
12559: privileged and active role (i.e. su or dc), false otherwise.
12560: 
12561: =item *
12562: X<getsection()>
12563: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12564: course $cname, return section name/number or '' for "not in course"
12565: and '-1' for "no section"
12566: 
12567: =item *
12568: X<userenvironment()>
12569: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12570: passed in @what from the requested user's environment, returns a hash
12571: 
12572: =item * 
12573: X<userlog_query()>
12574: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12575: activity.log file. %filters defines filters applied when parsing the
12576: log file. These can be start or end timestamps, or the type of action
12577: - log to look for Login or Logout events, check for Checkin or
12578: Checkout, role for role selection. The response is in the form
12579: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12580: escaped strings of the action recorded in the activity.log file.
12581: 
12582: =back
12583: 
12584: =head2 User Roles
12585: 
12586: =over 4
12587: 
12588: =item *
12589: 
12590: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12591:  F: full access
12592:  U,I,K: authentication modes (cxx only)
12593:  '': forbidden
12594:  1: user needs to choose course
12595:  2: browse allowed
12596:  A: passphrase authentication needed
12597: 
12598: =item *
12599: 
12600: constructaccess($url,$setpriv) : check for access to construction space URL
12601: 
12602: See if the owner domain and name in the URL match those in the
12603: expected environment.  If so, return three element list
12604: ($ownername,$ownerdomain,$ownerhome).
12605: 
12606: Otherwise return the null string.
12607: 
12608: If second argument 'setpriv' is true, it assigns the privileges,
12609: and returns the same three element list, unless the owner has
12610: blocked "ad hoc" Domain Coordinator access to the Author Space,
12611: in which case the null string is returned.
12612: 
12613: =item *
12614: 
12615: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12616: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12617: and course level
12618: 
12619: =item *
12620: 
12621: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12622: (rolesplain.tab); plain text explanation of a user role term.
12623: $type is Course (default) or Community.
12624: If $forcedefault evaluates to true, text returned will be default 
12625: text for $type. Otherwise, if this is a course, the text returned 
12626: will be a custom name for the role (if defined in the course's 
12627: environment).  If no custom name is defined the default is returned.
12628:    
12629: =item *
12630: 
12631: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12632: All arguments are optional. Returns a hash of a roles, either for
12633: co-author/assistant author roles for a user's Construction Space
12634: (default), or if $context is 'userroles', roles for the user himself,
12635: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12636: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12637: For each key, value is set to colon-separated start and end times for
12638: the role.  If no username and domain are specified, will default to
12639: current user/domain. Types, roles, and roledoms are references to arrays
12640: of role statuses (active, future or previous), roles 
12641: (e.g., cc,in, st etc.) and domains of the roles which can be used
12642: to restrict the list of roles reported. If no array ref is 
12643: provided for types, will default to return only active roles.
12644: 
12645: =item *
12646: 
12647: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12648: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12649: 
12650: Additional optional arguments are: $type (if role checking is to be restricted 
12651: to certain user status types -- previous (expired roles), active (currently
12652: available roles) or future (roles available in the future), and
12653: $hideprivileged -- if true will not report course roles for users who
12654: have active Domain Coordinator role in course's domain or in additional
12655: domains (specified in 'Domains to check for privileged users' in course
12656: environment -- set via:  Course Settings -> Classlists and staff listing).
12657: 
12658: =item *
12659: 
12660: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12661: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12662: $possdomains and $possroles are optional array refs -- to domains to check and
12663: roles to check.  If $possdomains is not specified, a dump will be done of the
12664: users' roles.db to check for a dc or su role in any domain. This can be
12665: time consuming if &privileged is called repeatedly (e.g., when displaying a
12666: classlist), so in such cases, supplying a $possdomains array is preferred, as
12667: this then allows &privileged_by_domain() to be used, which caches the identity
12668: of privileged users, eliminating the need for repeated calls to &dump().
12669: 
12670: =item *
12671: 
12672: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12673: where the outer hash keys are domains specified in the $possdomains array ref,
12674: next inner hash keys are privileged roles specified in the $roles array ref,
12675: and the innermost hash contains key = value pairs for username:domain = end:start
12676: for active or future "privileged" users with that role in that domain. To avoid
12677: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12678: innerhash are cached using priv_$role and $dom as the identifiers.
12679: 
12680: =back
12681: 
12682: =head2 User Modification
12683: 
12684: =over 4
12685: 
12686: =item *
12687: 
12688: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12689: user for the level given by URL.  Optional start and end dates (leave empty
12690: string or zero for "no date")
12691: 
12692: =item *
12693: 
12694: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12695: change a users, password, possible return values are: ok,
12696: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12697: refused
12698: 
12699: =item *
12700: 
12701: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12702: 
12703: =item *
12704: 
12705: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12706:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12707: 
12708: will update user information (firstname,middlename,lastname,generation,
12709: permanentemail), and if forceid is true, student/employee ID also.
12710: A user's institutional affiliation(s) can also be updated.
12711: User information fields will not be overwritten with empty entries 
12712: unless the field is included in the $candelete array reference.
12713: This array is included when a single user is modified via "Manage Users",
12714: or when Autoupdate.pl is run by cron in a domain.
12715: 
12716: =item *
12717: 
12718: modifystudent
12719: 
12720: modify a student's enrollment and identification information.
12721: The course id is resolved based on the current user's environment.  
12722: This means the invoking user must be a course coordinator or otherwise
12723: associated with a course.
12724: 
12725: This call is essentially a wrapper for lonnet::modifyuser and
12726: lonnet::modify_student_enrollment
12727: 
12728: Inputs: 
12729: 
12730: =over 4
12731: 
12732: =item B<$udom> Student's loncapa domain
12733: 
12734: =item B<$uname> Student's loncapa login name
12735: 
12736: =item B<$uid> Student/Employee ID
12737: 
12738: =item B<$umode> Student's authentication mode
12739: 
12740: =item B<$upass> Student's password
12741: 
12742: =item B<$first> Student's first name
12743: 
12744: =item B<$middle> Student's middle name
12745: 
12746: =item B<$last> Student's last name
12747: 
12748: =item B<$gene> Student's generation
12749: 
12750: =item B<$usec> Student's section in course
12751: 
12752: =item B<$end> Unix time of the roles expiration
12753: 
12754: =item B<$start> Unix time of the roles start date
12755: 
12756: =item B<$forceid> If defined, allow $uid to be changed
12757: 
12758: =item B<$desiredhome> server to use as home server for student
12759: 
12760: =item B<$email> Student's permanent e-mail address
12761: 
12762: =item B<$type> Type of enrollment (auto or manual)
12763: 
12764: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12765: 
12766: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12767: 
12768: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12769: 
12770: =item B<$context> role change context (shown in User Management Logs display in a course)
12771: 
12772: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12773: 
12774: =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.
12775: 
12776: =back
12777: 
12778: =item *
12779: 
12780: modify_student_enrollment
12781: 
12782: Change a student's enrollment status in a class.  The environment variable
12783: 'role.request.course' must be defined for this function to proceed.
12784: 
12785: Inputs:
12786: 
12787: =over 4
12788: 
12789: =item $udom, student's domain
12790: 
12791: =item $uname, student's name
12792: 
12793: =item $uid, student's user id
12794: 
12795: =item $first, student's first name
12796: 
12797: =item $middle
12798: 
12799: =item $last
12800: 
12801: =item $gene
12802: 
12803: =item $usec
12804: 
12805: =item $end
12806: 
12807: =item $start
12808: 
12809: =item $type
12810: 
12811: =item $locktype
12812: 
12813: =item $cid
12814: 
12815: =item $selfenroll
12816: 
12817: =item $context
12818: 
12819: =item $credits, number of credits student will earn from this class
12820: 
12821: =back
12822: 
12823: 
12824: =item *
12825: 
12826: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12827: custom role; give a custom role to a user for the level given by URL.  Specify
12828: name and domain of role author, and role name
12829: 
12830: =item *
12831: 
12832: revokerole($udom,$uname,$url,$role) : revoke a role for url
12833: 
12834: =item *
12835: 
12836: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12837: 
12838: =back
12839: 
12840: =head2 Course Infomation
12841: 
12842: =over 4
12843: 
12844: =item *
12845: 
12846: coursedescription($courseid,$options) : returns a hash of information about the
12847: specified course id, including all environment settings for the
12848: course, the description of the course will be in the hash under the
12849: key 'description'
12850: 
12851: $options is an optional parameter that if supplied is a hash reference that controls
12852: what how this function works.  It has the following key/values:
12853: 
12854: =over 4
12855: 
12856: =item freshen_cache
12857: 
12858: If defined, and the environment cache for the course is valid, it is 
12859: returned in the returned hash.
12860: 
12861: =item one_time
12862: 
12863: If defined, the last cache time is set to _now_
12864: 
12865: =item user
12866: 
12867: If defined, the supplied username is used instead of the current user.
12868: 
12869: 
12870: =back
12871: 
12872: =item *
12873: 
12874: resdata($name,$domain,$type,@which) : request for current parameter
12875: setting for a specific $type, where $type is either 'course' or 'user',
12876: @what should be a list of parameters to ask about. This routine caches
12877: answers for 10 minutes.
12878: 
12879: =item *
12880: 
12881: get_courseresdata($courseid, $domain) : dump the entire course resource
12882: data base, returning a hash that is keyed by the resource name and has
12883: values that are the resource value.  I believe that the timestamps and
12884: versions are also returned.
12885: 
12886: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12887: supplemental content area. This routine caches the number of files for 
12888: 10 minutes.
12889: 
12890: =back
12891: 
12892: =head2 Course Modification
12893: 
12894: =over 4
12895: 
12896: =item *
12897: 
12898: writecoursepref($courseid,%prefs) : write preferences (environment
12899: database) for a course
12900: 
12901: =item *
12902: 
12903: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12904: 
12905: =item *
12906: 
12907: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12908: 
12909: =item *
12910: 
12911: is_course($courseid), is_course($cdom, $cnum)
12912: 
12913: Accepts either a combined $courseid (in the form of domain_courseid) or the
12914: two component version $cdom, $cnum. It checks if the specified course exists.
12915: 
12916: Returns:
12917:     undef if the course doesn't exist, otherwise
12918:     in scalar context the combined courseid.
12919:     in list context the two components of the course identifier, domain and 
12920:     courseid.    
12921: 
12922: =back
12923: 
12924: =head2 Resource Subroutines
12925: 
12926: =over 4
12927: 
12928: =item *
12929: 
12930: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12931: 
12932: =item *
12933: 
12934: repcopy($filename) : subscribes to the requested file, and attempts to
12935: replicate from the owning library server, Might return
12936: 'unavailable', 'not_found', 'forbidden', 'ok', or
12937: 'bad_request', also attempts to grab the metadata for the
12938: resource. Expects the local filesystem pathname
12939: (/home/httpd/html/res/....)
12940: 
12941: =back
12942: 
12943: =head2 Resource Information
12944: 
12945: =over 4
12946: 
12947: =item *
12948: 
12949: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12950: and returns the value of a variety of different possible values,
12951: $varname should be a request string, and the other parameters can be
12952: used to specify who and what one is asking about. Ordinarily, $cid 
12953: does not need to be specified, as it is retrived from 
12954: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12955: within lonuserstate::loadmap() when initializing a course, before
12956: $env{'request.course.id'} has been set, so it needs to be provided
12957: in that one case.
12958: 
12959: Possible values for $varname are environment.lastname (or other item
12960: from the envirnment hash), user.name (or someother aspect about the
12961: user), resource.0.maxtries (or some other part and parameter of a
12962: resource)
12963: 
12964: =item *
12965: 
12966: directcondval($number) : get current value of a condition; reads from a state
12967: string
12968: 
12969: =item *
12970: 
12971: condval($condidx) : value of condition index based on state
12972: 
12973: =item *
12974: 
12975: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12976: resource's metadata, $what should be either a specific key, or either
12977: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12978: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12979: 
12980: this function automatically caches all requests
12981: 
12982: =item *
12983: 
12984: metadata_query($query,$custom,$customshow) : make a metadata query against the
12985: network of library servers; returns file handle of where SQL and regex results
12986: will be stored for query
12987: 
12988: =item *
12989: 
12990: symbread($filename) : return symbolic list entry (filename argument optional);
12991: returns the data handle
12992: 
12993: =item *
12994: 
12995: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12996: and is a possible symb for the URL in $thisfn, and if is an encrypted
12997: resource that the user accessed using /enc/ returns a 1 on success, 0
12998: on failure, user must be in a course, as it assumes the existence of
12999: the course initial hash, and uses $env('request.course.id'}.  The third
13000: arg is an optional reference to a scalar.  If this arg is passed in the 
13001: call to symbverify, it will be set to 1 if the symb has been set to be 
13002: encrypted; otherwise it will be null.  
13003: 
13004: =item *
13005: 
13006: symbclean($symb) : removes versions numbers from a symb, returns the
13007: cleaned symb
13008: 
13009: =item *
13010: 
13011: is_on_map($uri) : checks if the $uri is somewhere on the current
13012: course map, user must be in a course for it to work.
13013: 
13014: =item *
13015: 
13016: numval($salt) : return random seed value (addend for rndseed)
13017: 
13018: =item *
13019: 
13020: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13021: a random seed, all arguments are optional, if they aren't sent it uses the
13022: environment to derive them. Note: if symb isn't sent and it can't get one
13023: from &symbread it will use the current time as its return value
13024: 
13025: =item *
13026: 
13027: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13028: unfakeable, receipt
13029: 
13030: =item *
13031: 
13032: receipt() : API to ireceipt working off of env values; given out to users
13033: 
13034: =item *
13035: 
13036: countacc($url) : count the number of accesses to a given URL
13037: 
13038: =item *
13039: 
13040: 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
13041: 
13042: =item *
13043: 
13044: 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)
13045: 
13046: =item *
13047: 
13048: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13049: 
13050: =item *
13051: 
13052: devalidate($symb) : devalidate temporary spreadsheet calculations,
13053: forcing spreadsheet to reevaluate the resource scores next time.
13054: 
13055: =item * 
13056: 
13057: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13058: when viewing in course context.
13059: 
13060:  input: six args -- filename (decluttered), course number, course domain,
13061:                     url, symb (if registered) and group (if this is a 
13062:                     group item -- e.g., bulletin board, group page etc.).
13063: 
13064:  output: array of five scalars --
13065:          $cfile -- url for file editing if editable on current server
13066:          $home -- homeserver of resource (i.e., for author if published,
13067:                                           or course if uploaded.).
13068:          $switchserver --  1 if server switch will be needed.
13069:          $forceedit -- 1 if icon/link should be to go to edit mode 
13070:          $forceview -- 1 if icon/link should be to go to view mode
13071: 
13072: =item *
13073: 
13074: is_course_upload($file,$cnum,$cdom)
13075: 
13076: Used in course context to determine if current file was uploaded to 
13077: the course (i.e., would be found in /userfiles/docs on the course's 
13078: homeserver.
13079: 
13080:   input: 3 args -- filename (decluttered), course number and course domain.
13081:   output: boolean -- 1 if file was uploaded.
13082: 
13083: =back
13084: 
13085: =head2 Storing/Retreiving Data
13086: 
13087: =over 4
13088: 
13089: =item *
13090: 
13091: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13092: for this url; hashref needs to be given and should be a \%hashname; the
13093: remaining args aren't required and if they aren't passed or are '' they will
13094: be derived from the env
13095: 
13096: =item *
13097: 
13098: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13099: uses critical subroutine
13100: 
13101: =item *
13102: 
13103: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13104: all args are optional
13105: 
13106: =item *
13107: 
13108: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13109: dumps the complete (or key matching regexp) namespace into a hash
13110: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13111: normally &store()ed into
13112: 
13113: $range should be either an integer '100' (give me the first 100
13114:                                            matching records)
13115:               or be  two integers sperated by a - with no spaces
13116:                  '30-50' (give me the 30th through the 50th matching
13117:                           records)
13118: 
13119: 
13120: =item *
13121: 
13122: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13123: replaces a &store() version of data with a replacement set of data
13124: for a particular resource in a namespace passed in the $storehash hash 
13125: reference
13126: 
13127: =item *
13128: 
13129: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13130: works very similar to store/cstore, but all data is stored in a
13131: temporary location and can be reset using tmpreset, $storehash should
13132: be a hash reference, returns nothing on success
13133: 
13134: =item *
13135: 
13136: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13137: similar to restore, but all data is stored in a temporary location and
13138: can be reset using tmpreset. Returns a hash of values on success,
13139: error string otherwise.
13140: 
13141: =item *
13142: 
13143: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13144: deltes all keys for $symb form the temporary storage hash.
13145: 
13146: =item *
13147: 
13148: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13149: reference filled in from namesp ($udom and $uname are optional)
13150: 
13151: =item *
13152: 
13153: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13154: namesp ($udom and $uname are optional)
13155: 
13156: =item *
13157: 
13158: dump($namespace,$udom,$uname,$regexp,$range) : 
13159: dumps the complete (or key matching regexp) namespace into a hash
13160: ($udom, $uname, $regexp, $range are optional)
13161: 
13162: $range should be either an integer '100' (give me the first 100
13163:                                            matching records)
13164:               or be  two integers sperated by a - with no spaces
13165:                  '30-50' (give me the 30th through the 50th matching
13166:                           records)
13167: =item *
13168: 
13169: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13170: $store can be a scalar, an array reference, or if the amount to be 
13171: incremented is > 1, a hash reference.
13172: 
13173: ($udom and $uname are optional)
13174: 
13175: =item *
13176: 
13177: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13178: ($udom and $uname are optional)
13179: 
13180: =item *
13181: 
13182: cput($namespace,$storehash,$udom,$uname) : critical put
13183: ($udom and $uname are optional)
13184: 
13185: =item *
13186: 
13187: newput($namespace,$storehash,$udom,$uname) :
13188: 
13189: Attempts to store the items in the $storehash, but only if they don't
13190: currently exist, if this succeeds you can be certain that you have 
13191: successfully created a new key value pair in the $namespace db.
13192: 
13193: 
13194: Args:
13195:  $namespace: name of database to store values to
13196:  $storehash: hashref to store to the db
13197:  $udom: (optional) domain of user containing the db
13198:  $uname: (optional) name of user caontaining the db
13199: 
13200: Returns:
13201:  'ok' -> succeeded in storing all keys of $storehash
13202:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13203:                         least <key> already existed in the db (other
13204:                         requested keys may also already exist)
13205:  'error: <msg>' -> unable to tie the DB or other error occurred
13206:  'con_lost' -> unable to contact request server
13207:  'refused' -> action was not allowed by remote machine
13208: 
13209: 
13210: =item *
13211: 
13212: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13213: reference filled in from namesp (encrypts the return communication)
13214: ($udom and $uname are optional)
13215: 
13216: =item *
13217: 
13218: log($udom,$name,$home,$message) : write to permanent log for user; use
13219: critical subroutine
13220: 
13221: =item *
13222: 
13223: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13224: array reference filled in from namespace found in domain level on either
13225: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13226: 
13227: =item *
13228: 
13229: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13230: domain level either on specified domain server ($uhome) or primary domain 
13231: server ($udom and $uhome are optional)
13232: 
13233: =item * 
13234: 
13235: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13236: for: authentication, language, quotas, timezone, date locale, and portal URL in
13237: the target domain.
13238: 
13239: May also include additional key => value pairs for the following groups:
13240: 
13241: =over
13242: 
13243: =item
13244: disk quotas (MB allocated by default to portfolios and authoring spaces).
13245: 
13246: =over
13247: 
13248: =item defaultquota, authorquota
13249: 
13250: =back
13251: 
13252: =item
13253: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13254: portfolio for users).
13255: 
13256: =over
13257: 
13258: =item
13259: aboutme, blog, webdav, portfolio
13260: 
13261: =back
13262: 
13263: =item
13264: requestcourses: ability to request courses, and how requests are processed.
13265: 
13266: =over
13267: 
13268: =item
13269: official, unofficial, community
13270: 
13271: =back
13272: 
13273: =item
13274: inststatus: types of institutional affiliation, and order in which they are displayed.
13275: 
13276: =over
13277: 
13278: =item
13279: inststatustypes, inststatusorder
13280: 
13281: =back
13282: 
13283: =item
13284: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13285: for course's uploaded content.
13286: 
13287: =over
13288: 
13289: =item
13290: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13291: 
13292: =back
13293: 
13294: =item
13295: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13296: on your servers.
13297: 
13298: =over
13299: 
13300: =item 
13301: remotesessions, hostedsessions
13302: 
13303: =back
13304: 
13305: =back
13306: 
13307: In cases where a domain coordinator has never used the "Set Domain Configuration"
13308: utility to create a configuration.db file on a domain's primary library server 
13309: only the following domain defaults: auth_def, auth_arg_def, lang_def
13310: -- corresponding values are authentication type (internal, krb4, krb5,
13311: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13312: will be available. Values are retrieved from cache (if current), unless the
13313: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13314: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13315: 
13316: Typical usage:
13317: 
13318: %domdefaults = &get_domain_defaults($target_domain);
13319: 
13320: =back
13321: 
13322: =head2 Network Status Functions
13323: 
13324: =over 4
13325: 
13326: =item *
13327: 
13328: dirlist() : return directory list based on URI (first arg).
13329: 
13330: Inputs: 1 required, 5 optional.
13331: 
13332: =over
13333: 
13334: =item 
13335: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13336: 
13337: =item
13338: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13339: 
13340: =item
13341: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13342: 
13343: =item
13344: $getpropath - boolean: 1 if prepend path using &propath(). 
13345: 
13346: =item
13347: $getuserdir - boolean: 1 if prepend path for "userfiles".
13348: 
13349: =item 
13350: $alternateRoot - path to prepend in place of path from $uri.
13351: 
13352: =back
13353: 
13354: Returns: Array of up to two items.
13355: 
13356: =over
13357: 
13358: a reference to an array of files/subdirectories
13359: 
13360: =over
13361: 
13362: Each element in the array of files/subdirectories is a & separated list of
13363: item name and the result of running stat on the item.  If dirlist was requested
13364: for a file instead of a directory, the item name will be ''. For a directory 
13365: listing, if the item is a metadata file, the element will end &N&M 
13366: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13367: default copyright set (1).  
13368: 
13369: =back
13370: 
13371: a scalar containing error condition (if encountered).
13372: 
13373: =over
13374: 
13375: =item 
13376: no_host (no homeserver identified for $username:$domain).
13377: 
13378: =item 
13379: no_such_host (server contacted for listing not identified as valid host).
13380: 
13381: =item 
13382: con_lost (connection to remote server failed).
13383: 
13384: =item 
13385: refused (invalid $username:$domain received on lond side).
13386: 
13387: =item 
13388: no_such_dir (directory at specified path on lond side does not exist). 
13389: 
13390: =item 
13391: empty (directory at specified path on lond side is empty).
13392: 
13393: =over
13394: 
13395: This is currently not encountered because the &ls3, &ls2, 
13396: &ls (_handler) routines on the lond side do not filter out
13397: . and .. from a directory listing. 
13398: 
13399: =back
13400: 
13401: =back
13402: 
13403: =back
13404: 
13405: =item *
13406: 
13407: spareserver() : find server with least workload from spare.tab
13408: 
13409: 
13410: =item *
13411: 
13412: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13413: if there is no corresponding loncapa host.
13414: 
13415: =back
13416: 
13417: 
13418: =head2 Apache Request
13419: 
13420: =over 4
13421: 
13422: =item *
13423: 
13424: ssi($url,%hash) : server side include, does a complete request cycle on url to
13425: localhost, posts hash
13426: 
13427: =back
13428: 
13429: =head2 Data to String to Data
13430: 
13431: =over 4
13432: 
13433: =item *
13434: 
13435: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13436: and '&' separators, supports elements that are arrayrefs and hashrefs
13437: 
13438: =item *
13439: 
13440: hashref2str($hashref) : convert a hashref into a string complete with
13441: escaping and '=' and '&' separators, supports elements that are
13442: arrayrefs and hashrefs
13443: 
13444: =item *
13445: 
13446: arrayref2str($arrayref) : convert an arrayref into a string complete
13447: with escaping and '&' separators, supports elements that are arrayrefs
13448: and hashrefs
13449: 
13450: =item *
13451: 
13452: str2hash($string) : convert string to hash using unescaping and
13453: splitting on '=' and '&', supports elements that are arrayrefs and
13454: hashrefs
13455: 
13456: =item *
13457: 
13458: str2array($string) : convert string to hash using unescaping and
13459: splitting on '&', supports elements that are arrayrefs and hashrefs
13460: 
13461: =back
13462: 
13463: =head2 Logging Routines
13464: 
13465: 
13466: These routines allow one to make log messages in the lonnet.log and
13467: lonnet.perm logfiles.
13468: 
13469: =over 4
13470: 
13471: =item *
13472: 
13473: logtouch() : make sure the logfile, lonnet.log, exists
13474: 
13475: =item *
13476: 
13477: logthis() : append message to the normal lonnet.log file, it gets
13478: preiodically rolled over and deleted.
13479: 
13480: =item *
13481: 
13482: logperm() : append a permanent message to lonnet.perm.log, this log
13483: file never gets deleted by any automated portion of the system, only
13484: messages of critical importance should go in here.
13485: 
13486: 
13487: =back
13488: 
13489: =head2 General File Helper Routines
13490: 
13491: =over 4
13492: 
13493: =item *
13494: 
13495: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13496: (a) files in /uploaded
13497:   (i) If a local copy of the file exists - 
13498:       compares modification date of local copy with last-modified date for 
13499:       definitive version stored on home server for course. If local copy is 
13500:       stale, requests a new version from the home server and stores it. 
13501:       If the original has been removed from the home server, then local copy 
13502:       is unlinked.
13503:   (ii) If local copy does not exist -
13504:       requests the file from the home server and stores it. 
13505:   
13506:   If $caller is 'uploadrep':  
13507:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13508:     for request for files originally uploaded via DOCS. 
13509:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13510:   
13511:   Otherwise:
13512:      This indicates a call from the content generation phase of the request.
13513:      -  returns the entire contents of the file or -1.
13514:      
13515: (b) files in /res
13516:    - returns the entire contents of a file or -1; 
13517:    it properly subscribes to and replicates the file if neccessary.
13518: 
13519: 
13520: =item *
13521: 
13522: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13523:                   reference
13524: 
13525: returns either a stat() list of data about the file or an empty list
13526: if the file doesn't exist or couldn't find out about it (connection
13527: problems or user unknown)
13528: 
13529: =item *
13530: 
13531: filelocation($dir,$file) : returns file system location of a file
13532: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13533: directory that relative $file lookups are to looked in ($dir of /a/dir
13534: and a file of ../bob will become /a/bob)
13535: 
13536: =item *
13537: 
13538: hreflocation($dir,$file) : returns file system location or a URL; same as
13539: filelocation except for hrefs
13540: 
13541: =item *
13542: 
13543: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13544: 
13545: =back
13546: 
13547: =head2 Usererfile file routines (/uploaded*)
13548: 
13549: =over 4
13550: 
13551: =item *
13552: 
13553: userfileupload(): main rotine for putting a file in a user or course's
13554:                   filespace, arguments are,
13555: 
13556:  formname - required - this is the name of the element in $env where the
13557:            filename, and the contents of the file to create/modifed exist
13558:            the filename is in $env{'form.'.$formname.'.filename'} and the
13559:            contents of the file is located in $env{'form.'.$formname}
13560:  context - if coursedoc, store the file in the course of the active role
13561:              of the current user; 
13562:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13563:            if 'canceloverwrite': delete file in tmp/overwrites directory
13564:  subdir - required - subdirectory to put the file in under ../userfiles/
13565:          if undefined, it will be placed in "unknown"
13566: 
13567:  (This routine calls clean_filename() to remove any dangerous
13568:  characters from the filename, and then calls finuserfileupload() to
13569:  complete the transaction)
13570: 
13571:  returns either the url of the uploaded file (/uploaded/....) if successful
13572:  and /adm/notfound.html if unsuccessful
13573: 
13574: =item *
13575: 
13576: clean_filename(): routine for cleaing a filename up for storage in
13577:                  userfile space, argument is:
13578: 
13579:  filename - proposed filename
13580: 
13581: returns: the new clean filename
13582: 
13583: =item *
13584: 
13585: finishuserfileupload(): routine that creates and sends the file to
13586: userspace, probably shouldn't be called directly
13587: 
13588:   docuname: username or courseid of destination for the file
13589:   docudom: domain of user/course of destination for the file
13590:   formname: same as for userfileupload()
13591:   fname: filename (including subdirectories) for the file
13592:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13593:   allfiles: reference to hash used to store objects found by parser
13594:   codebase: reference to hash used for codebases of java objects found by parser
13595:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13596:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13597:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13598:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13599:   context: if 'overwrite', will move the uploaded file from its temporary location to
13600:             userfiles to facilitate overwriting a previously uploaded file with same name.
13601:   mimetype: reference to scalar to accommodate mime type determined
13602:             from File::MMagic if $parser = parse.
13603: 
13604:  returns either the url of the uploaded file (/uploaded/....) if successful
13605:  and /adm/notfound.html if unsuccessful (or an error message if context 
13606:  was 'overwrite').
13607:  
13608: 
13609: =item *
13610: 
13611: renameuserfile(): renames an existing userfile to a new name
13612: 
13613:   Args:
13614:    docuname: username or courseid of destination for the file
13615:    docudom: domain of user/course of destination for the file
13616:    old: current file name (including any subdirs under userfiles)
13617:    new: desired file name (including any subdirs under userfiles)
13618: 
13619: =item *
13620: 
13621: mkdiruserfile(): creates a directory is a userfiles dir
13622: 
13623:   Args:
13624:    docuname: username or courseid of destination for the file
13625:    docudom: domain of user/course of destination for the file
13626:    dir: dir to create (including any subdirs under userfiles)
13627: 
13628: =item *
13629: 
13630: removeuserfile(): removes a file that exists in userfiles
13631: 
13632:   Args:
13633:    docuname: username or courseid of destination for the file
13634:    docudom: domain of user/course of destination for the file
13635:    fname: filname to delete (including any subdirs under userfiles)
13636: 
13637: =item *
13638: 
13639: removeuploadedurl(): convience function for removeuserfile()
13640: 
13641:   Args:
13642:    url:  a full /uploaded/... url to delete
13643: 
13644: =item * 
13645: 
13646: get_portfile_permissions():
13647:   Args:
13648:     domain: domain of user or course contain the portfolio files
13649:     user: name of user or num of course contain the portfolio files
13650:   Returns:
13651:     hashref of a dump of the proper file_permissions.db
13652:    
13653: 
13654: =item * 
13655: 
13656: get_access_controls():
13657: 
13658: Args:
13659:   current_permissions: the hash ref returned from get_portfile_permissions()
13660:   group: (optional) the group you want the files associated with
13661:   file: (optional) the file you want access info on
13662: 
13663: Returns:
13664:     a hash (keys are file names) of hashes containing
13665:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13666:         values are XML containing access control settings (see below) 
13667: 
13668: Internal notes:
13669: 
13670:  access controls are stored in file_permissions.db as key=value pairs.
13671:     key -> path to file/file_name\0uniqueID:scope_end_start
13672:         where scope -> public,guest,course,group,domains or users.
13673:               end -> UNIX time for end of access (0 -> no end date)
13674:               start -> UNIX time for start of access
13675: 
13676:     value -> XML description of access control
13677:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13678:             <start></start>
13679:             <end></end>
13680: 
13681:             <password></password>  for scope type = guest
13682: 
13683:             <domain></domain>     for scope type = course or group
13684:             <number></number>
13685:             <roles id="">
13686:              <role></role>
13687:              <access></access>
13688:              <section></section>
13689:              <group></group>
13690:             </roles>
13691: 
13692:             <dom></dom>         for scope type = domains
13693: 
13694:             <users>             for scope type = users
13695:              <user>
13696:               <uname></uname>
13697:               <udom></udom>
13698:              </user>
13699:             </users>
13700:            </scope> 
13701:               
13702:  Access data is also aggregated for each file in an additional key=value pair:
13703:  key -> path to file/file_name\0accesscontrol 
13704:  value -> reference to hash
13705:           hash contains key = value pairs
13706:           where key = uniqueID:scope_end_start
13707:                 value = UNIX time record was last updated
13708: 
13709:           Used to improve speed of look-ups of access controls for each file.  
13710:  
13711:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13712: 
13713: =item *
13714: 
13715: modify_access_controls():
13716: 
13717: Modifies access controls for a portfolio file
13718: Args
13719: 1. file name
13720: 2. reference to hash of required changes,
13721: 3. domain
13722: 4. username
13723:   where domain,username are the domain of the portfolio owner 
13724:   (either a user or a course) 
13725: 
13726: Returns:
13727: 1. result of additions or updates ('ok' or 'error', with error message). 
13728: 2. result of deletions ('ok' or 'error', with error message).
13729: 3. reference to hash of any new or updated access controls.
13730: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13731:    key = integer (inbound ID)
13732:    value = uniqueID
13733: 
13734: =item *
13735: 
13736: get_timebased_id():
13737: 
13738: Attempts to get a unique timestamp-based suffix for use with items added to a 
13739: course via the Course Editor (e.g., folders, composite pages, 
13740: group bulletin boards).
13741: 
13742: Args: (first three required; six others optional)
13743: 
13744: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13745:    docssequence, or name of group
13746: 
13747: 2. keyid (alphanumeric): name of temporary locking key in hash,
13748:    e.g., num, boardids
13749: 
13750: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13751:    file will be named nohist_namespace.db
13752: 
13753: 4. cdom: domain of course; default is current course domain from %env
13754: 
13755: 5. cnum: course number; default is current course number from %env
13756: 
13757: 6. idtype: set to concat if an additional digit is to be appended to the 
13758:    unix timestamp to form the suffix, if the plain timestamp is already
13759:    in use.  Default is to not do this, but simply increment the unix 
13760:    timestamp by 1 until a unique key is obtained.
13761: 
13762: 7. who: holder of locking key; defaults to user:domain for user.
13763: 
13764: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13765:    retrying); default is 3.
13766: 
13767: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13768: 
13769: Returns:
13770: 
13771: 1. suffix obtained (numeric)
13772: 
13773: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13774: 
13775: 3. error: contains (localized) error message if an error occurred.
13776: 
13777: 
13778: =back
13779: 
13780: =head2 HTTP Helper Routines
13781: 
13782: =over 4
13783: 
13784: =item *
13785: 
13786: escape() : unpack non-word characters into CGI-compatible hex codes
13787: 
13788: =item *
13789: 
13790: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13791: 
13792: =back
13793: 
13794: =head1 PRIVATE SUBROUTINES
13795: 
13796: =head2 Underlying communication routines (Shouldn't call)
13797: 
13798: =over 4
13799: 
13800: =item *
13801: 
13802: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13803: 
13804: =item *
13805: 
13806: reply() : uses subreply to send a message to remote machine, logs all failures
13807: 
13808: =item *
13809: 
13810: critical() : passes a critical message to another server; if cannot
13811: get through then place message in connection buffer directory and
13812: returns con_delayed, if incapable of saving message, returns
13813: con_failed
13814: 
13815: =item *
13816: 
13817: reconlonc() : tries to reconnect lonc client processes.
13818: 
13819: =back
13820: 
13821: =head2 Resource Access Logging
13822: 
13823: =over 4
13824: 
13825: =item *
13826: 
13827: flushcourselogs() : flush (save) buffer logs and access logs
13828: 
13829: =item *
13830: 
13831: courselog($what) : save message for course in hash
13832: 
13833: =item *
13834: 
13835: courseacclog($what) : save message for course using &courselog().  Perform
13836: special processing for specific resource types (problems, exams, quizzes, etc).
13837: 
13838: =item *
13839: 
13840: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13841: as a PerlChildExitHandler
13842: 
13843: =back
13844: 
13845: =head2 Other
13846: 
13847: =over 4
13848: 
13849: =item *
13850: 
13851: symblist($mapname,%newhash) : update symbolic storage links
13852: 
13853: =back
13854: 
13855: =cut
13856: 

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