File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1244: download - view: text, annotated - select for diffs
Thu Dec 5 05:19:18 2013 UTC (10 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support Apache 2.4 (Fedora 18, 19, 20; SuSE 13.1)
  - $r->user needs to be set in lonnet::check_for_valid_session()
    if the session is valid, but lonacc:sso_login() also needs to be able
    to identify an SSO case.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1244 2013/12/05 05:19:18 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$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,$userref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640:     if ($apache >= 2.4) {
  641:         if ($r->user() eq '') {
  642:             if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  643:                 $r->user($disk_env{'user.name'});
  644:             } else {
  645:                 $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  646:             }
  647:         }
  648:         if (($r->user() ne '') && (ref($userref))) {
  649:             $$userref = $r->user();
  650:         }
  651:     }
  652:     return $handle;
  653: }
  654: 
  655: sub timed_flock {
  656:     my ($file,$lock_type) = @_;
  657:     my $failed=0;
  658:     eval {
  659: 	local $SIG{__DIE__}='DEFAULT';
  660: 	local $SIG{ALRM}=sub {
  661: 	    $failed=1;
  662: 	    die("failed lock");
  663: 	};
  664: 	alarm(13);
  665: 	flock($file,$lock_type);
  666: 	alarm(0);
  667:     };
  668:     if ($failed) {
  669: 	return undef;
  670:     } else {
  671: 	return 1;
  672:     }
  673: }
  674: 
  675: # ---------------------------------------------------------- Append Environment
  676: 
  677: sub appenv {
  678:     my ($newenv,$roles) = @_;
  679:     if (ref($newenv) eq 'HASH') {
  680:         foreach my $key (keys(%{$newenv})) {
  681:             my $refused = 0;
  682: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  683:                 $refused = 1;
  684:                 if (ref($roles) eq 'ARRAY') {
  685:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  686:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  687:                         $refused = 0;
  688:                     }
  689:                 }
  690:             }
  691:             if ($refused) {
  692:                 &logthis("<font color=\"blue\">WARNING: ".
  693:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  694:                          .'</font>');
  695: 	        delete($newenv->{$key});
  696:             } else {
  697:                 $env{$key}=$newenv->{$key};
  698:             }
  699:         }
  700:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  701:         if ($opened
  702: 	    && &timed_flock($env_file,LOCK_EX)
  703: 	    &&
  704: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  705: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  706: 	    while (my ($key,$value) = each(%{$newenv})) {
  707: 	        $disk_env{$key} = $value;
  708: 	    }
  709: 	    untie(%disk_env);
  710:         }
  711:     }
  712:     return 'ok';
  713: }
  714: # ----------------------------------------------------- Delete from Environment
  715: 
  716: sub delenv {
  717:     my ($delthis,$regexp,$roles) = @_;
  718:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  719:         my $refused = 1;
  720:         if (ref($roles) eq 'ARRAY') {
  721:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  722:             if (grep(/^\Q$role\E$/,@{$roles})) {
  723:                 $refused = 0;
  724:             }
  725:         }
  726:         if ($refused) {
  727:             &logthis("<font color=\"blue\">WARNING: ".
  728:                      "Attempt to delete from environment ".$delthis);
  729:             return 'error';
  730:         }
  731:     }
  732:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  733:     if ($opened
  734: 	&& &timed_flock($env_file,LOCK_EX)
  735: 	&&
  736: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  737: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  738: 	foreach my $key (keys(%disk_env)) {
  739: 	    if ($regexp) {
  740:                 if ($key=~/^$delthis/) {
  741:                     delete($env{$key});
  742:                     delete($disk_env{$key});
  743:                 } 
  744:             } else {
  745:                 if ($key=~/^\Q$delthis\E/) {
  746: 		    delete($env{$key});
  747: 		    delete($disk_env{$key});
  748: 	        }
  749:             }
  750: 	}
  751: 	untie(%disk_env);
  752:     }
  753:     return 'ok';
  754: }
  755: 
  756: sub get_env_multiple {
  757:     my ($name) = @_;
  758:     my @values;
  759:     if (defined($env{$name})) {
  760:         # exists is it an array
  761:         if (ref($env{$name})) {
  762:             @values=@{ $env{$name} };
  763:         } else {
  764:             $values[0]=$env{$name};
  765:         }
  766:     }
  767:     return(@values);
  768: }
  769: 
  770: # ------------------------------------------------------------------- Locking
  771: 
  772: sub set_lock {
  773:     my ($text)=@_;
  774:     $locknum++;
  775:     my $id=$$.'-'.$locknum;
  776:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  777:              'session.lock.'.$id => $text});
  778:     return $id;
  779: }
  780: 
  781: sub get_locks {
  782:     my $num=0;
  783:     my %texts=();
  784:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  785:        if ($lock=~/\w/) {
  786:           $num++;
  787:           $texts{$lock}=$env{'session.lock.'.$lock};
  788:        }
  789:    }
  790:    return ($num,%texts);
  791: }
  792: 
  793: sub remove_lock {
  794:     my ($id)=@_;
  795:     my $newlocks='';
  796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  797:        if (($lock=~/\w/) && ($lock ne $id)) {
  798:           $newlocks.=','.$lock;
  799:        }
  800:     }
  801:     &appenv({'session.locks' => $newlocks});
  802:     &delenv('session.lock.'.$id);
  803: }
  804: 
  805: sub remove_all_locks {
  806:     my $activelocks=$env{'session.locks'};
  807:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  808:        if ($lock=~/\w/) {
  809:           &remove_lock($lock);
  810:        }
  811:     }
  812: }
  813: 
  814: 
  815: # ------------------------------------------ Find out current server userload
  816: sub userload {
  817:     my $numusers=0;
  818:     {
  819: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  820: 	my $filename;
  821: 	my $curtime=time;
  822: 	while ($filename=readdir(LONIDS)) {
  823: 	    next if ($filename eq '.' || $filename eq '..');
  824: 	    next if ($filename =~ /publicuser_\d+\.id/);
  825: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  826: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  827: 	}
  828: 	closedir(LONIDS);
  829:     }
  830:     my $userloadpercent=0;
  831:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  832:     if ($maxuserload) {
  833: 	$userloadpercent=100*$numusers/$maxuserload;
  834:     }
  835:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  836:     return $userloadpercent;
  837: }
  838: 
  839: # ------------------------------ Find server with least workload from spare.tab
  840: 
  841: sub spareserver {
  842:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  843:     my $spare_server;
  844:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  845:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  846:                                                      :  $userloadpercent;
  847:     my ($uint_dom,$remotesessions);
  848:     if (($udom ne '') && (&domain($udom) ne '')) {
  849:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  850:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  851:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  852:         $remotesessions = $udomdefaults{'remotesessions'};
  853:     }
  854:     my $spareshash = &this_host_spares($udom);
  855:     if (ref($spareshash) eq 'HASH') {
  856:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  857:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  858:                 if ($uint_dom) {
  859:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  860:                                                  $try_server));
  861:                 }
  862: 	        ($spare_server, $lowest_load) =
  863: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  864:             }
  865:         }
  866: 
  867:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  868: 
  869:         if (!$found_server) {
  870:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  871: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  872:                     if ($uint_dom) {
  873:                         next unless (&spare_can_host($udom,$uint_dom,
  874:                                                      $remotesessions,$try_server));
  875:                     }
  876: 	            ($spare_server, $lowest_load) =
  877: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  878:                 }
  879: 	    }
  880:         }
  881:     }
  882: 
  883:     if (!$want_server_name) {
  884:         my $protocol = 'http';
  885:         if ($protocol{$spare_server} eq 'https') {
  886:             $protocol = $protocol{$spare_server};
  887:         }
  888:         if (defined($spare_server)) {
  889:             my $hostname = &hostname($spare_server);
  890:             if (defined($hostname)) {
  891: 	        $spare_server = $protocol.'://'.$hostname;
  892:             }
  893:         }
  894:     }
  895:     return $spare_server;
  896: }
  897: 
  898: sub compare_server_load {
  899:     my ($try_server, $spare_server, $lowest_load) = @_;
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect);
  965:     foreach my $lonhost (keys(%servers)) {
  966:         my $loginvia;
  967:         if ($checkloginvia) {
  968:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  969:             if ($loginvia) {
  970:                 my ($server,$path) = split(/:/,$loginvia);
  971:                 ($login_host, $lowest_load) =
  972:                     &compare_server_load($server, $login_host, $lowest_load);
  973:                 if ($login_host eq $server) {
  974:                     $portal_path = $path;
  975:                     $isredirect = 1;
  976:                 }
  977:             } else {
  978:                 ($login_host, $lowest_load) =
  979:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  980:                 if ($login_host eq $lonhost) {
  981:                     $portal_path = '';
  982:                     $isredirect = ''; 
  983:                 }
  984:             }
  985:         } else {
  986:             ($login_host, $lowest_load) =
  987:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  988:         }
  989:     }
  990:     if ($login_host ne '') {
  991:         $hostname = &hostname($login_host);
  992:     }
  993:     return ($login_host,$hostname,$portal_path,$isredirect);
  994: }
  995: 
  996: # --------------------------------------------- Try to change a user's password
  997: 
  998: sub changepass {
  999:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1000:     $currentpass = &escape($currentpass);
 1001:     $newpass     = &escape($newpass);
 1002:     my $lonhost = $perlvar{'lonHostID'};
 1003:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1004: 		       $server);
 1005:     if (! $answer) {
 1006: 	&logthis("No reply on password change request to $server ".
 1007: 		 "by $uname in domain $udom.");
 1008:     } elsif ($answer =~ "^ok") {
 1009:         &logthis("$uname in $udom successfully changed their password ".
 1010: 		 "on $server.");
 1011:     } elsif ($answer =~ "^pwchange_failure") {
 1012: 	&logthis("$uname in $udom was unable to change their password ".
 1013: 		 "on $server.  The action was blocked by either lcpasswd ".
 1014: 		 "or pwchange");
 1015:     } elsif ($answer =~ "^non_authorized") {
 1016:         &logthis("$uname in $udom did not get their password correct when ".
 1017: 		 "attempting to change it on $server.");
 1018:     } elsif ($answer =~ "^auth_mode_error") {
 1019:         &logthis("$uname in $udom attempted to change their password despite ".
 1020: 		 "not being locally or internally authenticated on $server.");
 1021:     } elsif ($answer =~ "^unknown_user") {
 1022:         &logthis("$uname in $udom attempted to change their password ".
 1023: 		 "on $server but were unable to because $server is not ".
 1024: 		 "their home server.");
 1025:     } elsif ($answer =~ "^refused") {
 1026: 	&logthis("$server refused to change $uname in $udom password because ".
 1027: 		 "it was sent an unencrypted request to change the password.");
 1028:     } elsif ($answer =~ "invalid_client") {
 1029:         &logthis("$server refused to change $uname in $udom password because ".
 1030:                  "it was a reset by e-mail originating from an invalid server.");
 1031:     }
 1032:     return $answer;
 1033: }
 1034: 
 1035: # ----------------------- Try to determine user's current authentication scheme
 1036: 
 1037: sub queryauthenticate {
 1038:     my ($uname,$udom)=@_;
 1039:     my $uhome=&homeserver($uname,$udom);
 1040:     if (!$uhome) {
 1041: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1042: 	return 'no_host';
 1043:     }
 1044:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1045:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1046: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1047:     }
 1048:     return $answer;
 1049: }
 1050: 
 1051: # --------- Try to authenticate user from domain's lib servers (first this one)
 1052: 
 1053: sub authenticate {
 1054:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1055:     $upass=&escape($upass);
 1056:     $uname= &LONCAPA::clean_username($uname);
 1057:     my $uhome=&homeserver($uname,$udom,1);
 1058:     my $newhome;
 1059:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1060: # Maybe the machine was offline and only re-appeared again recently?
 1061:         &reconlonc();
 1062: # One more
 1063: 	$uhome=&homeserver($uname,$udom,1);
 1064:         if (($uhome eq 'no_host') && $checkdefauth) {
 1065:             if (defined(&domain($udom,'primary'))) {
 1066:                 $newhome=&domain($udom,'primary');
 1067:             }
 1068:             if ($newhome ne '') {
 1069:                 $uhome = $newhome;
 1070:             }
 1071:         }
 1072: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1073: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1074: 	    return 'no_host';
 1075:         }
 1076:     }
 1077:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1078:     if ($answer eq 'authorized') {
 1079:         if ($newhome) {
 1080:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1081:             return 'no_account_on_host'; 
 1082:         } else {
 1083:             &logthis("User $uname at $udom authorized by $uhome");
 1084:             return $uhome;
 1085:         }
 1086:     }
 1087:     if ($answer eq 'non_authorized') {
 1088: 	&logthis("User $uname at $udom rejected by $uhome");
 1089: 	return 'no_host'; 
 1090:     }
 1091:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1092:     return 'no_host';
 1093: }
 1094: 
 1095: sub can_host_session {
 1096:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1097:     my $canhost = 1;
 1098:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1099:     if (ref($remotesessions) eq 'HASH') {
 1100:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1101:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1102:                 $canhost = 0;
 1103:             } else {
 1104:                 $canhost = 1;
 1105:             }
 1106:         }
 1107:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1108:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1109:                 $canhost = 1;
 1110:             } else {
 1111:                 $canhost = 0;
 1112:             }
 1113:         }
 1114:         if ($canhost) {
 1115:             if ($remotesessions->{'version'} ne '') {
 1116:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1117:                 if ($reqmajor ne '' && $reqminor ne '') {
 1118:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1119:                         my $major = $1;
 1120:                         my $minor = $2;
 1121:                         if (($major < $reqmajor ) ||
 1122:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1123:                             $canhost = 0;
 1124:                         }
 1125:                     } else {
 1126:                         $canhost = 0;
 1127:                     }
 1128:                 }
 1129:             }
 1130:         }
 1131:     }
 1132:     if ($canhost) {
 1133:         if (ref($hostedsessions) eq 'HASH') {
 1134:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1135:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1136:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1137:                 if (($uint_dom ne '') && 
 1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1139:                     $canhost = 0;
 1140:                 } else {
 1141:                     $canhost = 1;
 1142:                 }
 1143:             }
 1144:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1145:                 if (($uint_dom ne '') && 
 1146:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1147:                     $canhost = 1;
 1148:                 } else {
 1149:                     $canhost = 0;
 1150:                 }
 1151:             }
 1152:         }
 1153:     }
 1154:     return $canhost;
 1155: }
 1156: 
 1157: sub spare_can_host {
 1158:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1159:     my $canhost=1;
 1160:     my @intdoms;
 1161:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1162:     if (ref($internet_names) eq 'ARRAY') {
 1163:         @intdoms = @{$internet_names};
 1164:     }
 1165:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1166:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1167:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1168:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1169:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1170:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1171:                                      $remotesessions,
 1172:                                      $defdomdefaults{'hostedsessions'});
 1173:     }
 1174:     return $canhost;
 1175: }
 1176: 
 1177: sub this_host_spares {
 1178:     my ($dom) = @_;
 1179:     my ($dom_in_use,$lonhost_in_use,$result);
 1180:     my @hosts = &current_machine_ids();
 1181:     foreach my $lonhost (@hosts) {
 1182:         if (&host_domain($lonhost) eq $dom) {
 1183:             $dom_in_use = $dom;
 1184:             $lonhost_in_use = $lonhost;
 1185:             last;
 1186:         }
 1187:     }
 1188:     if ($dom_in_use ne '') {
 1189:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1190:     }
 1191:     if (ref($result) ne 'HASH') {
 1192:         $lonhost_in_use = $perlvar{'lonHostID'};
 1193:         $dom_in_use = &host_domain($lonhost_in_use);
 1194:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1195:         if (ref($result) ne 'HASH') {
 1196:             $result = \%spareid;
 1197:         }
 1198:     }
 1199:     return $result;
 1200: }
 1201: 
 1202: sub spares_for_offload  {
 1203:     my ($dom_in_use,$lonhost_in_use) = @_;
 1204:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1205:     if (defined($cached)) {
 1206:         return $result;
 1207:     } else {
 1208:         my $cachetime = 60*60*24;
 1209:         my %domconfig =
 1210:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1211:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1212:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1213:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1214:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1215:                 }
 1216:             }
 1217:         }
 1218:     }
 1219:     return;
 1220: }
 1221: 
 1222: sub get_lonbalancer_config {
 1223:     my ($servers) = @_;
 1224:     my ($currbalancer,$currtargets);
 1225:     if (ref($servers) eq 'HASH') {
 1226:         foreach my $server (keys(%{$servers})) {
 1227:             my %what = (
 1228:                          spareid => 1,
 1229:                          perlvar => 1,
 1230:                        );
 1231:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1232:             if ($result eq 'ok') {
 1233:                 if (ref($returnhash) eq 'HASH') {
 1234:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1235:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1236:                             $currbalancer = $server;
 1237:                             $currtargets = {};
 1238:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1239:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1240:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1241:                                 }
 1242:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1243:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1244:                                 }
 1245:                             }
 1246:                             last;
 1247:                         }
 1248:                     }
 1249:                 }
 1250:             }
 1251:         }
 1252:     }
 1253:     return ($currbalancer,$currtargets);
 1254: }
 1255: 
 1256: sub check_loadbalancing {
 1257:     my ($uname,$udom) = @_;
 1258:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1259:         $rule_in_effect,$offloadto,$otherserver);
 1260:     my $lonhost = $perlvar{'lonHostID'};
 1261:     my @hosts = &current_machine_ids();
 1262:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1263:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1264:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1265:     my $serverhomedom = &host_domain($lonhost);
 1266: 
 1267:     my $cachetime = 60*60*24;
 1268: 
 1269:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1270:         $dom_in_use = $udom;
 1271:         $homeintdom = 1;
 1272:     } else {
 1273:         $dom_in_use = $serverhomedom;
 1274:     }
 1275:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1276:     unless (defined($cached)) {
 1277:         my %domconfig =
 1278:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1279:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1280:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1281:         }
 1282:     }
 1283:     if (ref($result) eq 'HASH') {
 1284:         ($is_balancer,$currtargets,$currrules) = 
 1285:             &check_balancer_result($result,@hosts);
 1286:         if ($is_balancer) {
 1287:             if (ref($currrules) eq 'HASH') {
 1288:                 if ($homeintdom) {
 1289:                     if ($uname ne '') {
 1290:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1291:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1292:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1293:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1294:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1295:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1296:                             }
 1297:                         }
 1298:                         if ($rule_in_effect eq '') {
 1299:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1300:                             if ($userenv{'inststatus'} ne '') {
 1301:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1302:                                 my ($othertitle,$usertypes,$types) =
 1303:                                     &Apache::loncommon::sorted_inst_types($udom);
 1304:                                 if (ref($types) eq 'ARRAY') {
 1305:                                     foreach my $type (@{$types}) {
 1306:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1307:                                             if (exists($currrules->{$type})) {
 1308:                                                 $rule_in_effect = $currrules->{$type};
 1309:                                             }
 1310:                                         }
 1311:                                     }
 1312:                                 }
 1313:                             } else {
 1314:                                 if (exists($currrules->{'default'})) {
 1315:                                     $rule_in_effect = $currrules->{'default'};
 1316:                                 }
 1317:                             }
 1318:                         }
 1319:                     } else {
 1320:                         if (exists($currrules->{'default'})) {
 1321:                             $rule_in_effect = $currrules->{'default'};
 1322:                         }
 1323:                     }
 1324:                 } else {
 1325:                     if ($currrules->{'_LC_external'} ne '') {
 1326:                         $rule_in_effect = $currrules->{'_LC_external'};
 1327:                     }
 1328:                 }
 1329:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1330:                                                        $uname,$udom);
 1331:             }
 1332:         }
 1333:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1334:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1335:         unless (defined($cached)) {
 1336:             my %domconfig =
 1337:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1338:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1339:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1340:             }
 1341:         }
 1342:         if (ref($result) eq 'HASH') {
 1343:             ($is_balancer,$currtargets,$currrules) = 
 1344:                 &check_balancer_result($result,@hosts);
 1345:             if ($is_balancer) {
 1346:                 if (ref($currrules) eq 'HASH') {
 1347:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1348:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1349:                     }
 1350:                 }
 1351:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1352:                                                        $uname,$udom);
 1353:             }
 1354:         } else {
 1355:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1356:                 $is_balancer = 1;
 1357:                 $offloadto = &this_host_spares($dom_in_use);
 1358:             }
 1359:         }
 1360:     } else {
 1361:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1362:             $is_balancer = 1;
 1363:             $offloadto = &this_host_spares($dom_in_use);
 1364:         }
 1365:     }
 1366:     if ($is_balancer) {
 1367:         my $lowest_load = 30000;
 1368:         if (ref($offloadto) eq 'HASH') {
 1369:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1370:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1371:                     ($otherserver,$lowest_load) =
 1372:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1373:                 }
 1374:             }
 1375:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1376: 
 1377:             if (!$found_server) {
 1378:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1379:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1380:                         ($otherserver,$lowest_load) =
 1381:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1382:                     }
 1383:                 }
 1384:             }
 1385:         } elsif (ref($offloadto) eq 'ARRAY') {
 1386:             if (@{$offloadto} == 1) {
 1387:                 $otherserver = $offloadto->[0];
 1388:             } elsif (@{$offloadto} > 1) {
 1389:                 foreach my $try_server (@{$offloadto}) {
 1390:                     ($otherserver,$lowest_load) =
 1391:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1392:                 }
 1393:             }
 1394:         }
 1395:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1396:             $is_balancer = 0;
 1397:             if ($uname ne '' && $udom ne '') {
 1398:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1399:                     
 1400:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1401:                              'user.loadbalcheck.time' => time});
 1402:                 }
 1403:             }
 1404:         }
 1405:     }
 1406:     return ($is_balancer,$otherserver);
 1407: }
 1408: 
 1409: sub check_balancer_result {
 1410:     my ($result,@hosts) = @_;
 1411:     my ($is_balancer,$currtargets,$currrules);
 1412:     if (ref($result) eq 'HASH') {
 1413:         if ($result->{'lonhost'} ne '') {
 1414:             my $currbalancer = $result->{'lonhost'};
 1415:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1416:                 $is_balancer = 1;
 1417:                 $currtargets = $result->{'targets'};
 1418:                 $currrules = $result->{'rules'};
 1419:             }
 1420:         } else {
 1421:             foreach my $key (keys(%{$result})) {
 1422:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1423:                     (ref($result->{$key}) eq 'HASH')) {
 1424:                     $is_balancer = 1;
 1425:                     $currrules = $result->{$key}{'rules'};
 1426:                     $currtargets = $result->{$key}{'targets'};
 1427:                     last;
 1428:                 }
 1429:             }
 1430:         }
 1431:     }
 1432:     return ($is_balancer,$currtargets,$currrules);
 1433: }
 1434: 
 1435: sub get_loadbalancer_targets {
 1436:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1437:     my $offloadto;
 1438:     if ($rule_in_effect eq 'none') {
 1439:         return [$perlvar{'lonHostID'}];
 1440:     } elsif ($rule_in_effect eq '') {
 1441:         $offloadto = $currtargets;
 1442:     } else {
 1443:         if ($rule_in_effect eq 'homeserver') {
 1444:             my $homeserver = &homeserver($uname,$udom);
 1445:             if ($homeserver ne 'no_host') {
 1446:                 $offloadto = [$homeserver];
 1447:             }
 1448:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1449:             my %domconfig =
 1450:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1451:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1452:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1453:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1454:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1455:                     }
 1456:                 }
 1457:             } else {
 1458:                 my %servers = &internet_dom_servers($udom);
 1459:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1460:                 if (&hostname($remotebalancer) ne '') {
 1461:                     $offloadto = [$remotebalancer];
 1462:                 }
 1463:             }
 1464:         } elsif (&hostname($rule_in_effect) ne '') {
 1465:             $offloadto = [$rule_in_effect];
 1466:         }
 1467:     }
 1468:     return $offloadto;
 1469: }
 1470: 
 1471: sub internet_dom_servers {
 1472:     my ($dom) = @_;
 1473:     my (%uniqservers,%servers);
 1474:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1475:     my @machinedoms = &machine_domains($primaryserver);
 1476:     foreach my $mdom (@machinedoms) {
 1477:         my %currservers = %servers;
 1478:         my %server = &get_servers($mdom);
 1479:         %servers = (%currservers,%server);
 1480:     }
 1481:     my %by_hostname;
 1482:     foreach my $id (keys(%servers)) {
 1483:         push(@{$by_hostname{$servers{$id}}},$id);
 1484:     }
 1485:     foreach my $hostname (sort(keys(%by_hostname))) {
 1486:         if (@{$by_hostname{$hostname}} > 1) {
 1487:             my $match = 0;
 1488:             foreach my $id (@{$by_hostname{$hostname}}) {
 1489:                 if (&host_domain($id) eq $dom) {
 1490:                     $uniqservers{$id} = $hostname;
 1491:                     $match = 1;
 1492:                 }
 1493:             }
 1494:             unless ($match) {
 1495:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1496:             }
 1497:         } else {
 1498:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1499:         }
 1500:     }
 1501:     return %uniqservers;
 1502: }
 1503: 
 1504: # ---------------------- Find the homebase for a user from domain's lib servers
 1505: 
 1506: my %homecache;
 1507: sub homeserver {
 1508:     my ($uname,$udom,$ignoreBadCache)=@_;
 1509:     my $index="$uname:$udom";
 1510: 
 1511:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1512: 
 1513:     my %servers = &get_servers($udom,'library');
 1514:     foreach my $tryserver (keys(%servers)) {
 1515:         next if ($ignoreBadCache ne 'true' && 
 1516: 		 exists($badServerCache{$tryserver}));
 1517: 
 1518: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1519: 	if ($answer eq 'found') {
 1520: 	    delete($badServerCache{$tryserver}); 
 1521: 	    return $homecache{$index}=$tryserver;
 1522: 	} elsif ($answer eq 'no_host') {
 1523: 	    $badServerCache{$tryserver}=1;
 1524: 	}
 1525:     }    
 1526:     return 'no_host';
 1527: }
 1528: 
 1529: # ------------------------------------- Find the usernames behind a list of IDs
 1530: 
 1531: sub idget {
 1532:     my ($udom,@ids)=@_;
 1533:     my %returnhash=();
 1534:     
 1535:     my %servers = &get_servers($udom,'library');
 1536:     foreach my $tryserver (keys(%servers)) {
 1537: 	my $idlist=join('&',@ids);
 1538: 	$idlist=~tr/A-Z/a-z/; 
 1539: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1540: 	my @answer=();
 1541: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1542: 	    @answer=split(/\&/,$reply);
 1543: 	}                    ;
 1544: 	my $i;
 1545: 	for ($i=0;$i<=$#ids;$i++) {
 1546: 	    if ($answer[$i]) {
 1547: 		$returnhash{$ids[$i]}=$answer[$i];
 1548: 	    } 
 1549: 	}
 1550:     } 
 1551:     return %returnhash;
 1552: }
 1553: 
 1554: # ------------------------------------- Find the IDs behind a list of usernames
 1555: 
 1556: sub idrget {
 1557:     my ($udom,@unames)=@_;
 1558:     my %returnhash=();
 1559:     foreach my $uname (@unames) {
 1560:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1561:     }
 1562:     return %returnhash;
 1563: }
 1564: 
 1565: # ------------------------------- Store away a list of names and associated IDs
 1566: 
 1567: sub idput {
 1568:     my ($udom,%ids)=@_;
 1569:     my %servers=();
 1570:     foreach my $uname (keys(%ids)) {
 1571: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1572:         my $uhom=&homeserver($uname,$udom);
 1573:         if ($uhom ne 'no_host') {
 1574:             my $id=&escape($ids{$uname});
 1575:             $id=~tr/A-Z/a-z/;
 1576:             my $esc_unam=&escape($uname);
 1577: 	    if ($servers{$uhom}) {
 1578: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1579:             } else {
 1580:                 $servers{$uhom}=$id.'='.$esc_unam;
 1581:             }
 1582:         }
 1583:     }
 1584:     foreach my $server (keys(%servers)) {
 1585:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1586:     }
 1587: }
 1588: 
 1589: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1590: 
 1591: sub iddel {
 1592:     my ($udom,$idshashref,$uhome)=@_;
 1593:     my %result=();
 1594:     unless (ref($idshashref) eq 'HASH') {
 1595:         return %result;
 1596:     }
 1597:     my %servers=();
 1598:     while (my ($id,$uname) = each(%{$idshashref})) {
 1599:         my $uhom;
 1600:         if ($uhome) {
 1601:             $uhom = $uhome;
 1602:         } else {
 1603:             $uhom=&homeserver($uname,$udom);
 1604:         }
 1605:         if ($uhom ne 'no_host') {
 1606:             if ($servers{$uhom}) {
 1607:                 $servers{$uhom}.='&'.&escape($id);
 1608:             } else {
 1609:                 $servers{$uhom}=&escape($id);
 1610:             }
 1611:         }
 1612:     }
 1613:     foreach my $server (keys(%servers)) {
 1614:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1615:     }
 1616:     return %result;
 1617: }
 1618: 
 1619: # ------------------------------dump from db file owned by domainconfig user
 1620: sub dump_dom {
 1621:     my ($namespace, $udom, $regexp) = @_;
 1622: 
 1623:     $udom ||= $env{'user.domain'};
 1624: 
 1625:     return () unless $udom;
 1626: 
 1627:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1628: }
 1629: 
 1630: # ------------------------------------------ get items from domain db files   
 1631: 
 1632: sub get_dom {
 1633:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1634:     my $items='';
 1635:     foreach my $item (@$storearr) {
 1636:         $items.=&escape($item).'&';
 1637:     }
 1638:     $items=~s/\&$//;
 1639:     if (!$udom) {
 1640:         $udom=$env{'user.domain'};
 1641:         if (defined(&domain($udom,'primary'))) {
 1642:             $uhome=&domain($udom,'primary');
 1643:         } else {
 1644:             undef($uhome);
 1645:         }
 1646:     } else {
 1647:         if (!$uhome) {
 1648:             if (defined(&domain($udom,'primary'))) {
 1649:                 $uhome=&domain($udom,'primary');
 1650:             }
 1651:         }
 1652:     }
 1653:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1654:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1655:         my %returnhash;
 1656:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1657:             return %returnhash;
 1658:         }
 1659:         my @pairs=split(/\&/,$rep);
 1660:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1661:             return @pairs;
 1662:         }
 1663:         my $i=0;
 1664:         foreach my $item (@$storearr) {
 1665:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1666:             $i++;
 1667:         }
 1668:         return %returnhash;
 1669:     } else {
 1670:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1671:     }
 1672: }
 1673: 
 1674: # -------------------------------------------- put items in domain db files 
 1675: 
 1676: sub put_dom {
 1677:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1678:     if (!$udom) {
 1679:         $udom=$env{'user.domain'};
 1680:         if (defined(&domain($udom,'primary'))) {
 1681:             $uhome=&domain($udom,'primary');
 1682:         } else {
 1683:             undef($uhome);
 1684:         }
 1685:     } else {
 1686:         if (!$uhome) {
 1687:             if (defined(&domain($udom,'primary'))) {
 1688:                 $uhome=&domain($udom,'primary');
 1689:             }
 1690:         }
 1691:     } 
 1692:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1693:         my $items='';
 1694:         foreach my $item (keys(%$storehash)) {
 1695:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1696:         }
 1697:         $items=~s/\&$//;
 1698:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1699:     } else {
 1700:         &logthis("put_dom failed - no homeserver and/or domain");
 1701:     }
 1702: }
 1703: 
 1704: # --------------------- newput for items in db file owned by domainconfig user
 1705: sub newput_dom {
 1706:     my ($namespace,$storehash,$udom) = @_;
 1707:     my $result;
 1708:     if (!$udom) {
 1709:         $udom=$env{'user.domain'};
 1710:     }
 1711:     if ($udom) {
 1712:         my $uname = &get_domainconfiguser($udom);
 1713:         $result = &newput($namespace,$storehash,$udom,$uname);
 1714:     }
 1715:     return $result;
 1716: }
 1717: 
 1718: # --------------------- delete for items in db file owned by domainconfig user
 1719: sub del_dom {
 1720:     my ($namespace,$storearr,$udom)=@_;
 1721:     if (ref($storearr) eq 'ARRAY') {
 1722:         if (!$udom) {
 1723:             $udom=$env{'user.domain'};
 1724:         }
 1725:         if ($udom) {
 1726:             my $uname = &get_domainconfiguser($udom); 
 1727:             return &del($namespace,$storearr,$udom,$uname);
 1728:         }
 1729:     }
 1730: }
 1731: 
 1732: # ----------------------------------construct domainconfig user for a domain 
 1733: sub get_domainconfiguser {
 1734:     my ($udom) = @_;
 1735:     return $udom.'-domainconfig';
 1736: }
 1737: 
 1738: sub retrieve_inst_usertypes {
 1739:     my ($udom) = @_;
 1740:     my (%returnhash,@order);
 1741:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1742:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1743:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1744:         %returnhash = %{$domdefs{'inststatustypes'}};
 1745:         @order = @{$domdefs{'inststatusorder'}};
 1746:     } else {
 1747:         if (defined(&domain($udom,'primary'))) {
 1748:             my $uhome=&domain($udom,'primary');
 1749:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1750:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1751:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1752:                 return (\%returnhash,\@order);
 1753:             }
 1754:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1755:             my @pairs=split(/\&/,$hashitems);
 1756:             foreach my $item (@pairs) {
 1757:                 my ($key,$value)=split(/=/,$item,2);
 1758:                 $key = &unescape($key);
 1759:                 next if ($key =~ /^error: 2 /);
 1760:                 $returnhash{$key}=&thaw_unescape($value);
 1761:             }
 1762:             my @esc_order = split(/\&/,$orderitems);
 1763:             foreach my $item (@esc_order) {
 1764:                 push(@order,&unescape($item));
 1765:             }
 1766:         } else {
 1767:             &logthis("get_dom failed - no primary domain server for $udom");
 1768:         }
 1769:     }
 1770:     return (\%returnhash,\@order);
 1771: }
 1772: 
 1773: sub is_domainimage {
 1774:     my ($url) = @_;
 1775:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1776:         if (&domain($1) ne '') {
 1777:             return '1';
 1778:         }
 1779:     }
 1780:     return;
 1781: }
 1782: 
 1783: sub inst_directory_query {
 1784:     my ($srch) = @_;
 1785:     my $udom = $srch->{'srchdomain'};
 1786:     my %results;
 1787:     my $homeserver = &domain($udom,'primary');
 1788:     my $outcome;
 1789:     if ($homeserver ne '') {
 1790: 	my $queryid=&reply("querysend:instdirsearch:".
 1791: 			   &escape($srch->{'srchby'}).':'.
 1792: 			   &escape($srch->{'srchterm'}).':'.
 1793: 			   &escape($srch->{'srchtype'}),$homeserver);
 1794: 	my $host=&hostname($homeserver);
 1795: 	if ($queryid !~/^\Q$host\E\_/) {
 1796: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1797: 	    return;
 1798: 	}
 1799: 	my $response = &get_query_reply($queryid);
 1800: 	my $maxtries = 5;
 1801: 	my $tries = 1;
 1802: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1803: 	    $response = &get_query_reply($queryid);
 1804: 	    $tries ++;
 1805: 	}
 1806: 
 1807:         if (!&error($response) && $response ne 'refused') {
 1808:             if ($response eq 'unavailable') {
 1809:                 $outcome = $response;
 1810:             } else {
 1811:                 $outcome = 'ok';
 1812:                 my @matches = split(/\n/,$response);
 1813:                 foreach my $match (@matches) {
 1814:                     my ($key,$value) = split(/=/,$match);
 1815:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1816:                 }
 1817:             }
 1818:         }
 1819:     }
 1820:     return ($outcome,%results);
 1821: }
 1822: 
 1823: sub usersearch {
 1824:     my ($srch) = @_;
 1825:     my $dom = $srch->{'srchdomain'};
 1826:     my %results;
 1827:     my %libserv = &all_library();
 1828:     my $query = 'usersearch';
 1829:     foreach my $tryserver (keys(%libserv)) {
 1830:         if (&host_domain($tryserver) eq $dom) {
 1831:             my $host=&hostname($tryserver);
 1832:             my $queryid=
 1833:                 &reply("querysend:".&escape($query).':'.
 1834:                        &escape($srch->{'srchby'}).':'.
 1835:                        &escape($srch->{'srchtype'}).':'.
 1836:                        &escape($srch->{'srchterm'}),$tryserver);
 1837:             if ($queryid !~/^\Q$host\E\_/) {
 1838:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1839:                 next;
 1840:             }
 1841:             my $reply = &get_query_reply($queryid);
 1842:             my $maxtries = 1;
 1843:             my $tries = 1;
 1844:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1845:                 $reply = &get_query_reply($queryid);
 1846:                 $tries ++;
 1847:             }
 1848:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1849:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1850:             } else {
 1851:                 my @matches;
 1852:                 if ($reply =~ /\n/) {
 1853:                     @matches = split(/\n/,$reply);
 1854:                 } else {
 1855:                     @matches = split(/\&/,$reply);
 1856:                 }
 1857:                 foreach my $match (@matches) {
 1858:                     my ($uname,$udom,%userhash);
 1859:                     foreach my $entry (split(/:/,$match)) {
 1860:                         my ($key,$value) =
 1861:                             map {&unescape($_);} split(/=/,$entry);
 1862:                         $userhash{$key} = $value;
 1863:                         if ($key eq 'username') {
 1864:                             $uname = $value;
 1865:                         } elsif ($key eq 'domain') {
 1866:                             $udom = $value;
 1867:                         }
 1868:                     }
 1869:                     $results{$uname.':'.$udom} = \%userhash;
 1870:                 }
 1871:             }
 1872:         }
 1873:     }
 1874:     return %results;
 1875: }
 1876: 
 1877: sub get_instuser {
 1878:     my ($udom,$uname,$id) = @_;
 1879:     my $homeserver = &domain($udom,'primary');
 1880:     my ($outcome,%results);
 1881:     if ($homeserver ne '') {
 1882:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1883:                            &escape($id).':'.&escape($udom),$homeserver);
 1884:         my $host=&hostname($homeserver);
 1885:         if ($queryid !~/^\Q$host\E\_/) {
 1886:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1887:             return;
 1888:         }
 1889:         my $response = &get_query_reply($queryid);
 1890:         my $maxtries = 5;
 1891:         my $tries = 1;
 1892:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1893:             $response = &get_query_reply($queryid);
 1894:             $tries ++;
 1895:         }
 1896:         if (!&error($response) && $response ne 'refused') {
 1897:             if ($response eq 'unavailable') {
 1898:                 $outcome = $response;
 1899:             } else {
 1900:                 $outcome = 'ok';
 1901:                 my @matches = split(/\n/,$response);
 1902:                 foreach my $match (@matches) {
 1903:                     my ($key,$value) = split(/=/,$match);
 1904:                     $results{&unescape($key)} = &thaw_unescape($value);
 1905:                 }
 1906:             }
 1907:         }
 1908:     }
 1909:     my %userinfo;
 1910:     if (ref($results{$uname}) eq 'HASH') {
 1911:         %userinfo = %{$results{$uname}};
 1912:     } 
 1913:     return ($outcome,%userinfo);
 1914: }
 1915: 
 1916: sub inst_rulecheck {
 1917:     my ($udom,$uname,$id,$item,$rules) = @_;
 1918:     my %returnhash;
 1919:     if ($udom ne '') {
 1920:         if (ref($rules) eq 'ARRAY') {
 1921:             @{$rules} = map {&escape($_);} (@{$rules});
 1922:             my $rulestr = join(':',@{$rules});
 1923:             my $homeserver=&domain($udom,'primary');
 1924:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1925:                 my $response;
 1926:                 if ($item eq 'username') {                
 1927:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1928:                                               ':'.&escape($uname).':'.$rulestr,
 1929:                                               $homeserver));
 1930:                 } elsif ($item eq 'id') {
 1931:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1932:                                               ':'.&escape($id).':'.$rulestr,
 1933:                                               $homeserver));
 1934:                 } elsif ($item eq 'selfcreate') {
 1935:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1936:                                                &escape($udom).':'.&escape($uname).
 1937:                                               ':'.$rulestr,$homeserver));
 1938:                 }
 1939:                 if ($response ne 'refused') {
 1940:                     my @pairs=split(/\&/,$response);
 1941:                     foreach my $item (@pairs) {
 1942:                         my ($key,$value)=split(/=/,$item,2);
 1943:                         $key = &unescape($key);
 1944:                         next if ($key =~ /^error: 2 /);
 1945:                         $returnhash{$key}=&thaw_unescape($value);
 1946:                     }
 1947:                 }
 1948:             }
 1949:         }
 1950:     }
 1951:     return %returnhash;
 1952: }
 1953: 
 1954: sub inst_userrules {
 1955:     my ($udom,$check) = @_;
 1956:     my (%ruleshash,@ruleorder);
 1957:     if ($udom ne '') {
 1958:         my $homeserver=&domain($udom,'primary');
 1959:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1960:             my $response;
 1961:             if ($check eq 'id') {
 1962:                 $response=&reply('instidrules:'.&escape($udom),
 1963:                                  $homeserver);
 1964:             } elsif ($check eq 'email') {
 1965:                 $response=&reply('instemailrules:'.&escape($udom),
 1966:                                  $homeserver);
 1967:             } else {
 1968:                 $response=&reply('instuserrules:'.&escape($udom),
 1969:                                  $homeserver);
 1970:             }
 1971:             if (($response ne 'refused') && ($response ne 'error') && 
 1972:                 ($response ne 'unknown_cmd') && 
 1973:                 ($response ne 'no_such_host')) {
 1974:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1975:                 my @pairs=split(/\&/,$hashitems);
 1976:                 foreach my $item (@pairs) {
 1977:                     my ($key,$value)=split(/=/,$item,2);
 1978:                     $key = &unescape($key);
 1979:                     next if ($key =~ /^error: 2 /);
 1980:                     $ruleshash{$key}=&thaw_unescape($value);
 1981:                 }
 1982:                 my @esc_order = split(/\&/,$orderitems);
 1983:                 foreach my $item (@esc_order) {
 1984:                     push(@ruleorder,&unescape($item));
 1985:                 }
 1986:             }
 1987:         }
 1988:     }
 1989:     return (\%ruleshash,\@ruleorder);
 1990: }
 1991: 
 1992: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1993: 
 1994: sub get_domain_defaults {
 1995:     my ($domain,$ignore_cache) = @_;
 1996:     return if (($domain eq '') || ($domain eq 'public'));
 1997:     my $cachetime = 60*60*24;
 1998:     unless ($ignore_cache) {
 1999:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2000:         if (defined($cached)) {
 2001:             if (ref($result) eq 'HASH') {
 2002:                 return %{$result};
 2003:             }
 2004:         }
 2005:     }
 2006:     my %domdefaults;
 2007:     my %domconfig =
 2008:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2009:                                   'requestcourses','inststatus',
 2010:                                   'coursedefaults','usersessions',
 2011:                                   'requestauthor'],$domain);
 2012:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2013:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2014:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2015:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2016:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2017:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2018:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2019:     } else {
 2020:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2021:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2022:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2023:     }
 2024:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2025:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2026:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2027:         } else {
 2028:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2029:         }
 2030:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2031:         foreach my $item (@usertools) {
 2032:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2033:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2034:             }
 2035:         }
 2036:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2037:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2038:         }
 2039:     }
 2040:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2041:         foreach my $item ('official','unofficial','community') {
 2042:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2043:         }
 2044:     }
 2045:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2046:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2047:     }
 2048:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2049:         foreach my $item ('inststatustypes','inststatusorder') {
 2050:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2051:         }
 2052:     }
 2053:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2054:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2055:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2056:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2057:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2058:         }
 2059:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2060:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2061:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2062:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2063:         }
 2064:     }
 2065:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2066:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2067:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2068:         }
 2069:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2070:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2071:         }
 2072:     }
 2073:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2074:     return %domdefaults;
 2075: }
 2076: 
 2077: # --------------------------------------------------- Assign a key to a student
 2078: 
 2079: sub assign_access_key {
 2080: #
 2081: # a valid key looks like uname:udom#comments
 2082: # comments are being appended
 2083: #
 2084:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2085:     $kdom=
 2086:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2087:     $knum=
 2088:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2089:     $cdom=
 2090:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2091:     $cnum=
 2092:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2093:     $udom=$env{'user.name'} unless (defined($udom));
 2094:     $uname=$env{'user.domain'} unless (defined($uname));
 2095:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2096:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2097:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2098:                                                   # assigned to this person
 2099:                                                   # - this should not happen,
 2100:                                                   # unless something went wrong
 2101:                                                   # the first time around
 2102: # ready to assign
 2103:         $logentry=$1.'; '.$logentry;
 2104:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2105:                                                  $kdom,$knum) eq 'ok') {
 2106: # key now belongs to user
 2107: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2108:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2109:                 &appenv({'environment.'.$envkey => $ckey});
 2110:                 return 'ok';
 2111:             } else {
 2112:                 return 
 2113:   'error: Count not permanently assign key, will need to be re-entered later.';
 2114: 	    }
 2115:         } else {
 2116:             return 'error: Could not assign key, try again later.';
 2117:         }
 2118:     } elsif (!$existing{$ckey}) {
 2119: # the key does not exist
 2120: 	return 'error: The key does not exist';
 2121:     } else {
 2122: # the key is somebody else's
 2123: 	return 'error: The key is already in use';
 2124:     }
 2125: }
 2126: 
 2127: # ------------------------------------------ put an additional comment on a key
 2128: 
 2129: sub comment_access_key {
 2130: #
 2131: # a valid key looks like uname:udom#comments
 2132: # comments are being appended
 2133: #
 2134:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2135:     $cdom=
 2136:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2137:     $cnum=
 2138:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2139:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2140:     if ($existing{$ckey}) {
 2141:         $existing{$ckey}.='; '.$logentry;
 2142: # ready to assign
 2143:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2144:                                                  $cdom,$cnum) eq 'ok') {
 2145: 	    return 'ok';
 2146:         } else {
 2147: 	    return 'error: Count not store comment.';
 2148:         }
 2149:     } else {
 2150: # the key does not exist
 2151: 	return 'error: The key does not exist';
 2152:     }
 2153: }
 2154: 
 2155: # ------------------------------------------------------ Generate a set of keys
 2156: 
 2157: sub generate_access_keys {
 2158:     my ($number,$cdom,$cnum,$logentry)=@_;
 2159:     $cdom=
 2160:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2161:     $cnum=
 2162:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2163:     unless (&allowed('mky',$cdom)) { return 0; }
 2164:     unless (($cdom) && ($cnum)) { return 0; }
 2165:     if ($number>10000) { return 0; }
 2166:     sleep(2); # make sure don't get same seed twice
 2167:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2168:     my $total=0;
 2169:     for (my $i=1;$i<=$number;$i++) {
 2170:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2171:                   sprintf("%lx",int(100000*rand)).'-'.
 2172:                   sprintf("%lx",int(100000*rand));
 2173:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2174:        $newkey=~s/0/h/g; # and also 0 and O
 2175:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2176:        if ($existing{$newkey}) {
 2177:            $i--;
 2178:        } else {
 2179: 	  if (&put('accesskeys',
 2180:               { $newkey => '# generated '.localtime().
 2181:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2182:                            '; '.$logentry },
 2183: 		   $cdom,$cnum) eq 'ok') {
 2184:               $total++;
 2185: 	  }
 2186:        }
 2187:     }
 2188:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2189:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2190:     return $total;
 2191: }
 2192: 
 2193: # ------------------------------------------------------- Validate an accesskey
 2194: 
 2195: sub validate_access_key {
 2196:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2197:     $cdom=
 2198:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2199:     $cnum=
 2200:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2201:     $udom=$env{'user.domain'} unless (defined($udom));
 2202:     $uname=$env{'user.name'} unless (defined($uname));
 2203:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2204:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2205: }
 2206: 
 2207: # ------------------------------------- Find the section of student in a course
 2208: sub devalidate_getsection_cache {
 2209:     my ($udom,$unam,$courseid)=@_;
 2210:     my $hashid="$udom:$unam:$courseid";
 2211:     &devalidate_cache_new('getsection',$hashid);
 2212: }
 2213: 
 2214: sub courseid_to_courseurl {
 2215:     my ($courseid) = @_;
 2216:     #already url style courseid
 2217:     return $courseid if ($courseid =~ m{^/});
 2218: 
 2219:     if (exists($env{'course.'.$courseid.'.num'})) {
 2220: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2221: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2222: 	return "/$cdom/$cnum";
 2223:     }
 2224: 
 2225:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2226:     if (exists($courseinfo{'num'})) {
 2227: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2228:     }
 2229: 
 2230:     return undef;
 2231: }
 2232: 
 2233: sub getsection {
 2234:     my ($udom,$unam,$courseid)=@_;
 2235:     my $cachetime=1800;
 2236: 
 2237:     my $hashid="$udom:$unam:$courseid";
 2238:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2239:     if (defined($cached)) { return $result; }
 2240: 
 2241:     my %Pending; 
 2242:     my %Expired;
 2243:     #
 2244:     # Each role can either have not started yet (pending), be active, 
 2245:     #    or have expired.
 2246:     #
 2247:     # If there is an active role, we are done.
 2248:     #
 2249:     # If there is more than one role which has not started yet, 
 2250:     #     choose the one which will start sooner
 2251:     # If there is one role which has not started yet, return it.
 2252:     #
 2253:     # If there is more than one expired role, choose the one which ended last.
 2254:     # If there is a role which has expired, return it.
 2255:     #
 2256:     $courseid = &courseid_to_courseurl($courseid);
 2257:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2258:     foreach my $key (keys(%roleshash)) {
 2259:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2260:         my $section=$1;
 2261:         if ($key eq $courseid.'_st') { $section=''; }
 2262:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2263:         my $now=time;
 2264:         if (defined($end) && $end && ($now > $end)) {
 2265:             $Expired{$end}=$section;
 2266:             next;
 2267:         }
 2268:         if (defined($start) && $start && ($now < $start)) {
 2269:             $Pending{$start}=$section;
 2270:             next;
 2271:         }
 2272:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2273:     }
 2274:     #
 2275:     # Presumedly there will be few matching roles from the above
 2276:     # loop and the sorting time will be negligible.
 2277:     if (scalar(keys(%Pending))) {
 2278:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2279:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2280:     } 
 2281:     if (scalar(keys(%Expired))) {
 2282:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2283:         my $time = pop(@sorted);
 2284:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2285:     }
 2286:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2287: }
 2288: 
 2289: sub save_cache {
 2290:     &purge_remembered();
 2291:     #&Apache::loncommon::validate_page();
 2292:     undef(%env);
 2293:     undef($env_loaded);
 2294: }
 2295: 
 2296: my $to_remember=-1;
 2297: my %remembered;
 2298: my %accessed;
 2299: my $kicks=0;
 2300: my $hits=0;
 2301: sub make_key {
 2302:     my ($name,$id) = @_;
 2303:     if (length($id) > 65 
 2304: 	&& length(&escape($id)) > 200) {
 2305: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2306:     }
 2307:     return &escape($name.':'.$id);
 2308: }
 2309: 
 2310: sub devalidate_cache_new {
 2311:     my ($name,$id,$debug) = @_;
 2312:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2313:     $id=&make_key($name,$id);
 2314:     $memcache->delete($id);
 2315:     delete($remembered{$id});
 2316:     delete($accessed{$id});
 2317: }
 2318: 
 2319: sub is_cached_new {
 2320:     my ($name,$id,$debug) = @_;
 2321:     $id=&make_key($name,$id);
 2322:     if (exists($remembered{$id})) {
 2323: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2324: 	$accessed{$id}=[&gettimeofday()];
 2325: 	$hits++;
 2326: 	return ($remembered{$id},1);
 2327:     }
 2328:     my $value = $memcache->get($id);
 2329:     if (!(defined($value))) {
 2330: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2331: 	return (undef,undef);
 2332:     }
 2333:     if ($value eq '__undef__') {
 2334: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2335: 	$value=undef;
 2336:     }
 2337:     &make_room($id,$value,$debug);
 2338:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2339:     return ($value,1);
 2340: }
 2341: 
 2342: sub do_cache_new {
 2343:     my ($name,$id,$value,$time,$debug) = @_;
 2344:     $id=&make_key($name,$id);
 2345:     my $setvalue=$value;
 2346:     if (!defined($setvalue)) {
 2347: 	$setvalue='__undef__';
 2348:     }
 2349:     if (!defined($time) ) {
 2350: 	$time=600;
 2351:     }
 2352:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2353:     my $result = $memcache->set($id,$setvalue,$time);
 2354:     if (! $result) {
 2355: 	&logthis("caching of id -> $id  failed");
 2356: 	$memcache->disconnect_all();
 2357:     }
 2358:     # need to make a copy of $value
 2359:     &make_room($id,$value,$debug);
 2360:     return $value;
 2361: }
 2362: 
 2363: sub make_room {
 2364:     my ($id,$value,$debug)=@_;
 2365: 
 2366:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2367:                                     : $value;
 2368:     if ($to_remember<0) { return; }
 2369:     $accessed{$id}=[&gettimeofday()];
 2370:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2371:     my $to_kick;
 2372:     my $max_time=0;
 2373:     foreach my $other (keys(%accessed)) {
 2374: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2375: 	    $to_kick=$other;
 2376: 	    $max_time=&tv_interval($accessed{$other});
 2377: 	}
 2378:     }
 2379:     delete($remembered{$to_kick});
 2380:     delete($accessed{$to_kick});
 2381:     $kicks++;
 2382:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2383:     return;
 2384: }
 2385: 
 2386: sub purge_remembered {
 2387:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2388:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2389:     undef(%remembered);
 2390:     undef(%accessed);
 2391: }
 2392: # ------------------------------------- Read an entry from a user's environment
 2393: 
 2394: sub userenvironment {
 2395:     my ($udom,$unam,@what)=@_;
 2396:     my $items;
 2397:     foreach my $item (@what) {
 2398:         $items.=&escape($item).'&';
 2399:     }
 2400:     $items=~s/\&$//;
 2401:     my %returnhash=();
 2402:     my $uhome = &homeserver($unam,$udom);
 2403:     unless ($uhome eq 'no_host') {
 2404:         my @answer=split(/\&/, 
 2405:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2406:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2407:             return %returnhash;
 2408:         }
 2409:         my $i;
 2410:         for ($i=0;$i<=$#what;$i++) {
 2411: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2412:         }
 2413:     }
 2414:     return %returnhash;
 2415: }
 2416: 
 2417: # ---------------------------------------------------------- Get a studentphoto
 2418: sub studentphoto {
 2419:     my ($udom,$unam,$ext) = @_;
 2420:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2421:     if (defined($env{'request.course.id'})) {
 2422:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2423:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2424:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2425:             } else {
 2426:                 my ($result,$perm_reqd)=
 2427: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2428:                 if ($result eq 'ok') {
 2429:                     if (!($perm_reqd eq 'yes')) {
 2430:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2431:                     }
 2432:                 }
 2433:             }
 2434:         }
 2435:     } else {
 2436:         my ($result,$perm_reqd) = 
 2437: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2438:         if ($result eq 'ok') {
 2439:             if (!($perm_reqd eq 'yes')) {
 2440:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2441:             }
 2442:         }
 2443:     }
 2444:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2445: }
 2446: 
 2447: sub retrievestudentphoto {
 2448:     my ($udom,$unam,$ext,$type) = @_;
 2449:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2450:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2451:     if ($ret eq 'ok') {
 2452:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2453:         if ($type eq 'thumbnail') {
 2454:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2455:         }
 2456:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2457:         return $tokenurl;
 2458:     } else {
 2459:         if ($type eq 'thumbnail') {
 2460:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2461:         } else { 
 2462:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2463:         }
 2464:     }
 2465: }
 2466: 
 2467: # -------------------------------------------------------------------- New chat
 2468: 
 2469: sub chatsend {
 2470:     my ($newentry,$anon,$group)=@_;
 2471:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2473:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2474:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2475: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2476: 		   &escape($newentry)).':'.$group,$chome);
 2477: }
 2478: 
 2479: # ------------------------------------------ Find current version of a resource
 2480: 
 2481: sub getversion {
 2482:     my $fname=&clutter(shift);
 2483:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2484:     return &currentversion(&filelocation('',$fname));
 2485: }
 2486: 
 2487: sub currentversion {
 2488:     my $fname=shift;
 2489:     my $author=$fname;
 2490:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2491:     my ($udom,$uname)=split(/\//,$author);
 2492:     my $home=&homeserver($uname,$udom);
 2493:     if ($home eq 'no_host') { 
 2494:         return -1; 
 2495:     }
 2496:     my $answer=&reply("currentversion:$fname",$home);
 2497:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2498: 	return -1;
 2499:     }
 2500:     return $answer;
 2501: }
 2502: 
 2503: #
 2504: # Return special version number of resource if set by override, empty otherwise
 2505: #
 2506: sub usedversion {
 2507:     my $fname=shift;
 2508:     unless ($fname) { $fname=$env{'request.uri'}; }
 2509:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2510:     if ($urlversion) { return $urlversion; }
 2511:     return '';
 2512: }
 2513: 
 2514: # ----------------------------- Subscribe to a resource, return URL if possible
 2515: 
 2516: sub subscribe {
 2517:     my $fname=shift;
 2518:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2519:     $fname=~s/[\n\r]//g;
 2520:     my $author=$fname;
 2521:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2522:     my ($udom,$uname)=split(/\//,$author);
 2523:     my $home=homeserver($uname,$udom);
 2524:     if ($home eq 'no_host') {
 2525:         return 'not_found';
 2526:     }
 2527:     my $answer=reply("sub:$fname",$home);
 2528:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2529: 	$answer.=' by '.$home;
 2530:     }
 2531:     return $answer;
 2532: }
 2533:     
 2534: # -------------------------------------------------------------- Replicate file
 2535: 
 2536: sub repcopy {
 2537:     my $filename=shift;
 2538:     $filename=~s/\/+/\//g;
 2539:     my $londocroot = $perlvar{'lonDocRoot'};
 2540:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2541:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2542:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2543: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2544: 	return &repcopy_userfile($filename);
 2545:     }
 2546:     $filename=~s/[\n\r]//g;
 2547:     my $transname="$filename.in.transfer";
 2548: # FIXME: this should flock
 2549:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2550:     my $remoteurl=subscribe($filename);
 2551:     if ($remoteurl =~ /^con_lost by/) {
 2552: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2553:            return 'unavailable';
 2554:     } elsif ($remoteurl eq 'not_found') {
 2555: 	   #&logthis("Subscribe returned not_found: $filename");
 2556: 	   return 'not_found';
 2557:     } elsif ($remoteurl =~ /^rejected by/) {
 2558: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2559:            return 'forbidden';
 2560:     } elsif ($remoteurl eq 'directory') {
 2561:            return 'ok';
 2562:     } else {
 2563:         my $author=$filename;
 2564:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2565:         my ($udom,$uname)=split(/\//,$author);
 2566:         my $home=homeserver($uname,$udom);
 2567:         unless ($home eq $perlvar{'lonHostID'}) {
 2568:            my @parts=split(/\//,$filename);
 2569:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2570:            if ($path ne "$londocroot/res") {
 2571:                &logthis("Malconfiguration for replication: $filename");
 2572: 	       return 'bad_request';
 2573:            }
 2574:            my $count;
 2575:            for ($count=5;$count<$#parts;$count++) {
 2576:                $path.="/$parts[$count]";
 2577:                if ((-e $path)!=1) {
 2578: 		   mkdir($path,0777);
 2579:                }
 2580:            }
 2581:            my $ua=new LWP::UserAgent;
 2582:            my $request=new HTTP::Request('GET',"$remoteurl");
 2583:            my $response=$ua->request($request,$transname);
 2584:            if ($response->is_error()) {
 2585: 	       unlink($transname);
 2586:                my $message=$response->status_line;
 2587:                &logthis("<font color=\"blue\">WARNING:"
 2588:                        ." LWP get: $message: $filename</font>");
 2589:                return 'unavailable';
 2590:            } else {
 2591: 	       if ($remoteurl!~/\.meta$/) {
 2592:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2593:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2594:                   if ($mresponse->is_error()) {
 2595: 		      unlink($filename.'.meta');
 2596:                       &logthis(
 2597:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2598:                   }
 2599: 	       }
 2600:                rename($transname,$filename);
 2601:                return 'ok';
 2602:            }
 2603:        }
 2604:     }
 2605: }
 2606: 
 2607: # ------------------------------------------------ Get server side include body
 2608: sub ssi_body {
 2609:     my ($filelink,%form)=@_;
 2610:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2611:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2612:     }
 2613:     my $output='';
 2614:     my $response;
 2615:     if ($filelink=~/^https?\:/) {
 2616:        ($output,$response)=&externalssi($filelink);
 2617:     } else {
 2618:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2619:        $filelink .= 'inhibitmenu=yes';
 2620:        ($output,$response)=&ssi($filelink,%form);
 2621:     }
 2622:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2623:     $output=~s/^.*?\<body[^\>]*\>//si;
 2624:     $output=~s/\<\/body\s*\>.*?$//si;
 2625:     if (wantarray) {
 2626:         return ($output, $response);
 2627:     } else {
 2628:         return $output;
 2629:     }
 2630: }
 2631: 
 2632: # --------------------------------------------------------- Server Side Include
 2633: 
 2634: sub absolute_url {
 2635:     my ($host_name) = @_;
 2636:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2637:     if ($host_name eq '') {
 2638: 	$host_name = $ENV{'SERVER_NAME'};
 2639:     }
 2640:     return $protocol.$host_name;
 2641: }
 2642: 
 2643: #
 2644: #   Server side include.
 2645: # Parameters:
 2646: #  fn     Possibly encrypted resource name/id.
 2647: #  form   Hash that describes how the rendering should be done
 2648: #         and other things.
 2649: # Returns:
 2650: #   Scalar context: The content of the response.
 2651: #   Array context:  2 element list of the content and the full response object.
 2652: #     
 2653: sub ssi {
 2654: 
 2655:     my ($fn,%form)=@_;
 2656:     my $ua=new LWP::UserAgent;
 2657:     my $request;
 2658: 
 2659:     $form{'no_update_last_known'}=1;
 2660:     &Apache::lonenc::check_encrypt(\$fn);
 2661:     if (%form) {
 2662:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2663:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2664:     } else {
 2665:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2666:     }
 2667: 
 2668:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2669:     my $response= $ua->request($request);
 2670:     my $content = $response->content;
 2671: 
 2672: 
 2673:     if (wantarray) {
 2674: 	return ($content, $response);
 2675:     } else {
 2676: 	return $content;
 2677:     }
 2678: }
 2679: 
 2680: sub externalssi {
 2681:     my ($url)=@_;
 2682:     my $ua=new LWP::UserAgent;
 2683:     my $request=new HTTP::Request('GET',$url);
 2684:     my $response=$ua->request($request);
 2685:     if (wantarray) {
 2686:         return ($response->content, $response);
 2687:     } else {
 2688:         return $response->content;
 2689:     }
 2690: }
 2691: 
 2692: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2693: 
 2694: sub allowuploaded {
 2695:     my ($srcurl,$url)=@_;
 2696:     $url=&clutter(&declutter($url));
 2697:     my $dir=$url;
 2698:     $dir=~s/\/[^\/]+$//;
 2699:     my %httpref=();
 2700:     my $httpurl=&hreflocation('',$url);
 2701:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2702:     &Apache::lonnet::appenv(\%httpref);
 2703: }
 2704: 
 2705: #
 2706: # Determine if the current user should be able to edit a particular resource,
 2707: # when viewing in course context.
 2708: # (a) When viewing resource used to determine if "Edit" item is included in 
 2709: #     Functions.
 2710: # (b) When displaying folder contents in course editor, used to determine if
 2711: #     "Edit" link will be displayed alongside resource.
 2712: #
 2713: #  input: six args -- filename (decluttered), course number, course domain,
 2714: #                   url, symb (if registered) and group (if this is a group
 2715: #                   item -- e.g., bulletin board, group page etc.).
 2716: #  output: array of five scalars -- 
 2717: #          $cfile -- url for file editing if editable on current server
 2718: #          $home -- homeserver of resource (i.e., for author if published,
 2719: #                                           or course if uploaded.).
 2720: #          $switchserver --  1 if server switch will be needed.
 2721: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2722: #          $forceview -- 1 if icon/link should be to go to view mode
 2723: #
 2724: 
 2725: sub can_edit_resource {
 2726:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2727:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2728: #
 2729: # For aboutme pages user can only edit his/her own.
 2730: #
 2731:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2732:         my ($sdom,$sname) = ($1,$2);
 2733:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2734:             $home = $env{'user.home'};
 2735:             $cfile = $resurl;
 2736:             if ($env{'form.forceedit'}) {
 2737:                 $forceview = 1;
 2738:             } else {
 2739:                 $forceedit = 1;
 2740:             }
 2741:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2742:         } else {
 2743:             return;
 2744:         }
 2745:     }
 2746: 
 2747:     if ($env{'request.course.id'}) {
 2748:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2749:         if ($group ne '') {
 2750: # if this is a group homepage or group bulletin board, check group privs
 2751:             my $allowed = 0;
 2752:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2753:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2754:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2755:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2756:                     $allowed = 1;
 2757:                 }
 2758:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2759:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2760:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2761:                     $allowed = 1;
 2762:                 }
 2763:             }
 2764:             if ($allowed) {
 2765:                 $home=&homeserver($cnum,$cdom);
 2766:                 if ($env{'form.forceedit'}) {
 2767:                     $forceview = 1;
 2768:                 } else {
 2769:                     $forceedit = 1;
 2770:                 }
 2771:                 $cfile = $resurl;
 2772:             } else {
 2773:                 return;
 2774:             }
 2775:         } else {
 2776:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2777:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2778:                     return;
 2779:                 }
 2780:             } elsif (!$crsedit) {
 2781: #
 2782: # No edit allowed where CC has switched to student role.
 2783: #
 2784:                 return;
 2785:             }
 2786:         }
 2787:     }
 2788: 
 2789:     if ($file ne '') {
 2790:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2791:             if (&is_course_upload($file,$cnum,$cdom)) {
 2792:                 $uploaded = 1;
 2793:                 $incourse = 1;
 2794:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2795:                     $cfile = &hreflocation('',$file);
 2796:                     if ($env{'form.forceedit'}) {
 2797:                         $forceview = 1;
 2798:                     } else {
 2799:                         $forceedit = 1;
 2800:                     }
 2801:                 }
 2802:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2803:                 $incourse = 1;
 2804:                 if ($env{'form.forceedit'}) {
 2805:                     $forceview = 1;
 2806:                 } else {
 2807:                     $forceedit = 1;
 2808:                 }
 2809:                 $cfile = $resurl;
 2810:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2811:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2812:                     $incourse = 1;
 2813:                     if ($env{'form.forceedit'}) {
 2814:                         $forceview = 1;
 2815:                     } else {
 2816:                         $forceedit = 1;
 2817:                     }
 2818:                     $cfile = $resurl;
 2819:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2820:                     $incourse = 1;
 2821:                     $cfile = $resurl.'/smpedit';
 2822:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2823:                     $incourse = 1;
 2824:                     if ($env{'form.forceedit'}) {
 2825:                         $forceview = 1;
 2826:                     } else {
 2827:                         $forceedit = 1;
 2828:                     }
 2829:                     $cfile = $resurl;
 2830:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2831:                     $incourse = 1;
 2832:                     if ($env{'form.forceedit'}) {
 2833:                         $forceview = 1;
 2834:                     } else {
 2835:                         $forceedit = 1;
 2836:                     }
 2837:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2838:                 }
 2839:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2840:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2841:                 if (&is_on_map($template)) { 
 2842:                     $incourse = 1;
 2843:                     $forceview = 1;
 2844:                     $cfile = $template;
 2845:                 }
 2846:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2847:                     $incourse = 1;
 2848:                     if ($env{'form.forceedit'}) {
 2849:                         $forceview = 1;
 2850:                     } else {
 2851:                         $forceedit = 1;
 2852:                     }
 2853:                     $cfile = $resurl;
 2854:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2855:                 $incourse = 1;
 2856:                 $forceview = 1;
 2857:                 if ($symb) {
 2858:                     my ($map,$id,$res)=&decode_symb($symb);
 2859:                     $env{'request.symb'} = $symb;
 2860:                     $cfile = &clutter($res);
 2861:                 } else {
 2862:                     $cfile = $env{'form.suppurl'};
 2863:                     $cfile =~ s{^http://}{};
 2864:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2865:                 }
 2866:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2867:                 if ($env{'form.forceedit'}) {
 2868:                     $forceview = 1;
 2869:                 } else {
 2870:                     $forceedit = 1;
 2871:                 }
 2872:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2873:             }
 2874:         }
 2875:         if ($uploaded || $incourse) {
 2876:             $home=&homeserver($cnum,$cdom);
 2877:         } elsif ($file !~ m{/$}) {
 2878:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2879:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2880:             # Check that the user has permission to edit this resource
 2881:             my $setpriv = 1;
 2882:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2883:             if (defined($cfudom)) {
 2884:                 $home=&homeserver($cfuname,$cfudom);
 2885:                 $cfile=$file;
 2886:             }
 2887:         }
 2888:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2889:             (($home ne '') && ($home ne 'no_host'))) {
 2890:             my @ids=&current_machine_ids();
 2891:             unless (grep(/^\Q$home\E$/,@ids)) {
 2892:                 $switchserver=1;
 2893:             }
 2894:         }
 2895:     }
 2896:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2897: }
 2898: 
 2899: sub is_course_upload {
 2900:     my ($file,$cnum,$cdom) = @_;
 2901:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2902:     $uploadpath =~ s{^\/}{};
 2903:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2904:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2905:         return 1;
 2906:     }
 2907:     return;
 2908: }
 2909: 
 2910: sub in_course {
 2911:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2912:     if ($hideprivileged) {
 2913:         my $skipuser;
 2914:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2915:         my @possdoms = ($cdom);  
 2916:         if ($coursehash{'checkforpriv'}) { 
 2917:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2918:         }
 2919:         if (&privileged($uname,$udom,\@possdoms)) {
 2920:             $skipuser = 1;
 2921:             if ($coursehash{'nothideprivileged'}) {
 2922:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2923:                     my $user;
 2924:                     if ($item =~ /:/) {
 2925:                         $user = $item;
 2926:                     } else {
 2927:                         $user = join(':',split(/[\@]/,$item));
 2928:                     }
 2929:                     if ($user eq $uname.':'.$udom) {
 2930:                         undef($skipuser);
 2931:                         last;
 2932:                     }
 2933:                 }
 2934:             }
 2935:             if ($skipuser) {
 2936:                 return 0;
 2937:             }
 2938:         }
 2939:     }
 2940:     $type ||= 'any';
 2941:     if (!defined($cdom) || !defined($cnum)) {
 2942:         my $cid  = $env{'request.course.id'};
 2943:         $cdom = $env{'course.'.$cid.'.domain'};
 2944:         $cnum = $env{'course.'.$cid.'.num'};
 2945:     }
 2946:     my $typesref;
 2947:     if (($type eq 'any') || ($type eq 'all')) {
 2948:         $typesref = ['active','previous','future'];
 2949:     } elsif ($type eq 'previous' || $type eq 'future') {
 2950:         $typesref = [$type];
 2951:     }
 2952:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2953:                               $typesref,undef,[$cdom]);
 2954:     my ($tmp) = keys(%roles);
 2955:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2956:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2957:     if (@course_roles > 0) {
 2958:         return 1;
 2959:     }
 2960:     return 0;
 2961: }
 2962: 
 2963: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2964: # input: action, courseID, current domain, intended
 2965: #        path to file, source of file, instruction to parse file for objects,
 2966: #        ref to hash for embedded objects,
 2967: #        ref to hash for codebase of java objects.
 2968: #        reference to scalar to accommodate mime type determined
 2969: #          from File::MMagic if $parser = parse.
 2970: #
 2971: # output: url to file (if action was uploaddoc), 
 2972: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2973: #
 2974: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2975: # course.
 2976: #
 2977: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2978: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2979: #          course's home server.
 2980: #
 2981: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2982: #          be copied from $source (current location) to 
 2983: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2984: #         and will then be copied to
 2985: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2986: #         course's home server.
 2987: #
 2988: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2989: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2990: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2991: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2992: #         in course's home server.
 2993: #
 2994: 
 2995: sub process_coursefile {
 2996:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2997:         $mimetype)=@_;
 2998:     my $fetchresult;
 2999:     my $home=&homeserver($docuname,$docudom);
 3000:     if ($action eq 'propagate') {
 3001:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3002: 			     $home);
 3003:     } else {
 3004:         my $fpath = '';
 3005:         my $fname = $file;
 3006:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3007:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3008:         my $filepath = &build_filepath($fpath);
 3009:         if ($action eq 'copy') {
 3010:             if ($source eq '') {
 3011:                 $fetchresult = 'no source file';
 3012:                 return $fetchresult;
 3013:             } else {
 3014:                 my $destination = $filepath.'/'.$fname;
 3015:                 rename($source,$destination);
 3016:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3017:                                  $home);
 3018:             }
 3019:         } elsif ($action eq 'uploaddoc') {
 3020:             open(my $fh,'>'.$filepath.'/'.$fname);
 3021:             print $fh $env{'form.'.$source};
 3022:             close($fh);
 3023:             if ($parser eq 'parse') {
 3024:                 my $mm = new File::MMagic;
 3025:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3026:                 if ($type eq 'text/html') {
 3027:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3028:                     unless ($parse_result eq 'ok') {
 3029:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3030:                     }
 3031:                 }
 3032:                 if (ref($mimetype)) {
 3033:                     $$mimetype = $type;
 3034:                 } 
 3035:             }
 3036:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3037:                                  $home);
 3038:             if ($fetchresult eq 'ok') {
 3039:                 return '/uploaded/'.$fpath.'/'.$fname;
 3040:             } else {
 3041:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3042:                         ' to host '.$home.': '.$fetchresult);
 3043:                 return '/adm/notfound.html';
 3044:             }
 3045:         }
 3046:     }
 3047:     unless ( $fetchresult eq 'ok') {
 3048:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3049:              ' to host '.$home.': '.$fetchresult);
 3050:     }
 3051:     return $fetchresult;
 3052: }
 3053: 
 3054: sub build_filepath {
 3055:     my ($fpath) = @_;
 3056:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3057:     unless ($fpath eq '') {
 3058:         my @parts=split('/',$fpath);
 3059:         foreach my $part (@parts) {
 3060:             $filepath.= '/'.$part;
 3061:             if ((-e $filepath)!=1) {
 3062:                 mkdir($filepath,0777);
 3063:             }
 3064:         }
 3065:     }
 3066:     return $filepath;
 3067: }
 3068: 
 3069: sub store_edited_file {
 3070:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3071:     my $file = $primary_url;
 3072:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3073:     my $fpath = '';
 3074:     my $fname = $file;
 3075:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3076:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3077:     my $filepath = &build_filepath($fpath);
 3078:     open(my $fh,'>'.$filepath.'/'.$fname);
 3079:     print $fh $content;
 3080:     close($fh);
 3081:     my $home=&homeserver($docuname,$docudom);
 3082:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3083: 			  $home);
 3084:     if ($$fetchresult eq 'ok') {
 3085:         return '/uploaded/'.$fpath.'/'.$fname;
 3086:     } else {
 3087:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3088: 		 ' to host '.$home.': '.$$fetchresult);
 3089:         return '/adm/notfound.html';
 3090:     }
 3091: }
 3092: 
 3093: sub clean_filename {
 3094:     my ($fname,$args)=@_;
 3095: # Replace Windows backslashes by forward slashes
 3096:     $fname=~s/\\/\//g;
 3097:     if (!$args->{'keep_path'}) {
 3098:         # Get rid of everything but the actual filename
 3099: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3100:     }
 3101: # Replace spaces by underscores
 3102:     $fname=~s/\s+/\_/g;
 3103: # Replace all other weird characters by nothing
 3104:     $fname=~s{[^/\w\.\-]}{}g;
 3105: # Replace all .\d. sequences with _\d. so they no longer look like version
 3106: # numbers
 3107:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3108:     return $fname;
 3109: }
 3110: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3111: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3112: # image with the same aspect ratio as the original, but with dimensions which do 
 3113: # not exceed $resizewidth and $resizeheight.
 3114:  
 3115: sub resizeImage {
 3116:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3117:     my $ima = Image::Magick->new;
 3118:     my $resized;
 3119:     if (-e $img_path) {
 3120:         $ima->Read($img_path);
 3121:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3122:             my $width = $ima->Get('width');
 3123:             my $height = $ima->Get('height');
 3124:             if ($width > $resizewidth) {
 3125: 	        my $factor = $width/$resizewidth;
 3126:                 my $newheight = $height/$factor;
 3127:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3128:                 $resized = 1;
 3129:             }
 3130:         }
 3131:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3132:             my $width = $ima->Get('width');
 3133:             my $height = $ima->Get('height');
 3134:             if ($height > $resizeheight) {
 3135:                 my $factor = $height/$resizeheight;
 3136:                 my $newwidth = $width/$factor;
 3137:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3138:                 $resized = 1;
 3139:             }
 3140:         }
 3141:         if ($resized) {
 3142:             $ima->Write($img_path);
 3143:         }
 3144:     }
 3145:     return;
 3146: }
 3147: 
 3148: # --------------- Take an uploaded file and put it into the userfiles directory
 3149: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3150: #                    the desired filename is in $env{"form.$formname.filename"}
 3151: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3152: #                                    canceloverwrite, or ''. 
 3153: #                   if 'coursedoc': upload to the current course
 3154: #                   if 'existingfile': write file to tmp/overwrites directory 
 3155: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3156: #                   $context is passed as argument to &finishuserfileupload
 3157: #        $subdir - directory in userfile to store the file into
 3158: #        $parser - instruction to parse file for objects ($parser = parse)    
 3159: #        $allfiles - reference to hash for embedded objects
 3160: #        $codebase - reference to hash for codebase of java objects
 3161: #        $desuname - username for permanent storage of uploaded file
 3162: #        $dsetudom - domain for permanaent storage of uploaded file
 3163: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3164: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3165: #        $resizewidth - width (pixels) to which to resize uploaded image
 3166: #        $resizeheight - height (pixels) to which to resize uploaded image
 3167: #        $mimetype - reference to scalar to accommodate mime type determined
 3168: #                    from File::MMagic.
 3169: # 
 3170: # output: url of file in userspace, or error: <message> 
 3171: #             or /adm/notfound.html if failure to upload occurse
 3172: 
 3173: sub userfileupload {
 3174:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3175:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3176:     if (!defined($subdir)) { $subdir='unknown'; }
 3177:     my $fname=$env{'form.'.$formname.'.filename'};
 3178:     $fname=&clean_filename($fname);
 3179:     # See if there is anything left
 3180:     unless ($fname) { return 'error: no uploaded file'; }
 3181:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3182:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3183:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3184:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3185:         my $now = time;
 3186:         my $filepath;
 3187:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3188:              $filepath = 'tmp/helprequests/'.$now;
 3189:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3190:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3191:                          '_'.$env{'user.domain'}.'/pending';
 3192:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3193:             my ($docuname,$docudom);
 3194:             if ($destudom) {
 3195:                 $docudom = $destudom;
 3196:             } else {
 3197:                 $docudom = $env{'user.domain'};
 3198:             }
 3199:             if ($destuname) {
 3200:                 $docuname = $destuname;
 3201:             } else {
 3202:                 $docuname = $env{'user.name'};
 3203:             }
 3204:             if (exists($env{'form.group'})) {
 3205:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3206:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3207:             }
 3208:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3209:             if ($context eq 'canceloverwrite') {
 3210:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3211:                 if (-e  $tempfile) {
 3212:                     my @info = stat($tempfile);
 3213:                     if ($info[9] eq $env{'form.timestamp'}) {
 3214:                         unlink($tempfile);
 3215:                     }
 3216:                 }
 3217:                 return;
 3218:             }
 3219:         }
 3220:         # Create the directory if not present
 3221:         my @parts=split(/\//,$filepath);
 3222:         my $fullpath = $perlvar{'lonDaemons'};
 3223:         for (my $i=0;$i<@parts;$i++) {
 3224:             $fullpath .= '/'.$parts[$i];
 3225:             if ((-e $fullpath)!=1) {
 3226:                 mkdir($fullpath,0777);
 3227:             }
 3228:         }
 3229:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3230:         print $fh $env{'form.'.$formname};
 3231:         close($fh);
 3232:         if ($context eq 'existingfile') {
 3233:             my @info = stat($fullpath.'/'.$fname);
 3234:             return ($fullpath.'/'.$fname,$info[9]);
 3235:         } else {
 3236:             return $fullpath.'/'.$fname;
 3237:         }
 3238:     }
 3239:     if ($subdir eq 'scantron') {
 3240:         $fname = 'scantron_orig_'.$fname;
 3241:     } else {
 3242:         $fname="$subdir/$fname";
 3243:     }
 3244:     if ($context eq 'coursedoc') {
 3245: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3246: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3247:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3248:             return &finishuserfileupload($docuname,$docudom,
 3249: 					 $formname,$fname,$parser,$allfiles,
 3250: 					 $codebase,$thumbwidth,$thumbheight,
 3251:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3252:         } else {
 3253:             if ($env{'form.folder'}) {
 3254:                 $fname=$env{'form.folder'}.'/'.$fname;
 3255:             }
 3256:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3257: 				       $fname,$formname,$parser,
 3258: 				       $allfiles,$codebase,$mimetype);
 3259:         }
 3260:     } elsif (defined($destuname)) {
 3261:         my $docuname=$destuname;
 3262:         my $docudom=$destudom;
 3263: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3264: 				     $parser,$allfiles,$codebase,
 3265:                                      $thumbwidth,$thumbheight,
 3266:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3267:     } else {
 3268:         my $docuname=$env{'user.name'};
 3269:         my $docudom=$env{'user.domain'};
 3270:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3271:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3272:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3273:         }
 3274: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3275: 				     $parser,$allfiles,$codebase,
 3276:                                      $thumbwidth,$thumbheight,
 3277:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3278:     }
 3279: }
 3280: 
 3281: sub finishuserfileupload {
 3282:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3283:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3284:     my $path=$docudom.'/'.$docuname.'/';
 3285:     my $filepath=$perlvar{'lonDocRoot'};
 3286:   
 3287:     my ($fnamepath,$file,$fetchthumb);
 3288:     $file=$fname;
 3289:     if ($fname=~m|/|) {
 3290:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3291: 	$path.=$fnamepath.'/';
 3292:     }
 3293:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3294:     my $count;
 3295:     for ($count=4;$count<=$#parts;$count++) {
 3296:         $filepath.="/$parts[$count]";
 3297:         if ((-e $filepath)!=1) {
 3298: 	    mkdir($filepath,0777);
 3299:         }
 3300:     }
 3301: 
 3302: # Save the file
 3303:     {
 3304: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3305: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3306: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3307: 	    return '/adm/notfound.html';
 3308: 	}
 3309:         if ($context eq 'overwrite') {
 3310:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3311:             my $target = $filepath.'/'.$file;
 3312:             if (-e $source) {
 3313:                 my @info = stat($source);
 3314:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3315:                     unless (&File::Copy::move($source,$target)) {
 3316:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3317:                         return "Moving from $source failed";
 3318:                     }
 3319:                 } else {
 3320:                     return "Temporary file: $source had unexpected date/time for last modification";
 3321:                 }
 3322:             } else {
 3323:                 return "Temporary file: $source missing";
 3324:             }
 3325:         } elsif (!print FH ($env{'form.'.$formname})) {
 3326: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3327: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3328: 	    return '/adm/notfound.html';
 3329: 	}
 3330: 	close(FH);
 3331:         if ($resizewidth && $resizeheight) {
 3332:             my $mm = new File::MMagic;
 3333:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3334:             if ($mime_type =~ m{^image/}) {
 3335: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3336:             }  
 3337: 	}
 3338:     }
 3339:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3340:         if (ref($mimetype)) {
 3341:             if ($$mimetype eq '') {
 3342:                 my $mm = new File::MMagic;
 3343:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3344:                 $$mimetype = $type;
 3345:             }
 3346:         }
 3347:     }
 3348:     if ($parser eq 'parse') {
 3349:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3350:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3351:                                                        $allfiles,$codebase);
 3352:             unless ($parse_result eq 'ok') {
 3353:                 &logthis('Failed to parse '.$filepath.$file.
 3354: 	   	         ' for embedded media: '.$parse_result); 
 3355:             }
 3356:         }
 3357:     }
 3358:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3359:         my $input = $filepath.'/'.$file;
 3360:         my $output = $filepath.'/'.'tn-'.$file;
 3361:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3362:         system("convert -sample $thumbsize $input $output");
 3363:         if (-e $filepath.'/'.'tn-'.$file) {
 3364:             $fetchthumb  = 1; 
 3365:         }
 3366:     }
 3367:  
 3368: # Notify homeserver to grep it
 3369: #
 3370:     my $docuhome=&homeserver($docuname,$docudom);	
 3371:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3372:     if ($fetchresult eq 'ok') {
 3373:         if ($fetchthumb) {
 3374:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3375:             if ($thumbresult ne 'ok') {
 3376:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3377:                          $docuhome.': '.$thumbresult);
 3378:             }
 3379:         }
 3380: #
 3381: # Return the URL to it
 3382:         return '/uploaded/'.$path.$file;
 3383:     } else {
 3384:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3385: 		 ': '.$fetchresult);
 3386:         return '/adm/notfound.html';
 3387:     }
 3388: }
 3389: 
 3390: sub extract_embedded_items {
 3391:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3392:     my @state = ();
 3393:     my (%lastids,%related,%shockwave,%flashvars);
 3394:     my %javafiles = (
 3395:                       codebase => '',
 3396:                       code => '',
 3397:                       archive => ''
 3398:                     );
 3399:     my %mediafiles = (
 3400:                       src => '',
 3401:                       movie => '',
 3402:                      );
 3403:     my $p;
 3404:     if ($content) {
 3405:         $p = HTML::LCParser->new($content);
 3406:     } else {
 3407:         $p = HTML::LCParser->new($fullpath);
 3408:     }
 3409:     while (my $t=$p->get_token()) {
 3410: 	if ($t->[0] eq 'S') {
 3411: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3412: 	    push(@state, $tagname);
 3413:             if (lc($tagname) eq 'allow') {
 3414:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3415:             }
 3416: 	    if (lc($tagname) eq 'img') {
 3417: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3418: 	    }
 3419: 	    if (lc($tagname) eq 'a') {
 3420:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3421:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3422:                 }
 3423: 	    }
 3424:             if (lc($tagname) eq 'script') {
 3425:                 my $src;
 3426:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3427:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3428:                 } else {
 3429:                     if ($attr->{'src'} ne '') {
 3430:                         $src = $attr->{'src'};
 3431:                         &add_filetype($allfiles,$src,'src');
 3432:                     }
 3433:                 }
 3434:                 my $text = $p->get_trimmed_text();
 3435:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3436:                     my @swfargs = split(/,/,$1);
 3437:                     foreach my $item (@swfargs) {
 3438:                         $item =~ s/["']//g;
 3439:                         $item =~ s/^\s+//;
 3440:                         $item =~ s/\s+$//;
 3441:                     }
 3442:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3443:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3444:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3445:                         } else {
 3446:                             $related{$swfargs[0]} = [$swfargs[2]];
 3447:                         }
 3448:                     }
 3449:                 }
 3450:             }
 3451:             if (lc($tagname) eq 'link') {
 3452:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3453:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3454:                 }
 3455:             }
 3456: 	    if (lc($tagname) eq 'object' ||
 3457: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3458: 		foreach my $item (keys(%javafiles)) {
 3459: 		    $javafiles{$item} = '';
 3460: 		}
 3461:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3462:                     $lastids{lc($tagname)} = $attr->{'id'};
 3463:                 }
 3464: 	    }
 3465: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3466: 		my $name = lc($attr->{'name'});
 3467: 		foreach my $item (keys(%javafiles)) {
 3468: 		    if ($name eq $item) {
 3469: 			$javafiles{$item} = $attr->{'value'};
 3470: 			last;
 3471: 		    }
 3472: 		}
 3473:                 my $pathfrom;
 3474: 		foreach my $item (keys(%mediafiles)) {
 3475: 		    if ($name eq $item) {
 3476:                         $pathfrom = $attr->{'value'};
 3477:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3478: 			&add_filetype($allfiles,$pathfrom,$name);
 3479: 			last;
 3480: 		    }
 3481: 		}
 3482:                 if ($name eq 'flashvars') {
 3483:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3484:                 }
 3485:                 if ($pathfrom ne '') {
 3486:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3487:                                          $pathfrom);
 3488:                 }
 3489: 	    }
 3490: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3491: 		foreach my $item (keys(%javafiles)) {
 3492: 		    if ($attr->{$item}) {
 3493: 			$javafiles{$item} = $attr->{$item};
 3494: 			last;
 3495: 		    }
 3496: 		}
 3497: 		foreach my $item (keys(%mediafiles)) {
 3498: 		    if ($attr->{$item}) {
 3499: 			&add_filetype($allfiles,$attr->{$item},$item);
 3500: 			last;
 3501: 		    }
 3502: 		}
 3503:                 if (lc($tagname) eq 'embed') {
 3504:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3505:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3506:                                              $attr->{'src'});
 3507:                     }
 3508:                 }
 3509: 	    }
 3510:             if (lc($tagname) eq 'iframe') {
 3511:                 my $src = $attr->{'src'} ;
 3512:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3513:                     &add_filetype($allfiles,$src,'src');
 3514:                 } elsif ($src =~ m{^/}) {
 3515:                     if ($env{'request.course.id'}) {
 3516:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3517:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3518:                         my $url = &hreflocation('',$fullpath);
 3519:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3520:                             my $relpath = $1;
 3521:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3522:                                 &add_filetype($allfiles,$1,'src');
 3523:                             }
 3524:                         }
 3525:                     }
 3526:                 }
 3527:             }
 3528:             if ($t->[4] =~ m{/>$}) {
 3529:                 pop(@state);
 3530:             }
 3531: 	} elsif ($t->[0] eq 'E') {
 3532: 	    my ($tagname) = ($t->[1]);
 3533: 	    if ($javafiles{'codebase'} ne '') {
 3534: 		$javafiles{'codebase'} .= '/';
 3535: 	    }  
 3536: 	    if (lc($tagname) eq 'applet' ||
 3537: 		lc($tagname) eq 'object' ||
 3538: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3539: 		) {
 3540: 		foreach my $item (keys(%javafiles)) {
 3541: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3542: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3543: 			&add_filetype($allfiles,$file,$item);
 3544: 		    }
 3545: 		}
 3546: 	    } 
 3547: 	    pop @state;
 3548: 	}
 3549:     }
 3550:     foreach my $id (sort(keys(%flashvars))) {
 3551:         if ($shockwave{$id} ne '') {
 3552:             my @pairs = split(/\&/,$flashvars{$id});
 3553:             foreach my $pair (@pairs) {
 3554:                 my ($key,$value) = split(/\=/,$pair);
 3555:                 if ($key eq 'thumb') {
 3556:                     &add_filetype($allfiles,$value,$key);
 3557:                 } elsif ($key eq 'content') {
 3558:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3559:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3560:                     if ($ext ne '') {
 3561:                         &add_filetype($allfiles,$path.$value,$ext);
 3562:                     }
 3563:                 }
 3564:             }
 3565:         }
 3566:     }
 3567:     return 'ok';
 3568: }
 3569: 
 3570: sub add_filetype {
 3571:     my ($allfiles,$file,$type)=@_;
 3572:     if (exists($allfiles->{$file})) {
 3573: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3574: 	    push(@{$allfiles->{$file}}, &escape($type));
 3575: 	}
 3576:     } else {
 3577: 	@{$allfiles->{$file}} = (&escape($type));
 3578:     }
 3579: }
 3580: 
 3581: sub embedded_dependency {
 3582:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3583:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3584:         if (($identifier ne '') &&
 3585:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3586:             ($pathfrom ne '')) {
 3587:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3588:             foreach my $dep (@{$related->{$identifier}}) {
 3589:                 &add_filetype($allfiles,$path.$dep,'object');
 3590:             }
 3591:         }
 3592:     }
 3593:     return;
 3594: }
 3595: 
 3596: sub removeuploadedurl {
 3597:     my ($url)=@_;	
 3598:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3599:     return &removeuserfile($uname,$udom,$fname);
 3600: }
 3601: 
 3602: sub removeuserfile {
 3603:     my ($docuname,$docudom,$fname)=@_;
 3604:     my $home=&homeserver($docuname,$docudom);    
 3605:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3606:     if ($result eq 'ok') {	
 3607:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3608:             my $metafile = $fname.'.meta';
 3609:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3610: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3611:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3612:             my $sqlresult = 
 3613:                 &update_portfolio_table($docuname,$docudom,$file,
 3614:                                         'portfolio_metadata',$group,
 3615:                                         'delete');
 3616:         }
 3617:     }
 3618:     return $result;
 3619: }
 3620: 
 3621: sub mkdiruserfile {
 3622:     my ($docuname,$docudom,$dir)=@_;
 3623:     my $home=&homeserver($docuname,$docudom);
 3624:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3625: }
 3626: 
 3627: sub renameuserfile {
 3628:     my ($docuname,$docudom,$old,$new)=@_;
 3629:     my $home=&homeserver($docuname,$docudom);
 3630:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3631:                         &escape("$old").':'.&escape("$new"),$home);
 3632:     if ($result eq 'ok') {
 3633:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3634:             my $oldmeta = $old.'.meta';
 3635:             my $newmeta = $new.'.meta';
 3636:             my $metaresult = 
 3637:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3638: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3639:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3640:             my $sqlresult = 
 3641:                 &update_portfolio_table($docuname,$docudom,$file,
 3642:                                         'portfolio_metadata',$group,
 3643:                                         'delete');
 3644:         }
 3645:     }
 3646:     return $result;
 3647: }
 3648: 
 3649: # ------------------------------------------------------------------------- Log
 3650: 
 3651: sub log {
 3652:     my ($dom,$nam,$hom,$what)=@_;
 3653:     return critical("log:$dom:$nam:$what",$hom);
 3654: }
 3655: 
 3656: # ------------------------------------------------------------------ Course Log
 3657: #
 3658: # This routine flushes several buffers of non-mission-critical nature
 3659: #
 3660: 
 3661: sub flushcourselogs {
 3662:     &logthis('Flushing log buffers');
 3663: #
 3664: # course logs
 3665: # This is a log of all transactions in a course, which can be used
 3666: # for data mining purposes
 3667: #
 3668: # It also collects the courseid database, which lists last transaction
 3669: # times and course titles for all courseids
 3670: #
 3671:     my %courseidbuffer=();
 3672:     foreach my $crsid (keys(%courselogs)) {
 3673:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3674: 		          &escape($courselogs{$crsid}),
 3675: 		          $coursehombuf{$crsid}) eq 'ok') {
 3676: 	    delete $courselogs{$crsid};
 3677:         } else {
 3678:             &logthis('Failed to flush log buffer for '.$crsid);
 3679:             if (length($courselogs{$crsid})>40000) {
 3680:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3681:                         " exceeded maximum size, deleting.</font>");
 3682:                delete $courselogs{$crsid};
 3683:             }
 3684:         }
 3685:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3686:             'description' => $coursedescrbuf{$crsid},
 3687:             'inst_code'    => $courseinstcodebuf{$crsid},
 3688:             'type'        => $coursetypebuf{$crsid},
 3689:             'owner'       => $courseownerbuf{$crsid},
 3690:         };
 3691:     }
 3692: #
 3693: # Write course id database (reverse lookup) to homeserver of courses 
 3694: # Is used in pickcourse
 3695: #
 3696:     foreach my $crs_home (keys(%courseidbuffer)) {
 3697:         my $response = &courseidput(&host_domain($crs_home),
 3698:                                     $courseidbuffer{$crs_home},
 3699:                                     $crs_home,'timeonly');
 3700:     }
 3701: #
 3702: # File accesses
 3703: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3704: #
 3705:     foreach my $entry (keys(%accesshash)) {
 3706:         if ($entry =~ /___count$/) {
 3707:             my ($dom,$name);
 3708:             ($dom,$name,undef)=
 3709: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3710:             if (! defined($dom) || $dom eq '' || 
 3711:                 ! defined($name) || $name eq '') {
 3712:                 my $cid = $env{'request.course.id'};
 3713:                 $dom  = $env{'request.'.$cid.'.domain'};
 3714:                 $name = $env{'request.'.$cid.'.num'};
 3715:             }
 3716:             my $value = $accesshash{$entry};
 3717:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3718:             my %temphash=($url => $value);
 3719:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3720:             if ($result eq 'ok') {
 3721:                 delete $accesshash{$entry};
 3722:             }
 3723:         } else {
 3724:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3725:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3726:             my %temphash=($entry => $accesshash{$entry});
 3727:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3728:                 delete $accesshash{$entry};
 3729:             }
 3730:         }
 3731:     }
 3732: #
 3733: # Roles
 3734: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3735: #
 3736:     foreach my $entry (keys(%userrolehash)) {
 3737:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3738: 	    split(/\:/,$entry);
 3739:         if (&Apache::lonnet::put('nohist_userroles',
 3740:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3741:                 $rudom,$runame) eq 'ok') {
 3742: 	    delete $userrolehash{$entry};
 3743:         }
 3744:     }
 3745: #
 3746: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3747: #
 3748:     my %domrolebuffer = ();
 3749:     foreach my $entry (keys(%domainrolehash)) {
 3750:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3751:         if ($domrolebuffer{$rudom}) {
 3752:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3753:                       '='.&escape($domainrolehash{$entry});
 3754:         } else {
 3755:             $domrolebuffer{$rudom}.=&escape($entry).
 3756:                       '='.&escape($domainrolehash{$entry});
 3757:         }
 3758:         delete $domainrolehash{$entry};
 3759:     }
 3760:     foreach my $dom (keys(%domrolebuffer)) {
 3761: 	my %servers = &get_servers($dom,'library');
 3762: 	foreach my $tryserver (keys(%servers)) {
 3763: 	    unless (&reply('domroleput:'.$dom.':'.
 3764: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3765: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3766: 	    }
 3767:         }
 3768:     }
 3769:     $dumpcount++;
 3770: }
 3771: 
 3772: sub courselog {
 3773:     my $what=shift;
 3774:     $what=time.':'.$what;
 3775:     unless ($env{'request.course.id'}) { return ''; }
 3776:     $coursedombuf{$env{'request.course.id'}}=
 3777:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3778:     $coursenumbuf{$env{'request.course.id'}}=
 3779:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3780:     $coursehombuf{$env{'request.course.id'}}=
 3781:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3782:     $coursedescrbuf{$env{'request.course.id'}}=
 3783:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3784:     $courseinstcodebuf{$env{'request.course.id'}}=
 3785:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3786:     $courseownerbuf{$env{'request.course.id'}}=
 3787:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3788:     $coursetypebuf{$env{'request.course.id'}}=
 3789:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3790:     if (defined $courselogs{$env{'request.course.id'}}) {
 3791: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3792:     } else {
 3793: 	$courselogs{$env{'request.course.id'}}.=$what;
 3794:     }
 3795:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3796: 	&flushcourselogs();
 3797:     }
 3798: }
 3799: 
 3800: sub courseacclog {
 3801:     my $fnsymb=shift;
 3802:     unless ($env{'request.course.id'}) { return ''; }
 3803:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3804:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3805:         $what.=':POST';
 3806:         # FIXME: Probably ought to escape things....
 3807: 	foreach my $key (keys(%env)) {
 3808:             if ($key=~/^form\.(.*)/) {
 3809:                 my $formitem = $1;
 3810:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3811:                     $what.=':'.$formitem.'='.$env{$key};
 3812:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3813:                     $what.=':'.$formitem.'='.$env{$key};
 3814:                 }
 3815:             }
 3816:         }
 3817:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3818:         # FIXME: We should not be depending on a form parameter that someone
 3819:         # editing lonsearchcat.pm might change in the future.
 3820:         if ($env{'form.phase'} eq 'course_search') {
 3821:             $what.= ':POST';
 3822:             # FIXME: Probably ought to escape things....
 3823:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3824:                                  'crsdiscuss') {
 3825:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3826:             }
 3827:         }
 3828:     }
 3829:     &courselog($what);
 3830: }
 3831: 
 3832: sub countacc {
 3833:     my $url=&declutter(shift);
 3834:     return if (! defined($url) || $url eq '');
 3835:     unless ($env{'request.course.id'}) { return ''; }
 3836: #
 3837: # Mark that this url was used in this course
 3838: #
 3839:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3840: #
 3841: # Increase the access count for this resource in this child process
 3842: #
 3843:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3844:     $accesshash{$key}++;
 3845: }
 3846: 
 3847: sub linklog {
 3848:     my ($from,$to)=@_;
 3849:     $from=&declutter($from);
 3850:     $to=&declutter($to);
 3851:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3852:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3853: }
 3854: 
 3855: sub statslog {
 3856:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3857:     if ($users<2) { return; }
 3858:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3859:             'course'       => $env{'request.course.id'},
 3860:             'sections'     => '"all"',
 3861:             'num_students' => $users,
 3862:             'part'         => $part,
 3863:             'symb'         => $symb,
 3864:             'mean_tries'   => $av_attempts,
 3865:             'deg_of_diff'  => $degdiff});
 3866:     foreach my $key (keys(%dynstore)) {
 3867:         $accesshash{$key}=$dynstore{$key};
 3868:     }
 3869: }
 3870:   
 3871: sub userrolelog {
 3872:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3873:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3874:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3875:        $userrolehash
 3876:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3877:                     =$tend.':'.$tstart;
 3878:     }
 3879:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3880:        $userrolehash
 3881:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3882:                     =$tend.':'.$tstart;
 3883:     }
 3884:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3885:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3886:        $domainrolehash
 3887:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3888:                     = $tend.':'.$tstart;
 3889:     }
 3890: }
 3891: 
 3892: sub courserolelog {
 3893:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3894:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3895:         my $cdom = $1;
 3896:         my $cnum = $2;
 3897:         my $sec = $3;
 3898:         my $namespace = 'rolelog';
 3899:         my %storehash = (
 3900:                            role    => $trole,
 3901:                            start   => $tstart,
 3902:                            end     => $tend,
 3903:                            selfenroll => $selfenroll,
 3904:                            context    => $context,
 3905:                         );
 3906:         if ($trole eq 'gr') {
 3907:             $namespace = 'groupslog';
 3908:             $storehash{'group'} = $sec;
 3909:         } else {
 3910:             $storehash{'section'} = $sec;
 3911:         }
 3912:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3913:                    $domain,$cnum,$cdom);
 3914:         if (($trole ne 'st') || ($sec ne '')) {
 3915:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3916:         }
 3917:     }
 3918:     return;
 3919: }
 3920: 
 3921: sub domainrolelog {
 3922:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3923:     if ($area =~ m{^/($match_domain)/$}) {
 3924:         my $cdom = $1;
 3925:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3926:         my $namespace = 'rolelog';
 3927:         my %storehash = (
 3928:                            role    => $trole,
 3929:                            start   => $tstart,
 3930:                            end     => $tend,
 3931:                            context => $context,
 3932:                         );
 3933:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3934:                    $domain,$domconfiguser,$cdom);
 3935:     }
 3936:     return;
 3937: 
 3938: }
 3939: 
 3940: sub coauthorrolelog {
 3941:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3942:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3943:         my $audom = $1;
 3944:         my $auname = $2;
 3945:         my $namespace = 'rolelog';
 3946:         my %storehash = (
 3947:                            role    => $trole,
 3948:                            start   => $tstart,
 3949:                            end     => $tend,
 3950:                            context => $context,
 3951:                         );
 3952:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3953:                    $domain,$auname,$audom);
 3954:     }
 3955:     return;
 3956: }
 3957: 
 3958: sub get_course_adv_roles {
 3959:     my ($cid,$codes) = @_;
 3960:     $cid=$env{'request.course.id'} unless (defined($cid));
 3961:     my %coursehash=&coursedescription($cid);
 3962:     my $crstype = &Apache::loncommon::course_type($cid);
 3963:     my %nothide=();
 3964:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3965:         if ($user !~ /:/) {
 3966: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3967:         } else {
 3968:             $nothide{$user}=1;
 3969:         }
 3970:     }
 3971:     my @possdoms = ($coursehash{'domain'});
 3972:     if ($coursehash{'checkforpriv'}) {
 3973:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3974:     }
 3975:     my %returnhash=();
 3976:     my %dumphash=
 3977:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3978:     my $now=time;
 3979:     my %privileged;
 3980:     foreach my $entry (keys(%dumphash)) {
 3981: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3982:         if (($tstart) && ($tstart<0)) { next; }
 3983:         if (($tend) && ($tend<$now)) { next; }
 3984:         if (($tstart) && ($now<$tstart)) { next; }
 3985:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3986: 	if ($username eq '' || $domain eq '') { next; }
 3987:         if ((&privileged($username,$domain,\@possdoms)) &&
 3988:             (!$nothide{$username.':'.$domain})) { next; }
 3989: 	if ($role eq 'cr') { next; }
 3990:         if ($codes) {
 3991:             if ($section) { $role .= ':'.$section; }
 3992:             if ($returnhash{$role}) {
 3993:                 $returnhash{$role}.=','.$username.':'.$domain;
 3994:             } else {
 3995:                 $returnhash{$role}=$username.':'.$domain;
 3996:             }
 3997:         } else {
 3998:             my $key=&plaintext($role,$crstype);
 3999:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4000:             if ($returnhash{$key}) {
 4001: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4002:             } else {
 4003:                 $returnhash{$key}=$username.':'.$domain;
 4004:             }
 4005:         }
 4006:     }
 4007:     return %returnhash;
 4008: }
 4009: 
 4010: sub get_my_roles {
 4011:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4012:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4013:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4014:     my (%dumphash,%nothide);
 4015:     if ($context eq 'userroles') {
 4016:         %dumphash = &dump('roles',$udom,$uname);
 4017:     } else {
 4018:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4019:         if ($hidepriv) {
 4020:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4021:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4022:                 if ($user !~ /:/) {
 4023:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4024:                 } else {
 4025:                     $nothide{$user} = 1;
 4026:                 }
 4027:             }
 4028:         }
 4029:     }
 4030:     my %returnhash=();
 4031:     my $now=time;
 4032:     my %privileged;
 4033:     foreach my $entry (keys(%dumphash)) {
 4034:         my ($role,$tend,$tstart);
 4035:         if ($context eq 'userroles') {
 4036:             next if ($entry =~ /^rolesdef/);
 4037: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4038:         } else {
 4039:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4040:         }
 4041:         if (($tstart) && ($tstart<0)) { next; }
 4042:         my $status = 'active';
 4043:         if (($tend) && ($tend<=$now)) {
 4044:             $status = 'previous';
 4045:         } 
 4046:         if (($tstart) && ($now<$tstart)) {
 4047:             $status = 'future';
 4048:         }
 4049:         if (ref($types) eq 'ARRAY') {
 4050:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4051:                 next;
 4052:             } 
 4053:         } else {
 4054:             if ($status ne 'active') {
 4055:                 next;
 4056:             }
 4057:         }
 4058:         my ($rolecode,$username,$domain,$section,$area);
 4059:         if ($context eq 'userroles') {
 4060:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4061:             (undef,$domain,$username,$section) = split(/\//,$area);
 4062:         } else {
 4063:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4064:         }
 4065:         if (ref($roledoms) eq 'ARRAY') {
 4066:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4067:                 next;
 4068:             }
 4069:         }
 4070:         if (ref($roles) eq 'ARRAY') {
 4071:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4072:                 if ($role =~ /^cr\//) {
 4073:                     if (!grep(/^cr$/,@{$roles})) {
 4074:                         next;
 4075:                     }
 4076:                 } elsif ($role =~ /^gr\//) {
 4077:                     if (!grep(/^gr$/,@{$roles})) {
 4078:                         next;
 4079:                     }
 4080:                 } else {
 4081:                     next;
 4082:                 }
 4083:             }
 4084:         }
 4085:         if ($hidepriv) {
 4086:             my @privroles = ('dc','su');
 4087:             if ($context eq 'userroles') {
 4088:                 next if (grep(/^\Q$role\E$/,@privroles));
 4089:             } else {
 4090:                 my $possdoms = [$domain];
 4091:                 if (ref($roledoms) eq 'ARRAY') {
 4092:                    push(@{$possdoms},@{$roledoms}); 
 4093:                 }
 4094:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4095:                     if (!$nothide{$username.':'.$domain}) {
 4096:                         next;
 4097:                     }
 4098:                 }
 4099:             }
 4100:         }
 4101:         if ($withsec) {
 4102:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4103:                 $tstart.':'.$tend;
 4104:         } else {
 4105:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4106:         }
 4107:     }
 4108:     return %returnhash;
 4109: }
 4110: 
 4111: # ----------------------------------------------------- Frontpage Announcements
 4112: #
 4113: #
 4114: 
 4115: sub postannounce {
 4116:     my ($server,$text)=@_;
 4117:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4118:     unless ($text=~/\w/) { $text=''; }
 4119:     return &reply('setannounce:'.&escape($text),$server);
 4120: }
 4121: 
 4122: sub getannounce {
 4123: 
 4124:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4125: 	my $announcement='';
 4126: 	while (my $line = <$fh>) { $announcement .= $line; }
 4127: 	close($fh);
 4128: 	if ($announcement=~/\w/) { 
 4129: 	    return 
 4130:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4131:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4132: 	} else {
 4133: 	    return '';
 4134: 	}
 4135:     } else {
 4136: 	return '';
 4137:     }
 4138: }
 4139: 
 4140: # ---------------------------------------------------------- Course ID routines
 4141: # Deal with domain's nohist_courseid.db files
 4142: #
 4143: 
 4144: sub courseidput {
 4145:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4146:     return unless (ref($storehash) eq 'HASH');
 4147:     my $outcome;
 4148:     if ($caller eq 'timeonly') {
 4149:         my $cids = '';
 4150:         foreach my $item (keys(%$storehash)) {
 4151:             $cids.=&escape($item).'&';
 4152:         }
 4153:         $cids=~s/\&$//;
 4154:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4155:                           $coursehome);       
 4156:     } else {
 4157:         my $items = '';
 4158:         foreach my $item (keys(%$storehash)) {
 4159:             $items.= &escape($item).'='.
 4160:                      &freeze_escape($$storehash{$item}).'&';
 4161:         }
 4162:         $items=~s/\&$//;
 4163:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4164:                           $coursehome);
 4165:     }
 4166:     if ($outcome eq 'unknown_cmd') {
 4167:         my $what;
 4168:         foreach my $cid (keys(%$storehash)) {
 4169:             $what .= &escape($cid).'=';
 4170:             foreach my $item ('description','inst_code','owner','type') {
 4171:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4172:             }
 4173:             $what =~ s/\:$/&/;
 4174:         }
 4175:         $what =~ s/\&$//;  
 4176:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4177:     } else {
 4178:         return $outcome;
 4179:     }
 4180: }
 4181: 
 4182: sub courseiddump {
 4183:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4184:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4185:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4186:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4187:     my $as_hash = 1;
 4188:     my %returnhash;
 4189:     if (!$domfilter) { $domfilter=''; }
 4190:     my %libserv = &all_library();
 4191:     foreach my $tryserver (keys(%libserv)) {
 4192:         if ( (  $hostidflag == 1 
 4193: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4194: 	     || (!defined($hostidflag)) ) {
 4195: 
 4196: 	    if (($domfilter eq '') ||
 4197: 		(&host_domain($tryserver) eq $domfilter)) {
 4198:                 my $rep;
 4199:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4200:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4201:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4202:                                 &escape($descfilter), &escape($instcodefilter), 
 4203:                                 &escape($ownerfilter), &escape($coursefilter),
 4204:                                 &escape($typefilter), &escape($regexp_ok), 
 4205:                                 $as_hash, &escape($selfenrollonly), 
 4206:                                 &escape($catfilter), $showhidden, $caller, 
 4207:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4208:                                 &escape($createdbefore), &escape($createdafter), 
 4209:                                 &escape($creationcontext), $domcloner)));
 4210:                 } else {
 4211:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4212:                              $sincefilter.':'.&escape($descfilter).':'.
 4213:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4214:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4215:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4216:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4217:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4218:                              &escape($cc_clone).':'.$cloneonly.':'.
 4219:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4220:                              &escape($creationcontext).':'.$domcloner,
 4221:                              $tryserver);
 4222:                 }
 4223:                      
 4224:                 my @pairs=split(/\&/,$rep);
 4225:                 foreach my $item (@pairs) {
 4226:                     my ($key,$value)=split(/\=/,$item,2);
 4227:                     $key = &unescape($key);
 4228:                     next if ($key =~ /^error: 2 /);
 4229:                     my $result = &thaw_unescape($value);
 4230:                     if (ref($result) eq 'HASH') {
 4231:                         $returnhash{$key}=$result;
 4232:                     } else {
 4233:                         my @responses = split(/:/,$value);
 4234:                         my @items = ('description','inst_code','owner','type');
 4235:                         for (my $i=0; $i<@responses; $i++) {
 4236:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4237:                         }
 4238:                     }
 4239:                 }
 4240:             }
 4241:         }
 4242:     }
 4243:     return %returnhash;
 4244: }
 4245: 
 4246: sub courselastaccess {
 4247:     my ($cdom,$cnum,$hostidref) = @_;
 4248:     my %returnhash;
 4249:     if ($cdom && $cnum) {
 4250:         my $chome = &homeserver($cnum,$cdom);
 4251:         if ($chome ne 'no_host') {
 4252:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4253:             &extract_lastaccess(\%returnhash,$rep);
 4254:         }
 4255:     } else {
 4256:         if (!$cdom) { $cdom=''; }
 4257:         my %libserv = &all_library();
 4258:         foreach my $tryserver (keys(%libserv)) {
 4259:             if (ref($hostidref) eq 'ARRAY') {
 4260:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4261:             } 
 4262:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4263:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4264:                 &extract_lastaccess(\%returnhash,$rep);
 4265:             }
 4266:         }
 4267:     }
 4268:     return %returnhash;
 4269: }
 4270: 
 4271: sub extract_lastaccess {
 4272:     my ($returnhash,$rep) = @_;
 4273:     if (ref($returnhash) eq 'HASH') {
 4274:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4275:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4276:                  $rep eq '') {
 4277:             my @pairs=split(/\&/,$rep);
 4278:             foreach my $item (@pairs) {
 4279:                 my ($key,$value)=split(/\=/,$item,2);
 4280:                 $key = &unescape($key);
 4281:                 next if ($key =~ /^error: 2 /);
 4282:                 $returnhash->{$key} = &thaw_unescape($value);
 4283:             }
 4284:         }
 4285:     }
 4286:     return;
 4287: }
 4288: 
 4289: # ---------------------------------------------------------- DC e-mail
 4290: 
 4291: sub dcmailput {
 4292:     my ($domain,$msgid,$message,$server)=@_;
 4293:     my $status = &Apache::lonnet::critical(
 4294:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4295:        &escape($message),$server);
 4296:     return $status;
 4297: }
 4298: 
 4299: sub dcmaildump {
 4300:     my ($dom,$startdate,$enddate,$senders) = @_;
 4301:     my %returnhash=();
 4302: 
 4303:     if (defined(&domain($dom,'primary'))) {
 4304:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4305:                                                          &escape($enddate).':';
 4306: 	my @esc_senders=map { &escape($_)} @$senders;
 4307: 	$cmd.=&escape(join('&',@esc_senders));
 4308: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4309:             my ($key,$value) = split(/\=/,$line,2);
 4310:             if (($key) && ($value)) {
 4311:                 $returnhash{&unescape($key)} = &unescape($value);
 4312:             }
 4313:         }
 4314:     }
 4315:     return %returnhash;
 4316: }
 4317: # ---------------------------------------------------------- Domain roles
 4318: 
 4319: sub get_domain_roles {
 4320:     my ($dom,$roles,$startdate,$enddate)=@_;
 4321:     if ((!defined($startdate)) || ($startdate eq '')) {
 4322:         $startdate = '.';
 4323:     }
 4324:     if ((!defined($enddate)) || ($enddate eq '')) {
 4325:         $enddate = '.';
 4326:     }
 4327:     my $rolelist;
 4328:     if (ref($roles) eq 'ARRAY') {
 4329:         $rolelist = join('&',@{$roles});
 4330:     }
 4331:     my %personnel = ();
 4332: 
 4333:     my %servers = &get_servers($dom,'library');
 4334:     foreach my $tryserver (keys(%servers)) {
 4335: 	%{$personnel{$tryserver}}=();
 4336: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4337: 					    &escape($startdate).':'.
 4338: 					    &escape($enddate).':'.
 4339: 					    &escape($rolelist), $tryserver))) {
 4340: 	    my ($key,$value) = split(/\=/,$line,2);
 4341: 	    if (($key) && ($value)) {
 4342: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4343: 	    }
 4344: 	}
 4345:     }
 4346:     return %personnel;
 4347: }
 4348: 
 4349: # ----------------------------------------------------------- Interval timing 
 4350: 
 4351: {
 4352: # Caches needed for speedup of navmaps
 4353: # We don't want to cache this for very long at all (5 seconds at most)
 4354: # 
 4355: # The user for whom we cache
 4356: my $cachedkey='';
 4357: # The cached times for this user
 4358: my %cachedtimes=();
 4359: # When this was last done
 4360: my $cachedtime=();
 4361: 
 4362: sub load_all_first_access {
 4363:     my ($uname,$udom)=@_;
 4364:     if (($cachedkey eq $uname.':'.$udom) &&
 4365:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4366:         return;
 4367:     }
 4368:     $cachedtime=time;
 4369:     $cachedkey=$uname.':'.$udom;
 4370:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4371: }
 4372: 
 4373: sub get_first_access {
 4374:     my ($type,$argsymb,$argmap)=@_;
 4375:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4376:     if ($argsymb) { $symb=$argsymb; }
 4377:     my ($map,$id,$res)=&decode_symb($symb);
 4378:     if ($argmap) { $map = $argmap; }
 4379:     if ($type eq 'course') {
 4380: 	$res='course';
 4381:     } elsif ($type eq 'map') {
 4382: 	$res=&symbread($map);
 4383:     } else {
 4384: 	$res=$symb;
 4385:     }
 4386:     &load_all_first_access($uname,$udom);
 4387:     return $cachedtimes{"$courseid\0$res"};
 4388: }
 4389: 
 4390: sub set_first_access {
 4391:     my ($type,$interval)=@_;
 4392:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4393:     my ($map,$id,$res)=&decode_symb($symb);
 4394:     if ($type eq 'course') {
 4395: 	$res='course';
 4396:     } elsif ($type eq 'map') {
 4397: 	$res=&symbread($map);
 4398:     } else {
 4399: 	$res=$symb;
 4400:     }
 4401:     $cachedkey='';
 4402:     my $firstaccess=&get_first_access($type,$symb,$map);
 4403:     if (!$firstaccess) {
 4404:         my $start = time;
 4405: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4406:                           $udom,$uname);
 4407:         if ($putres eq 'ok') {
 4408:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4409:                  $udom,$uname); 
 4410:             &appenv(
 4411:                      {
 4412:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4413:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4414:                      }
 4415:                   );
 4416:         }
 4417:         return $putres;
 4418:     }
 4419:     return 'already_set';
 4420: }
 4421: }
 4422: # --------------------------------------------- Set Expire Date for Spreadsheet
 4423: 
 4424: sub expirespread {
 4425:     my ($uname,$udom,$stype,$usymb)=@_;
 4426:     my $cid=$env{'request.course.id'}; 
 4427:     if ($cid) {
 4428:        my $now=time;
 4429:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4430:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4431:                             $env{'course.'.$cid.'.num'}.
 4432: 	        	    ':nohist_expirationdates:'.
 4433:                             &escape($key).'='.$now,
 4434:                             $env{'course.'.$cid.'.home'})
 4435:     }
 4436:     return 'ok';
 4437: }
 4438: 
 4439: # ----------------------------------------------------- Devalidate Spreadsheets
 4440: 
 4441: sub devalidate {
 4442:     my ($symb,$uname,$udom)=@_;
 4443:     my $cid=$env{'request.course.id'}; 
 4444:     if ($cid) {
 4445:         # delete the stored spreadsheets for
 4446:         # - the student level sheet of this user in course's homespace
 4447:         # - the assessment level sheet for this resource 
 4448:         #   for this user in user's homespace
 4449: 	# - current conditional state info
 4450: 	my $key=$uname.':'.$udom.':';
 4451:         my $status=
 4452: 	    &del('nohist_calculatedsheets',
 4453: 		 [$key.'studentcalc:'],
 4454: 		 $env{'course.'.$cid.'.domain'},
 4455: 		 $env{'course.'.$cid.'.num'})
 4456: 		.' '.
 4457: 	    &del('nohist_calculatedsheets_'.$cid,
 4458: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4459:         unless ($status eq 'ok ok') {
 4460:            &logthis('Could not devalidate spreadsheet '.
 4461:                     $uname.' at '.$udom.' for '.
 4462: 		    $symb.': '.$status);
 4463:         }
 4464: 	&delenv('user.state.'.$cid);
 4465:     }
 4466: }
 4467: 
 4468: sub get_scalar {
 4469:     my ($string,$end) = @_;
 4470:     my $value;
 4471:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4472: 	$value = $1;
 4473:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4474: 	$value = $1;
 4475:     }
 4476:     return &unescape($value);
 4477: }
 4478: 
 4479: sub array2str {
 4480:   my (@array) = @_;
 4481:   my $result=&arrayref2str(\@array);
 4482:   $result=~s/^__ARRAY_REF__//;
 4483:   $result=~s/__END_ARRAY_REF__$//;
 4484:   return $result;
 4485: }
 4486: 
 4487: sub arrayref2str {
 4488:   my ($arrayref) = @_;
 4489:   my $result='__ARRAY_REF__';
 4490:   foreach my $elem (@$arrayref) {
 4491:     if(ref($elem) eq 'ARRAY') {
 4492:       $result.=&arrayref2str($elem).'&';
 4493:     } elsif(ref($elem) eq 'HASH') {
 4494:       $result.=&hashref2str($elem).'&';
 4495:     } elsif(ref($elem)) {
 4496:       #print("Got a ref of ".(ref($elem))." skipping.");
 4497:     } else {
 4498:       $result.=&escape($elem).'&';
 4499:     }
 4500:   }
 4501:   $result=~s/\&$//;
 4502:   $result .= '__END_ARRAY_REF__';
 4503:   return $result;
 4504: }
 4505: 
 4506: sub hash2str {
 4507:   my (%hash) = @_;
 4508:   my $result=&hashref2str(\%hash);
 4509:   $result=~s/^__HASH_REF__//;
 4510:   $result=~s/__END_HASH_REF__$//;
 4511:   return $result;
 4512: }
 4513: 
 4514: sub hashref2str {
 4515:   my ($hashref)=@_;
 4516:   my $result='__HASH_REF__';
 4517:   foreach my $key (sort(keys(%$hashref))) {
 4518:     if (ref($key) eq 'ARRAY') {
 4519:       $result.=&arrayref2str($key).'=';
 4520:     } elsif (ref($key) eq 'HASH') {
 4521:       $result.=&hashref2str($key).'=';
 4522:     } elsif (ref($key)) {
 4523:       $result.='=';
 4524:       #print("Got a ref of ".(ref($key))." skipping.");
 4525:     } else {
 4526: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4527:     }
 4528: 
 4529:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4530:       $result.=&arrayref2str($hashref->{$key}).'&';
 4531:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4532:       $result.=&hashref2str($hashref->{$key}).'&';
 4533:     } elsif(ref($hashref->{$key})) {
 4534:        $result.='&';
 4535:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4536:     } else {
 4537:       $result.=&escape($hashref->{$key}).'&';
 4538:     }
 4539:   }
 4540:   $result=~s/\&$//;
 4541:   $result .= '__END_HASH_REF__';
 4542:   return $result;
 4543: }
 4544: 
 4545: sub str2hash {
 4546:     my ($string)=@_;
 4547:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4548:     return %$hash;
 4549: }
 4550: 
 4551: sub str2hashref {
 4552:   my ($string) = @_;
 4553: 
 4554:   my %hash;
 4555: 
 4556:   if($string !~ /^__HASH_REF__/) {
 4557:       if (! ($string eq '' || !defined($string))) {
 4558: 	  $hash{'error'}='Not hash reference';
 4559:       }
 4560:       return (\%hash, $string);
 4561:   }
 4562: 
 4563:   $string =~ s/^__HASH_REF__//;
 4564: 
 4565:   while($string !~ /^__END_HASH_REF__/) {
 4566:       #key
 4567:       my $key='';
 4568:       if($string =~ /^__HASH_REF__/) {
 4569:           ($key, $string)=&str2hashref($string);
 4570:           if(defined($key->{'error'})) {
 4571:               $hash{'error'}='Bad data';
 4572:               return (\%hash, $string);
 4573:           }
 4574:       } elsif($string =~ /^__ARRAY_REF__/) {
 4575:           ($key, $string)=&str2arrayref($string);
 4576:           if($key->[0] eq 'Array reference error') {
 4577:               $hash{'error'}='Bad data';
 4578:               return (\%hash, $string);
 4579:           }
 4580:       } else {
 4581:           $string =~ s/^(.*?)=//;
 4582: 	  $key=&unescape($1);
 4583:       }
 4584:       $string =~ s/^=//;
 4585: 
 4586:       #value
 4587:       my $value='';
 4588:       if($string =~ /^__HASH_REF__/) {
 4589:           ($value, $string)=&str2hashref($string);
 4590:           if(defined($value->{'error'})) {
 4591:               $hash{'error'}='Bad data';
 4592:               return (\%hash, $string);
 4593:           }
 4594:       } elsif($string =~ /^__ARRAY_REF__/) {
 4595:           ($value, $string)=&str2arrayref($string);
 4596:           if($value->[0] eq 'Array reference error') {
 4597:               $hash{'error'}='Bad data';
 4598:               return (\%hash, $string);
 4599:           }
 4600:       } else {
 4601: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4602:       }
 4603:       $string =~ s/^&//;
 4604: 
 4605:       $hash{$key}=$value;
 4606:   }
 4607: 
 4608:   $string =~ s/^__END_HASH_REF__//;
 4609: 
 4610:   return (\%hash, $string);
 4611: }
 4612: 
 4613: sub str2array {
 4614:     my ($string)=@_;
 4615:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4616:     return @$array;
 4617: }
 4618: 
 4619: sub str2arrayref {
 4620:   my ($string) = @_;
 4621:   my @array;
 4622: 
 4623:   if($string !~ /^__ARRAY_REF__/) {
 4624:       if (! ($string eq '' || !defined($string))) {
 4625: 	  $array[0]='Array reference error';
 4626:       }
 4627:       return (\@array, $string);
 4628:   }
 4629: 
 4630:   $string =~ s/^__ARRAY_REF__//;
 4631: 
 4632:   while($string !~ /^__END_ARRAY_REF__/) {
 4633:       my $value='';
 4634:       if($string =~ /^__HASH_REF__/) {
 4635:           ($value, $string)=&str2hashref($string);
 4636:           if(defined($value->{'error'})) {
 4637:               $array[0] ='Array reference error';
 4638:               return (\@array, $string);
 4639:           }
 4640:       } elsif($string =~ /^__ARRAY_REF__/) {
 4641:           ($value, $string)=&str2arrayref($string);
 4642:           if($value->[0] eq 'Array reference error') {
 4643:               $array[0] ='Array reference error';
 4644:               return (\@array, $string);
 4645:           }
 4646:       } else {
 4647: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4648:       }
 4649:       $string =~ s/^&//;
 4650: 
 4651:       push(@array, $value);
 4652:   }
 4653: 
 4654:   $string =~ s/^__END_ARRAY_REF__//;
 4655: 
 4656:   return (\@array, $string);
 4657: }
 4658: 
 4659: # -------------------------------------------------------------------Temp Store
 4660: 
 4661: sub tmpreset {
 4662:   my ($symb,$namespace,$domain,$stuname) = @_;
 4663:   if (!$symb) {
 4664:     $symb=&symbread();
 4665:     if (!$symb) { $symb= $env{'request.url'}; }
 4666:   }
 4667:   $symb=escape($symb);
 4668: 
 4669:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4670:   $namespace=~s/\//\_/g;
 4671:   $namespace=~s/\W//g;
 4672: 
 4673:   if (!$domain) { $domain=$env{'user.domain'}; }
 4674:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4675:   if ($domain eq 'public' && $stuname eq 'public') {
 4676:       $stuname=$ENV{'REMOTE_ADDR'};
 4677:   }
 4678:   my $path=LONCAPA::tempdir();
 4679:   my %hash;
 4680:   if (tie(%hash,'GDBM_File',
 4681: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4682: 	  &GDBM_WRCREAT(),0640)) {
 4683:     foreach my $key (keys(%hash)) {
 4684:       if ($key=~ /:$symb/) {
 4685: 	delete($hash{$key});
 4686:       }
 4687:     }
 4688:   }
 4689: }
 4690: 
 4691: sub tmpstore {
 4692:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4693: 
 4694:   if (!$symb) {
 4695:     $symb=&symbread();
 4696:     if (!$symb) { $symb= $env{'request.url'}; }
 4697:   }
 4698:   $symb=escape($symb);
 4699: 
 4700:   if (!$namespace) {
 4701:     # I don't think we would ever want to store this for a course.
 4702:     # it seems this will only be used if we don't have a course.
 4703:     #$namespace=$env{'request.course.id'};
 4704:     #if (!$namespace) {
 4705:       $namespace=$env{'request.state'};
 4706:     #}
 4707:   }
 4708:   $namespace=~s/\//\_/g;
 4709:   $namespace=~s/\W//g;
 4710:   if (!$domain) { $domain=$env{'user.domain'}; }
 4711:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4712:   if ($domain eq 'public' && $stuname eq 'public') {
 4713:       $stuname=$ENV{'REMOTE_ADDR'};
 4714:   }
 4715:   my $now=time;
 4716:   my %hash;
 4717:   my $path=LONCAPA::tempdir();
 4718:   if (tie(%hash,'GDBM_File',
 4719: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4720: 	  &GDBM_WRCREAT(),0640)) {
 4721:     $hash{"version:$symb"}++;
 4722:     my $version=$hash{"version:$symb"};
 4723:     my $allkeys=''; 
 4724:     foreach my $key (keys(%$storehash)) {
 4725:       $allkeys.=$key.':';
 4726:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4727:     }
 4728:     $hash{"$version:$symb:timestamp"}=$now;
 4729:     $allkeys.='timestamp';
 4730:     $hash{"$version:keys:$symb"}=$allkeys;
 4731:     if (untie(%hash)) {
 4732:       return 'ok';
 4733:     } else {
 4734:       return "error:$!";
 4735:     }
 4736:   } else {
 4737:     return "error:$!";
 4738:   }
 4739: }
 4740: 
 4741: # -----------------------------------------------------------------Temp Restore
 4742: 
 4743: sub tmprestore {
 4744:   my ($symb,$namespace,$domain,$stuname) = @_;
 4745: 
 4746:   if (!$symb) {
 4747:     $symb=&symbread();
 4748:     if (!$symb) { $symb= $env{'request.url'}; }
 4749:   }
 4750:   $symb=escape($symb);
 4751: 
 4752:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4753: 
 4754:   if (!$domain) { $domain=$env{'user.domain'}; }
 4755:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4756:   if ($domain eq 'public' && $stuname eq 'public') {
 4757:       $stuname=$ENV{'REMOTE_ADDR'};
 4758:   }
 4759:   my %returnhash;
 4760:   $namespace=~s/\//\_/g;
 4761:   $namespace=~s/\W//g;
 4762:   my %hash;
 4763:   my $path=LONCAPA::tempdir();
 4764:   if (tie(%hash,'GDBM_File',
 4765: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4766: 	  &GDBM_READER(),0640)) {
 4767:     my $version=$hash{"version:$symb"};
 4768:     $returnhash{'version'}=$version;
 4769:     my $scope;
 4770:     for ($scope=1;$scope<=$version;$scope++) {
 4771:       my $vkeys=$hash{"$scope:keys:$symb"};
 4772:       my @keys=split(/:/,$vkeys);
 4773:       my $key;
 4774:       $returnhash{"$scope:keys"}=$vkeys;
 4775:       foreach $key (@keys) {
 4776: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4777: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4778:       }
 4779:     }
 4780:     if (!(untie(%hash))) {
 4781:       return "error:$!";
 4782:     }
 4783:   } else {
 4784:     return "error:$!";
 4785:   }
 4786:   return %returnhash;
 4787: }
 4788: 
 4789: # ----------------------------------------------------------------------- Store
 4790: 
 4791: sub store {
 4792:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4793:     my $home='';
 4794: 
 4795:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4796: 
 4797:     $symb=&symbclean($symb);
 4798:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4799: 
 4800:     if (!$domain) { $domain=$env{'user.domain'}; }
 4801:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4802: 
 4803:     &devalidate($symb,$stuname,$domain);
 4804: 
 4805:     $symb=escape($symb);
 4806:     if (!$namespace) { 
 4807:        unless ($namespace=$env{'request.course.id'}) { 
 4808:           return ''; 
 4809:        } 
 4810:     }
 4811:     if (!$home) { $home=$env{'user.home'}; }
 4812: 
 4813:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4814:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4815: 
 4816:     my $namevalue='';
 4817:     foreach my $key (keys(%$storehash)) {
 4818:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4819:     }
 4820:     $namevalue=~s/\&$//;
 4821:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4822:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4823: }
 4824: 
 4825: # -------------------------------------------------------------- Critical Store
 4826: 
 4827: sub cstore {
 4828:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4829:     my $home='';
 4830: 
 4831:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4832: 
 4833:     $symb=&symbclean($symb);
 4834:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4835: 
 4836:     if (!$domain) { $domain=$env{'user.domain'}; }
 4837:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4838: 
 4839:     &devalidate($symb,$stuname,$domain);
 4840: 
 4841:     $symb=escape($symb);
 4842:     if (!$namespace) { 
 4843:        unless ($namespace=$env{'request.course.id'}) { 
 4844:           return ''; 
 4845:        } 
 4846:     }
 4847:     if (!$home) { $home=$env{'user.home'}; }
 4848: 
 4849:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4850:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4851: 
 4852:     my $namevalue='';
 4853:     foreach my $key (keys(%$storehash)) {
 4854:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4855:     }
 4856:     $namevalue=~s/\&$//;
 4857:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4858:     return critical
 4859:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4860: }
 4861: 
 4862: # --------------------------------------------------------------------- Restore
 4863: 
 4864: sub restore {
 4865:     my ($symb,$namespace,$domain,$stuname) = @_;
 4866:     my $home='';
 4867: 
 4868:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4869: 
 4870:     if (!$symb) {
 4871:         return if ($namespace eq 'courserequests');
 4872:         unless ($symb=escape(&symbread())) { return ''; }
 4873:     } else {
 4874:         unless ($namespace eq 'courserequests') {
 4875:             $symb=&escape(&symbclean($symb));
 4876:         }
 4877:     }
 4878:     if (!$namespace) { 
 4879:        unless ($namespace=$env{'request.course.id'}) { 
 4880:           return ''; 
 4881:        } 
 4882:     }
 4883:     if (!$domain) { $domain=$env{'user.domain'}; }
 4884:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4885:     if (!$home) { $home=$env{'user.home'}; }
 4886:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4887: 
 4888:     my %returnhash=();
 4889:     foreach my $line (split(/\&/,$answer)) {
 4890: 	my ($name,$value)=split(/\=/,$line);
 4891:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4892:     }
 4893:     my $version;
 4894:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4895:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4896:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4897:        }
 4898:     }
 4899:     return %returnhash;
 4900: }
 4901: 
 4902: # ---------------------------------------------------------- Course Description
 4903: #
 4904: #  
 4905: 
 4906: sub coursedescription {
 4907:     my ($courseid,$args)=@_;
 4908:     $courseid=~s/^\///;
 4909:     $courseid=~s/\_/\//g;
 4910:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4911:     my $chome=&homeserver($cnum,$cdomain);
 4912:     my $normalid=$cdomain.'_'.$cnum;
 4913:     # need to always cache even if we get errors otherwise we keep 
 4914:     # trying and trying and trying to get the course description.
 4915:     my %envhash=();
 4916:     my %returnhash=();
 4917:     
 4918:     my $expiretime=600;
 4919:     if ($env{'request.course.id'} eq $normalid) {
 4920: 	$expiretime=120;
 4921:     }
 4922: 
 4923:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4924:     if (!$args->{'freshen_cache'}
 4925: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4926: 	foreach my $key (keys(%env)) {
 4927: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4928: 	    my ($setting) = $1;
 4929: 	    $returnhash{$setting} = $env{$key};
 4930: 	}
 4931: 	return %returnhash;
 4932:     }
 4933: 
 4934:     # get the data again
 4935: 
 4936:     if (!$args->{'one_time'}) {
 4937: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4938:     }
 4939: 
 4940:     if ($chome ne 'no_host') {
 4941:        %returnhash=&dump('environment',$cdomain,$cnum);
 4942:        if (!exists($returnhash{'con_lost'})) {
 4943: 	   my $username = $env{'user.name'}; # Defult username
 4944: 	   if(defined $args->{'user'}) {
 4945: 	       $username = $args->{'user'};
 4946: 	   }
 4947:            $returnhash{'home'}= $chome;
 4948: 	   $returnhash{'domain'} = $cdomain;
 4949: 	   $returnhash{'num'} = $cnum;
 4950:            if (!defined($returnhash{'type'})) {
 4951:                $returnhash{'type'} = 'Course';
 4952:            }
 4953:            while (my ($name,$value) = each %returnhash) {
 4954:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4955:            }
 4956:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4957:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4958: 	       $username.'_'.$cdomain.'_'.$cnum;
 4959:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4960:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4961:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4962:        }
 4963:     }
 4964:     if (!$args->{'one_time'}) {
 4965: 	&appenv(\%envhash);
 4966:     }
 4967:     return %returnhash;
 4968: }
 4969: 
 4970: sub update_released_required {
 4971:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4972:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4973:         $cid = $env{'request.course.id'};
 4974:         $cdom = $env{'course.'.$cid.'.domain'};
 4975:         $cnum = $env{'course.'.$cid.'.num'};
 4976:         $chome = $env{'course.'.$cid.'.home'};
 4977:     }
 4978:     if ($needsrelease) {
 4979:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4980:         my $needsupdate;
 4981:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4982:             $needsupdate = 1;
 4983:         } else {
 4984:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4985:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4986:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4987:                 $needsupdate = 1;
 4988:             }
 4989:         }
 4990:         if ($needsupdate) {
 4991:             my %needshash = (
 4992:                              'internal.releaserequired' => $needsrelease,
 4993:                             );
 4994:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4995:             if ($putresult eq 'ok') {
 4996:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4997:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4998:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4999:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5000:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5001:                 }
 5002:             }
 5003:         }
 5004:     }
 5005:     return;
 5006: }
 5007: 
 5008: # -------------------------------------------------See if a user is privileged
 5009: 
 5010: sub privileged {
 5011:     my ($username,$domain,$possdomains,$possroles)=@_;
 5012:     my $now = time;
 5013:     my $roles;
 5014:     if (ref($possroles) eq 'ARRAY') {
 5015:         $roles = $possroles; 
 5016:     } else {
 5017:         $roles = ['dc','su'];
 5018:     }
 5019:     if (ref($possdomains) eq 'ARRAY') {
 5020:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5021:         foreach my $dom (@{$possdomains}) {
 5022:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5023:                 (ref($privileged{$dom}) eq 'HASH')) {
 5024:                 foreach my $role (@{$roles}) {
 5025:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5026:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5027:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5028:                             return 1 unless (($end && $end < $now) ||
 5029:                                              ($start && $start > $now));
 5030:                         }
 5031:                     }
 5032:                 }
 5033:             }
 5034:         }
 5035:     } else {
 5036:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5037:         my $now = time;
 5038: 
 5039:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5040:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5041:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5042:                 return 1 unless ($tend && $tend < $now) 
 5043:                         or ($tstart && $tstart > $now);
 5044:             }
 5045:         }
 5046:     }
 5047:     return 0;
 5048: }
 5049: 
 5050: sub privileged_by_domain {
 5051:     my ($domains,$roles) = @_;
 5052:     my %privileged = ();
 5053:     my $cachetime = 60*60*24;
 5054:     my $now = time;
 5055:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5056:         return %privileged;
 5057:     }
 5058:     foreach my $dom (@{$domains}) {
 5059:         next if (ref($privileged{$dom}) eq 'HASH');
 5060:         my $needroles;
 5061:         foreach my $role (@{$roles}) {
 5062:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5063:             if (defined($cached)) {
 5064:                 if (ref($result) eq 'HASH') {
 5065:                     $privileged{$dom}{$role} = $result;
 5066:                 }
 5067:             } else {
 5068:                 $needroles = 1;
 5069:             }
 5070:         }
 5071:         if ($needroles) {
 5072:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5073:             $privileged{$dom} = {};
 5074:             foreach my $server (keys(%dompersonnel)) {
 5075:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5076:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5077:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5078:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5079:                         next if ($end && $end < $now);
 5080:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5081:                             $dompersonnel{$server}{$item};
 5082:                     }
 5083:                 }
 5084:             }
 5085:             if (ref($privileged{$dom}) eq 'HASH') {
 5086:                 foreach my $role (@{$roles}) {
 5087:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5088:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5089:                     } else {
 5090:                         my %hash = ();
 5091:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5092:                     }
 5093:                 }
 5094:             }
 5095:         }
 5096:     }
 5097:     return %privileged;
 5098: }
 5099: 
 5100: # -------------------------------------------------------- Get user privileges
 5101: 
 5102: sub rolesinit {
 5103:     my ($domain, $username) = @_;
 5104:     my %userroles = ('user.login.time' => time);
 5105:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5106: 
 5107:     # firstaccess and timerinterval are related to timed maps/resources. 
 5108:     # also, blocking can be triggered by an activating timer
 5109:     # it's saved in the user's %env.
 5110:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5111:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5112:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5113:         %timerintchk, %timerintenv);
 5114: 
 5115:     foreach my $key (keys(%firstaccess)) {
 5116:         my ($cid, $rest) = split(/\0/, $key);
 5117:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5118:     }
 5119: 
 5120:     foreach my $key (keys(%timerinterval)) {
 5121:         my ($cid,$rest) = split(/\0/,$key);
 5122:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5123:     }
 5124: 
 5125:     my %allroles=();
 5126:     my %allgroups=();
 5127: 
 5128:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5129:         my $role = $rolesdump{$area};
 5130:         $area =~ s/\_\w\w$//;
 5131: 
 5132:         my ($trole, $tend, $tstart, $group_privs);
 5133: 
 5134:         if ($role =~ /^cr/) {
 5135:         # Custom role, defined by a user 
 5136:         # e.g., user.role.cr/msu/smith/mynewrole
 5137:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5138:                 $trole = $1;
 5139:                 ($tend, $tstart) = split('_', $2);
 5140:             } else {
 5141:                 $trole = $role;
 5142:             }
 5143:         } elsif ($role =~ m|^gr/|) {
 5144:         # Role of member in a group, defined within a course/community
 5145:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5146:             ($trole, $tend, $tstart) = split(/_/, $role);
 5147:             next if $tstart eq '-1';
 5148:             ($trole, $group_privs) = split(/\//, $trole);
 5149:             $group_privs = &unescape($group_privs);
 5150:         } else {
 5151:         # Just a normal role, defined in roles.tab
 5152:             ($trole, $tend, $tstart) = split(/_/,$role);
 5153:         }
 5154: 
 5155:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5156:                  $username);
 5157:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5158: 
 5159:         # role expired or not available yet?
 5160:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5161:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5162: 
 5163:         next if $area eq '' or $trole eq '';
 5164: 
 5165:         my $spec = "$trole.$area";
 5166:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5167: 
 5168:         if ($trole =~ /^cr\//) {
 5169:         # Custom role, defined by a user
 5170:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5171:         } elsif ($trole eq 'gr') {
 5172:         # Role of a member in a group, defined within a course/community
 5173:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5174:             next;
 5175:         } else {
 5176:         # Normal role, defined in roles.tab
 5177:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5178:         }
 5179: 
 5180:         my $cid = $tdomain.'_'.$trest;
 5181:         unless ($firstaccchk{$cid}) {
 5182:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5183:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5184:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5185:                         $coursetimerstarts{$cid}{$item}; 
 5186:                 }
 5187:             }
 5188:             $firstaccchk{$cid} = 1;
 5189:         }
 5190:         unless ($timerintchk{$cid}) {
 5191:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5192:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5193:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5194:                        $coursetimerintervals{$cid}{$item};
 5195:                 }
 5196:             }
 5197:             $timerintchk{$cid} = 1;
 5198:         }
 5199:     }
 5200: 
 5201:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5202:         \%allroles, \%allgroups);
 5203:     $env{'user.adv'} = $userroles{'user.adv'};
 5204: 
 5205:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5206: }
 5207: 
 5208: sub set_arearole {
 5209:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5210:     unless ($nolog) {
 5211: # log the associated role with the area
 5212:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5213:     }
 5214:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5215: }
 5216: 
 5217: sub custom_roleprivs {
 5218:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5219:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5220:     my $homsvr=homeserver($rauthor,$rdomain);
 5221:     if (&hostname($homsvr) ne '') {
 5222:         my ($rdummy,$roledef)=
 5223:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5224:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5225:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5226:             if (defined($syspriv)) {
 5227:                 if ($trest =~ /^$match_community$/) {
 5228:                     $syspriv =~ s/bre\&S//; 
 5229:                 }
 5230:                 $$allroles{'cm./'}.=':'.$syspriv;
 5231:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5232:             }
 5233:             if ($tdomain ne '') {
 5234:                 if (defined($dompriv)) {
 5235:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5236:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5237:                 }
 5238:                 if (($trest ne '') && (defined($coursepriv))) {
 5239:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5240:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5241:                 }
 5242:             }
 5243:         }
 5244:     }
 5245: }
 5246: 
 5247: sub group_roleprivs {
 5248:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5249:     my $access = 1;
 5250:     my $now = time;
 5251:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5252:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5253:     if ($access) {
 5254:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5255:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5256:     }
 5257: }
 5258: 
 5259: sub standard_roleprivs {
 5260:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5261:     if (defined($pr{$trole.':s'})) {
 5262:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5263:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5264:     }
 5265:     if ($tdomain ne '') {
 5266:         if (defined($pr{$trole.':d'})) {
 5267:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5268:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5269:         }
 5270:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5271:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5272:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5273:         }
 5274:     }
 5275: }
 5276: 
 5277: sub set_userprivs {
 5278:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5279:     my $author=0;
 5280:     my $adv=0;
 5281:     my %grouproles = ();
 5282:     if (keys(%{$allgroups}) > 0) {
 5283:         my @groupkeys; 
 5284:         foreach my $role (keys(%{$allroles})) {
 5285:             push(@groupkeys,$role);
 5286:         }
 5287:         if (ref($groups_roles) eq 'HASH') {
 5288:             foreach my $key (keys(%{$groups_roles})) {
 5289:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5290:                     push(@groupkeys,$key);
 5291:                 }
 5292:             }
 5293:         }
 5294:         if (@groupkeys > 0) {
 5295:             foreach my $role (@groupkeys) {
 5296:                 my ($trole,$area,$sec,$extendedarea);
 5297:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5298:                     $trole = $1;
 5299:                     $area = $2;
 5300:                     $sec = $3;
 5301:                     $extendedarea = $area.$sec;
 5302:                     if (exists($$allgroups{$area})) {
 5303:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5304:                             my $spec = $trole.'.'.$extendedarea;
 5305:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5306:                                                 $$allgroups{$area}{$group};
 5307:                         }
 5308:                     }
 5309:                 }
 5310:             }
 5311:         }
 5312:     }
 5313:     foreach my $group (keys(%grouproles)) {
 5314:         $$allroles{$group} = $grouproles{$group};
 5315:     }
 5316:     foreach my $role (keys(%{$allroles})) {
 5317:         my %thesepriv;
 5318:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5319:         foreach my $item (split(/:/,$$allroles{$role})) {
 5320:             if ($item ne '') {
 5321:                 my ($privilege,$restrictions)=split(/&/,$item);
 5322:                 if ($restrictions eq '') {
 5323:                     $thesepriv{$privilege}='F';
 5324:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5325:                     $thesepriv{$privilege}.=$restrictions;
 5326:                 }
 5327:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5328:             }
 5329:         }
 5330:         my $thesestr='';
 5331:         foreach my $priv (sort(keys(%thesepriv))) {
 5332: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5333: 	}
 5334:         $userroles->{'user.priv.'.$role} = $thesestr;
 5335:     }
 5336:     return ($author,$adv);
 5337: }
 5338: 
 5339: sub role_status {
 5340:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5341:     my @pwhere = ();
 5342:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5343:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5344:         unless (!defined($$role) || $$role eq '') {
 5345:             $$where=join('.',@pwhere);
 5346:             $$trolecode=$$role.'.'.$$where;
 5347:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5348:             $$tstatus='is';
 5349:             if ($$tstart && $$tstart>$update) {
 5350:                 $$tstatus='future';
 5351:                 if ($$tstart<$now) {
 5352:                     if ($$tstart && $$tstart>$refresh) {
 5353:                         if (($$where ne '') && ($$role ne '')) {
 5354:                             my (%allroles,%allgroups,$group_privs,
 5355:                                 %groups_roles,@rolecodes);
 5356:                             my %userroles = (
 5357:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5358:                             );
 5359:                             @rolecodes = ('cm'); 
 5360:                             my $spec=$$role.'.'.$$where;
 5361:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5362:                             if ($$role =~ /^cr\//) {
 5363:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5364:                                 push(@rolecodes,'cr');
 5365:                             } elsif ($$role eq 'gr') {
 5366:                                 push(@rolecodes,$$role);
 5367:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5368:                                                     $env{'user.name'});
 5369:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5370:                                 (undef,my $group_privs) = split(/\//,$trole);
 5371:                                 $group_privs = &unescape($group_privs);
 5372:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5373:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5374:                                 &get_groups_roles($tdomain,$trest,
 5375:                                                   \%course_roles,\@rolecodes,
 5376:                                                   \%groups_roles);
 5377:                             } else {
 5378:                                 push(@rolecodes,$$role);
 5379:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5380:                             }
 5381:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5382:                             &appenv(\%userroles,\@rolecodes);
 5383:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5384:                         }
 5385:                     }
 5386:                     $$tstatus = 'is';
 5387:                 }
 5388:             }
 5389:             if ($$tend) {
 5390:                 if ($$tend<$update) {
 5391:                     $$tstatus='expired';
 5392:                 } elsif ($$tend<$now) {
 5393:                     $$tstatus='will_not';
 5394:                 }
 5395:             }
 5396:         }
 5397:     }
 5398: }
 5399: 
 5400: sub get_groups_roles {
 5401:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5402:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5403:                   (ref($rolecodes) eq 'ARRAY') && 
 5404:                   (ref($groups_roles) eq 'HASH')); 
 5405:     if (keys(%{$cdom_courseroles}) > 0) {
 5406:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5407:         if ($cdom ne '' && $cnum ne '') {
 5408:             foreach my $key (keys(%{$cdom_courseroles})) {
 5409:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5410:                     my $crsrole = $1;
 5411:                     my $crssec = $2;
 5412:                     if ($crsrole =~ /^cr/) {
 5413:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5414:                             push(@{$rolecodes},'cr');
 5415:                         }
 5416:                     } else {
 5417:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5418:                             push(@{$rolecodes},$crsrole);
 5419:                         }
 5420:                     }
 5421:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5422:                     if ($crssec ne '') {
 5423:                         $rolekey .= "/$crssec";
 5424:                     }
 5425:                     $rolekey .= './';
 5426:                     $groups_roles->{$rolekey} = $rolecodes;
 5427:                 }
 5428:             }
 5429:         }
 5430:     }
 5431:     return;
 5432: }
 5433: 
 5434: sub delete_env_groupprivs {
 5435:     my ($where,$courseroles,$possroles) = @_;
 5436:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5437:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5438:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5439:         %{$courseroles->{$udom}} =
 5440:             &get_my_roles('','','userroles',['active'],
 5441:                           $possroles,[$udom],1);
 5442:     }
 5443:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5444:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5445:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5446:             my $area = '/'.$cdom.'/'.$cnum;
 5447:             my $privkey = "user.priv.$crsrole.$area";
 5448:             if ($crssec ne '') {
 5449:                 $privkey .= '/'.$crssec;
 5450:             }
 5451:             $privkey .= ".$area/$group";
 5452:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5453:         }
 5454:     }
 5455:     return;
 5456: }
 5457: 
 5458: sub check_adhoc_privs {
 5459:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5460:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5461:     my $setprivs;
 5462:     if ($env{$cckey}) {
 5463:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5464:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5465:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5466:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5467:             $setprivs = 1;
 5468:         }
 5469:     } else {
 5470:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5471:         $setprivs = 1;
 5472:     }
 5473:     return $setprivs;
 5474: }
 5475: 
 5476: sub set_adhoc_privileges {
 5477: # role can be cc or ca
 5478:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5479:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5480:     my $spec = $role.'.'.$area;
 5481:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5482:                                   $env{'user.name'},1);
 5483:     my %ccrole = ();
 5484:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5485:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5486:     &appenv(\%userroles,[$role,'cm']);
 5487:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5488:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5489:         &appenv( {'request.role'        => $spec,
 5490:                   'request.role.domain' => $dcdom,
 5491:                   'request.course.sec'  => ''
 5492:                  }
 5493:                );
 5494:         my $tadv=0;
 5495:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5496:         &appenv({'request.role.adv'    => $tadv});
 5497:     }
 5498: }
 5499: 
 5500: # --------------------------------------------------------------- get interface
 5501: 
 5502: sub get {
 5503:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5504:    my $items='';
 5505:    foreach my $item (@$storearr) {
 5506:        $items.=&escape($item).'&';
 5507:    }
 5508:    $items=~s/\&$//;
 5509:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5510:    if (!$uname) { $uname=$env{'user.name'}; }
 5511:    my $uhome=&homeserver($uname,$udomain);
 5512: 
 5513:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5514:    my @pairs=split(/\&/,$rep);
 5515:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5516:      return @pairs;
 5517:    }
 5518:    my %returnhash=();
 5519:    my $i=0;
 5520:    foreach my $item (@$storearr) {
 5521:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5522:       $i++;
 5523:    }
 5524:    return %returnhash;
 5525: }
 5526: 
 5527: # --------------------------------------------------------------- del interface
 5528: 
 5529: sub del {
 5530:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5531:    my $items='';
 5532:    foreach my $item (@$storearr) {
 5533:        $items.=&escape($item).'&';
 5534:    }
 5535: 
 5536:    $items=~s/\&$//;
 5537:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5538:    if (!$uname) { $uname=$env{'user.name'}; }
 5539:    my $uhome=&homeserver($uname,$udomain);
 5540:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5541: }
 5542: 
 5543: # -------------------------------------------------------------- dump interface
 5544: 
 5545: sub unserialize {
 5546:     my ($rep, $escapedkeys) = @_;
 5547: 
 5548:     return {} if $rep =~ /^error/;
 5549: 
 5550:     my %returnhash=();
 5551: 	foreach my $item (split /\&/, $rep) {
 5552: 	    my ($key, $value) = split(/=/, $item, 2);
 5553: 	    $key = unescape($key) unless $escapedkeys;
 5554: 	    next if $key =~ /^error: 2 /;
 5555: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5556: 	}
 5557:     #return %returnhash;
 5558:     return \%returnhash;
 5559: }        
 5560: 
 5561: # see Lond::dump_with_regexp
 5562: # if $escapedkeys hash keys won't get unescaped.
 5563: sub dump {
 5564:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5565:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5566:     if (!$uname) { $uname=$env{'user.name'}; }
 5567:     my $uhome=&homeserver($uname,$udomain);
 5568: 
 5569:     my $reply;
 5570:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5571:         # user is hosted on this machine
 5572:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5573:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5574:         return %{unserialize($reply, $escapedkeys)};
 5575:     }
 5576:     if ($regexp) {
 5577: 	$regexp=&escape($regexp);
 5578:     } else {
 5579: 	$regexp='.';
 5580:     }
 5581:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5582:     my @pairs=split(/\&/,$rep);
 5583:     my %returnhash=();
 5584:     if (!($rep =~ /^error/ )) {
 5585: 	foreach my $item (@pairs) {
 5586: 	    my ($key,$value)=split(/=/,$item,2);
 5587:         $key = unescape($key) unless $escapedkeys;
 5588:         #$key = &unescape($key);
 5589: 	    next if ($key =~ /^error: 2 /);
 5590: 	    $returnhash{$key}=&thaw_unescape($value);
 5591: 	}
 5592:     }
 5593:     return %returnhash;
 5594: }
 5595: 
 5596: 
 5597: # --------------------------------------------------------- dumpstore interface
 5598: 
 5599: sub dumpstore {
 5600:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5601:    # same as dump but keys must be escaped. They may contain colon separated
 5602:    # lists of values that may themself contain colons (e.g. symbs).
 5603:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5604: }
 5605: 
 5606: # -------------------------------------------------------------- keys interface
 5607: 
 5608: sub getkeys {
 5609:    my ($namespace,$udomain,$uname)=@_;
 5610:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5611:    if (!$uname) { $uname=$env{'user.name'}; }
 5612:    my $uhome=&homeserver($uname,$udomain);
 5613:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5614:    my @keyarray=();
 5615:    foreach my $key (split(/\&/,$rep)) {
 5616:       next if ($key =~ /^error: 2 /);
 5617:       push(@keyarray,&unescape($key));
 5618:    }
 5619:    return @keyarray;
 5620: }
 5621: 
 5622: # --------------------------------------------------------------- currentdump
 5623: sub currentdump {
 5624:    my ($courseid,$sdom,$sname)=@_;
 5625:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5626:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5627:    $sname    = $env{'user.name'}         if (! defined($sname));
 5628:    my $uhome = &homeserver($sname,$sdom);
 5629:    my $rep;
 5630: 
 5631:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5632:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5633:                    $courseid)));
 5634:    } else {
 5635:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5636:    }
 5637: 
 5638:    return if ($rep =~ /^(error:|no_such_host)/);
 5639:    #
 5640:    my %returnhash=();
 5641:    #
 5642:    if ($rep eq "unknown_cmd") { 
 5643:        # an old lond will not know currentdump
 5644:        # Do a dump and make it look like a currentdump
 5645:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5646:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5647:        my %hash = @tmp;
 5648:        @tmp=();
 5649:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5650:    } else {
 5651:        my @pairs=split(/\&/,$rep);
 5652:        foreach my $pair (@pairs) {
 5653:            my ($key,$value)=split(/=/,$pair,2);
 5654:            my ($symb,$param) = split(/:/,$key);
 5655:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5656:                                                         &thaw_unescape($value);
 5657:        }
 5658:    }
 5659:    return %returnhash;
 5660: }
 5661: 
 5662: sub convert_dump_to_currentdump{
 5663:     my %hash = %{shift()};
 5664:     my %returnhash;
 5665:     # Code ripped from lond, essentially.  The only difference
 5666:     # here is the unescaping done by lonnet::dump().  Conceivably
 5667:     # we might run in to problems with parameter names =~ /^v\./
 5668:     while (my ($key,$value) = each(%hash)) {
 5669:         my ($v,$symb,$param) = split(/:/,$key);
 5670: 	$symb  = &unescape($symb);
 5671: 	$param = &unescape($param);
 5672:         next if ($v eq 'version' || $symb eq 'keys');
 5673:         next if (exists($returnhash{$symb}) &&
 5674:                  exists($returnhash{$symb}->{$param}) &&
 5675:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5676:         $returnhash{$symb}->{$param}=$value;
 5677:         $returnhash{$symb}->{'v.'.$param}=$v;
 5678:     }
 5679:     #
 5680:     # Remove all of the keys in the hashes which keep track of
 5681:     # the version of the parameter.
 5682:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5683:         # use a foreach because we are going to delete from the hash.
 5684:         foreach my $key (keys(%$param_hash)) {
 5685:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5686:         }
 5687:     }
 5688:     return \%returnhash;
 5689: }
 5690: 
 5691: # ------------------------------------------------------ critical inc interface
 5692: 
 5693: sub cinc {
 5694:     return &inc(@_,'critical');
 5695: }
 5696: 
 5697: # --------------------------------------------------------------- inc interface
 5698: 
 5699: sub inc {
 5700:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5701:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5702:     if (!$uname) { $uname=$env{'user.name'}; }
 5703:     my $uhome=&homeserver($uname,$udomain);
 5704:     my $items='';
 5705:     if (! ref($store)) {
 5706:         # got a single value, so use that instead
 5707:         $items = &escape($store).'=&';
 5708:     } elsif (ref($store) eq 'SCALAR') {
 5709:         $items = &escape($$store).'=&';        
 5710:     } elsif (ref($store) eq 'ARRAY') {
 5711:         $items = join('=&',map {&escape($_);} @{$store});
 5712:     } elsif (ref($store) eq 'HASH') {
 5713:         while (my($key,$value) = each(%{$store})) {
 5714:             $items.= &escape($key).'='.&escape($value).'&';
 5715:         }
 5716:     }
 5717:     $items=~s/\&$//;
 5718:     if ($critical) {
 5719: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5720:     } else {
 5721: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5722:     }
 5723: }
 5724: 
 5725: # --------------------------------------------------------------- put interface
 5726: 
 5727: sub put {
 5728:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5729:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5730:    if (!$uname) { $uname=$env{'user.name'}; }
 5731:    my $uhome=&homeserver($uname,$udomain);
 5732:    my $items='';
 5733:    foreach my $item (keys(%$storehash)) {
 5734:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5735:    }
 5736:    $items=~s/\&$//;
 5737:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5738: }
 5739: 
 5740: # ------------------------------------------------------------ newput interface
 5741: 
 5742: sub newput {
 5743:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5744:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5745:    if (!$uname) { $uname=$env{'user.name'}; }
 5746:    my $uhome=&homeserver($uname,$udomain);
 5747:    my $items='';
 5748:    foreach my $key (keys(%$storehash)) {
 5749:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5750:    }
 5751:    $items=~s/\&$//;
 5752:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5753: }
 5754: 
 5755: # ---------------------------------------------------------  putstore interface
 5756: 
 5757: sub putstore {
 5758:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5759:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5760:    if (!$uname) { $uname=$env{'user.name'}; }
 5761:    my $uhome=&homeserver($uname,$udomain);
 5762:    my $items='';
 5763:    foreach my $key (keys(%$storehash)) {
 5764:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5765:    }
 5766:    $items=~s/\&$//;
 5767:    my $esc_symb=&escape($symb);
 5768:    my $esc_v=&escape($version);
 5769:    my $reply =
 5770:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5771: 	      $uhome);
 5772:    if ($reply eq 'unknown_cmd') {
 5773:        # gfall back to way things use to be done
 5774:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5775: 			    $uname);
 5776:    }
 5777:    return $reply;
 5778: }
 5779: 
 5780: sub old_putstore {
 5781:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5782:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5783:     if (!$uname) { $uname=$env{'user.name'}; }
 5784:     my $uhome=&homeserver($uname,$udomain);
 5785:     my %newstorehash;
 5786:     foreach my $item (keys(%$storehash)) {
 5787: 	my $key = $version.':'.&escape($symb).':'.$item;
 5788: 	$newstorehash{$key} = $storehash->{$item};
 5789:     }
 5790:     my $items='';
 5791:     my %allitems = ();
 5792:     foreach my $item (keys(%newstorehash)) {
 5793: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5794: 	    my $key = $1.':keys:'.$2;
 5795: 	    $allitems{$key} .= $3.':';
 5796: 	}
 5797: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5798:     }
 5799:     foreach my $item (keys(%allitems)) {
 5800: 	$allitems{$item} =~ s/\:$//;
 5801: 	$items.= $item.'='.$allitems{$item}.'&';
 5802:     }
 5803:     $items=~s/\&$//;
 5804:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5805: }
 5806: 
 5807: # ------------------------------------------------------ critical put interface
 5808: 
 5809: sub cput {
 5810:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5811:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5812:    if (!$uname) { $uname=$env{'user.name'}; }
 5813:    my $uhome=&homeserver($uname,$udomain);
 5814:    my $items='';
 5815:    foreach my $item (keys(%$storehash)) {
 5816:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5817:    }
 5818:    $items=~s/\&$//;
 5819:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5820: }
 5821: 
 5822: # -------------------------------------------------------------- eget interface
 5823: 
 5824: sub eget {
 5825:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5826:    my $items='';
 5827:    foreach my $item (@$storearr) {
 5828:        $items.=&escape($item).'&';
 5829:    }
 5830:    $items=~s/\&$//;
 5831:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5832:    if (!$uname) { $uname=$env{'user.name'}; }
 5833:    my $uhome=&homeserver($uname,$udomain);
 5834:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5835:    my @pairs=split(/\&/,$rep);
 5836:    my %returnhash=();
 5837:    my $i=0;
 5838:    foreach my $item (@$storearr) {
 5839:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5840:       $i++;
 5841:    }
 5842:    return %returnhash;
 5843: }
 5844: 
 5845: # ------------------------------------------------------------ tmpput interface
 5846: sub tmpput {
 5847:     my ($storehash,$server,$context)=@_;
 5848:     my $items='';
 5849:     foreach my $item (keys(%$storehash)) {
 5850: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5851:     }
 5852:     $items=~s/\&$//;
 5853:     if (defined($context)) {
 5854:         $items .= ':'.&escape($context);
 5855:     }
 5856:     return &reply("tmpput:$items",$server);
 5857: }
 5858: 
 5859: # ------------------------------------------------------------ tmpget interface
 5860: sub tmpget {
 5861:     my ($token,$server)=@_;
 5862:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5863:     my $rep=&reply("tmpget:$token",$server);
 5864:     my %returnhash;
 5865:     foreach my $item (split(/\&/,$rep)) {
 5866: 	my ($key,$value)=split(/=/,$item);
 5867:         next if ($key =~ /^error: 2 /);
 5868: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5869:     }
 5870:     return %returnhash;
 5871: }
 5872: 
 5873: # ------------------------------------------------------------ tmpdel interface
 5874: sub tmpdel {
 5875:     my ($token,$server)=@_;
 5876:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5877:     return &reply("tmpdel:$token",$server);
 5878: }
 5879: 
 5880: # ------------------------------------------------------------ get_timebased_id 
 5881: 
 5882: sub get_timebased_id {
 5883:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5884:         $maxtries) = @_;
 5885:     my ($newid,$error,$dellock);
 5886:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5887:         return ('','ok','invalid call to get suffix');
 5888:     }
 5889: 
 5890: # set defaults for any optional args for which values were not supplied
 5891:     if ($who eq '') {
 5892:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5893:     }
 5894:     if (!$locktries) {
 5895:         $locktries = 3;
 5896:     }
 5897:     if (!$maxtries) {
 5898:         $maxtries = 10;
 5899:     }
 5900:     
 5901:     if (($cdom eq '') || ($cnum eq '')) {
 5902:         if ($env{'request.course.id'}) {
 5903:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5904:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5905:         }
 5906:         if (($cdom eq '') || ($cnum eq '')) {
 5907:             return ('','ok','call to get suffix not in course context');
 5908:         }
 5909:     }
 5910: 
 5911: # construct locking item
 5912:     my $lockhash = {
 5913:                       $prefix."\0".'locked_'.$keyid => $who,
 5914:                    };
 5915:     my $tries = 0;
 5916: 
 5917: # attempt to get lock on nohist_$namespace file
 5918:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5919:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5920:         $tries ++;
 5921:         sleep 1;
 5922:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5923:     }
 5924: 
 5925: # attempt to get unique identifier, based on current timestamp
 5926:     if ($gotlock eq 'ok') {
 5927:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5928:         my $id = time;
 5929:         $newid = $id;
 5930:         my $idtries = 0;
 5931:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5932:             if ($idtype eq 'concat') {
 5933:                 $newid = $id.$idtries;
 5934:             } else {
 5935:                 $newid ++;
 5936:             }
 5937:             $idtries ++;
 5938:         }
 5939:         if (!exists($inuse{$prefix."\0".$newid})) {
 5940:             my %new_item =  (
 5941:                               $prefix."\0".$newid => $who,
 5942:                             );
 5943:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5944:                                                  $cdom,$cnum);
 5945:             if ($putresult ne 'ok') {
 5946:                 undef($newid);
 5947:                 $error = 'error saving new item: '.$putresult;
 5948:             }
 5949:         } else {
 5950:              $error = ('error: no unique suffix available for the new item ');
 5951:         }
 5952: #  remove lock
 5953:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5954:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5955:     } else {
 5956:         $error = "error: could not obtain lockfile\n";
 5957:         $dellock = 'ok';
 5958:     }
 5959:     return ($newid,$dellock,$error);
 5960: }
 5961: 
 5962: # -------------------------------------------------- portfolio access checking
 5963: 
 5964: sub portfolio_access {
 5965:     my ($requrl) = @_;
 5966:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5967:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5968:     if ($result) {
 5969:         my %setters;
 5970:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5971:             my ($startblock,$endblock) =
 5972:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5973:             if ($startblock && $endblock) {
 5974:                 return 'B';
 5975:             }
 5976:         } else {
 5977:             my ($startblock,$endblock) =
 5978:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5979:             if ($startblock && $endblock) {
 5980:                 return 'B';
 5981:             }
 5982:         }
 5983:     }
 5984:     if ($result eq 'ok') {
 5985:        return 'F';
 5986:     } elsif ($result =~ /^[^:]+:guest_/) {
 5987:        return 'A';
 5988:     }
 5989:     return '';
 5990: }
 5991: 
 5992: sub get_portfolio_access {
 5993:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5994: 
 5995:     if (!ref($access_hash)) {
 5996: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5997: 	my %access_controls = &get_access_controls($current_perms,$group,
 5998: 						   $file_name);
 5999: 	$access_hash = $access_controls{$file_name};
 6000:     }
 6001: 
 6002:     my ($public,$guest,@domains,@users,@courses,@groups);
 6003:     my $now = time;
 6004:     if (ref($access_hash) eq 'HASH') {
 6005:         foreach my $key (keys(%{$access_hash})) {
 6006:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6007:             if ($start > $now) {
 6008:                 next;
 6009:             }
 6010:             if ($end && $end<$now) {
 6011:                 next;
 6012:             }
 6013:             if ($scope eq 'public') {
 6014:                 $public = $key;
 6015:                 last;
 6016:             } elsif ($scope eq 'guest') {
 6017:                 $guest = $key;
 6018:             } elsif ($scope eq 'domains') {
 6019:                 push(@domains,$key);
 6020:             } elsif ($scope eq 'users') {
 6021:                 push(@users,$key);
 6022:             } elsif ($scope eq 'course') {
 6023:                 push(@courses,$key);
 6024:             } elsif ($scope eq 'group') {
 6025:                 push(@groups,$key);
 6026:             }
 6027:         }
 6028:         if ($public) {
 6029:             return 'ok';
 6030:         }
 6031:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6032:             if ($guest) {
 6033:                 return $guest;
 6034:             }
 6035:         } else {
 6036:             if (@domains > 0) {
 6037:                 foreach my $domkey (@domains) {
 6038:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6039:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6040:                             return 'ok';
 6041:                         }
 6042:                     }
 6043:                 }
 6044:             }
 6045:             if (@users > 0) {
 6046:                 foreach my $userkey (@users) {
 6047:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6048:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6049:                             if (ref($item) eq 'HASH') {
 6050:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6051:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6052:                                     return 'ok';
 6053:                                 }
 6054:                             }
 6055:                         }
 6056:                     } 
 6057:                 }
 6058:             }
 6059:             my %roleshash;
 6060:             my @courses_and_groups = @courses;
 6061:             push(@courses_and_groups,@groups); 
 6062:             if (@courses_and_groups > 0) {
 6063:                 my (%allgroups,%allroles); 
 6064:                 my ($start,$end,$role,$sec,$group);
 6065:                 foreach my $envkey (%env) {
 6066:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6067:                         my $cid = $2.'_'.$3; 
 6068:                         if ($1 eq 'gr') {
 6069:                             $group = $4;
 6070:                             $allgroups{$cid}{$group} = $env{$envkey};
 6071:                         } else {
 6072:                             if ($4 eq '') {
 6073:                                 $sec = 'none';
 6074:                             } else {
 6075:                                 $sec = $4;
 6076:                             }
 6077:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6078:                         }
 6079:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6080:                         my $cid = $2.'_'.$3;
 6081:                         if ($4 eq '') {
 6082:                             $sec = 'none';
 6083:                         } else {
 6084:                             $sec = $4;
 6085:                         }
 6086:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6087:                     }
 6088:                 }
 6089:                 if (keys(%allroles) == 0) {
 6090:                     return;
 6091:                 }
 6092:                 foreach my $key (@courses_and_groups) {
 6093:                     my %content = %{$$access_hash{$key}};
 6094:                     my $cnum = $content{'number'};
 6095:                     my $cdom = $content{'domain'};
 6096:                     my $cid = $cdom.'_'.$cnum;
 6097:                     if (!exists($allroles{$cid})) {
 6098:                         next;
 6099:                     }    
 6100:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6101:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6102:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6103:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6104:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6105:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6106:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6107:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6108:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6109:                                         if (grep/^all$/,@sections) {
 6110:                                             return 'ok';
 6111:                                         } else {
 6112:                                             if (grep/^$sec$/,@sections) {
 6113:                                                 return 'ok';
 6114:                                             }
 6115:                                         }
 6116:                                     }
 6117:                                 }
 6118:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6119:                                     if (grep/^none$/,@groups) {
 6120:                                         return 'ok';
 6121:                                     }
 6122:                                 } else {
 6123:                                     if (grep/^all$/,@groups) {
 6124:                                         return 'ok';
 6125:                                     } 
 6126:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6127:                                         if (grep/^$group$/,@groups) {
 6128:                                             return 'ok';
 6129:                                         }
 6130:                                     }
 6131:                                 } 
 6132:                             }
 6133:                         }
 6134:                     }
 6135:                 }
 6136:             }
 6137:             if ($guest) {
 6138:                 return $guest;
 6139:             }
 6140:         }
 6141:     }
 6142:     return;
 6143: }
 6144: 
 6145: sub course_group_datechecker {
 6146:     my ($dates,$now,$status) = @_;
 6147:     my ($start,$end) = split(/\./,$dates);
 6148:     if (!$start && !$end) {
 6149:         return 'ok';
 6150:     }
 6151:     if (grep/^active$/,@{$status}) {
 6152:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6153:             return 'ok';
 6154:         }
 6155:     }
 6156:     if (grep/^previous$/,@{$status}) {
 6157:         if ($end > $now ) {
 6158:             return 'ok';
 6159:         }
 6160:     }
 6161:     if (grep/^future$/,@{$status}) {
 6162:         if ($start > $now) {
 6163:             return 'ok';
 6164:         }
 6165:     }
 6166:     return; 
 6167: }
 6168: 
 6169: sub parse_portfolio_url {
 6170:     my ($url) = @_;
 6171: 
 6172:     my ($type,$udom,$unum,$group,$file_name);
 6173:     
 6174:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6175: 	$type = 1;
 6176:         $udom = $1;
 6177:         $unum = $2;
 6178:         $file_name = $3;
 6179:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6180: 	$type = 2;
 6181:         $udom = $1;
 6182:         $unum = $2;
 6183:         $group = $3;
 6184:         $file_name = $3.'/'.$4;
 6185:     }
 6186:     if (wantarray) {
 6187: 	return ($type,$udom,$unum,$file_name,$group);
 6188:     }
 6189:     return $type;
 6190: }
 6191: 
 6192: sub is_portfolio_url {
 6193:     my ($url) = @_;
 6194:     return scalar(&parse_portfolio_url($url));
 6195: }
 6196: 
 6197: sub is_portfolio_file {
 6198:     my ($file) = @_;
 6199:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6200:         return 1;
 6201:     }
 6202:     return;
 6203: }
 6204: 
 6205: sub usertools_access {
 6206:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6207:     my ($access,%tools);
 6208:     if ($context eq '') {
 6209:         $context = 'tools';
 6210:     }
 6211:     if ($context eq 'requestcourses') {
 6212:         %tools = (
 6213:                       official   => 1,
 6214:                       unofficial => 1,
 6215:                       community  => 1,
 6216:                  );
 6217:     } elsif ($context eq 'requestauthor') {
 6218:         %tools = (
 6219:                       requestauthor => 1,
 6220:                  );
 6221:     } else {
 6222:         %tools = (
 6223:                       aboutme   => 1,
 6224:                       blog      => 1,
 6225:                       webdav    => 1,
 6226:                       portfolio => 1,
 6227:                  );
 6228:     }
 6229:     return if (!defined($tools{$tool}));
 6230: 
 6231:     if (($udom eq '') || ($uname eq '')) {
 6232:         $udom = $env{'user.domain'};
 6233:         $uname = $env{'user.name'};
 6234:     }
 6235: 
 6236:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6237:         if ($action ne 'reload') {
 6238:             if ($context eq 'requestcourses') {
 6239:                 return $env{'environment.canrequest.'.$tool};
 6240:             } elsif ($context eq 'requestauthor') {
 6241:                 return $env{'environment.canrequest.author'};
 6242:             } else {
 6243:                 return $env{'environment.availabletools.'.$tool};
 6244:             }
 6245:         }
 6246:     }
 6247: 
 6248:     my ($toolstatus,$inststatus,$envkey);
 6249:     if ($context eq 'requestauthor') {
 6250:         $envkey = $context; 
 6251:     } else {
 6252:         $envkey = $context.'.'.$tool;
 6253:     }
 6254: 
 6255:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6256:          ($action ne 'reload')) {
 6257:         $toolstatus = $env{'environment.'.$envkey};
 6258:         $inststatus = $env{'environment.inststatus'};
 6259:     } else {
 6260:         if (ref($userenvref) eq 'HASH') {
 6261:             $toolstatus = $userenvref->{$envkey};
 6262:             $inststatus = $userenvref->{'inststatus'};
 6263:         } else {
 6264:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6265:             $toolstatus = $userenv{$envkey};
 6266:             $inststatus = $userenv{'inststatus'};
 6267:         }
 6268:     }
 6269: 
 6270:     if ($toolstatus ne '') {
 6271:         if ($toolstatus) {
 6272:             $access = 1;
 6273:         } else {
 6274:             $access = 0;
 6275:         }
 6276:         return $access;
 6277:     }
 6278: 
 6279:     my ($is_adv,%domdef);
 6280:     if (ref($is_advref) eq 'HASH') {
 6281:         $is_adv = $is_advref->{'is_adv'};
 6282:     } else {
 6283:         $is_adv = &is_advanced_user($udom,$uname);
 6284:     }
 6285:     if (ref($domdefref) eq 'HASH') {
 6286:         %domdef = %{$domdefref};
 6287:     } else {
 6288:         %domdef = &get_domain_defaults($udom);
 6289:     }
 6290:     if (ref($domdef{$tool}) eq 'HASH') {
 6291:         if ($is_adv) {
 6292:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6293:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6294:                     $access = 1;
 6295:                 } else {
 6296:                     $access = 0;
 6297:                 }
 6298:                 return $access;
 6299:             }
 6300:         }
 6301:         if ($inststatus ne '') {
 6302:             my ($hasaccess,$hasnoaccess);
 6303:             foreach my $affiliation (split(/:/,$inststatus)) {
 6304:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6305:                     if ($domdef{$tool}{$affiliation}) {
 6306:                         $hasaccess = 1;
 6307:                     } else {
 6308:                         $hasnoaccess = 1;
 6309:                     }
 6310:                 }
 6311:             }
 6312:             if ($hasaccess || $hasnoaccess) {
 6313:                 if ($hasaccess) {
 6314:                     $access = 1;
 6315:                 } elsif ($hasnoaccess) {
 6316:                     $access = 0; 
 6317:                 }
 6318:                 return $access;
 6319:             }
 6320:         } else {
 6321:             if ($domdef{$tool}{'default'} ne '') {
 6322:                 if ($domdef{$tool}{'default'}) {
 6323:                     $access = 1;
 6324:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6325:                     $access = 0;
 6326:                 }
 6327:                 return $access;
 6328:             }
 6329:         }
 6330:     } else {
 6331:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6332:             $access = 1;
 6333:         } else {
 6334:             $access = 0;
 6335:         }
 6336:         return $access;
 6337:     }
 6338: }
 6339: 
 6340: sub is_course_owner {
 6341:     my ($cdom,$cnum,$udom,$uname) = @_;
 6342:     if (($udom eq '') || ($uname eq '')) {
 6343:         $udom = $env{'user.domain'};
 6344:         $uname = $env{'user.name'};
 6345:     }
 6346:     unless (($udom eq '') || ($uname eq '')) {
 6347:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6348:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6349:                 return 1;
 6350:             } else {
 6351:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6352:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6353:                     return 1;
 6354:                 }
 6355:             }
 6356:         }
 6357:     }
 6358:     return;
 6359: }
 6360: 
 6361: sub is_advanced_user {
 6362:     my ($udom,$uname) = @_;
 6363:     if ($udom ne '' && $uname ne '') {
 6364:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6365:             if (wantarray) {
 6366:                 return ($env{'user.adv'},$env{'user.author'});
 6367:             } else {
 6368:                 return $env{'user.adv'};
 6369:             }
 6370:         }
 6371:     }
 6372:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6373:     my %allroles;
 6374:     my ($is_adv,$is_author);
 6375:     foreach my $role (keys(%roleshash)) {
 6376:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6377:         my $area = '/'.$tdomain.'/'.$trest;
 6378:         if ($sec ne '') {
 6379:             $area .= '/'.$sec;
 6380:         }
 6381:         if (($area ne '') && ($trole ne '')) {
 6382:             my $spec=$trole.'.'.$area;
 6383:             if ($trole =~ /^cr\//) {
 6384:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6385:             } elsif ($trole ne 'gr') {
 6386:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6387:             }
 6388:             if ($trole eq 'au') {
 6389:                 $is_author = 1;
 6390:             }
 6391:         }
 6392:     }
 6393:     foreach my $role (keys(%allroles)) {
 6394:         last if ($is_adv);
 6395:         foreach my $item (split(/:/,$allroles{$role})) {
 6396:             if ($item ne '') {
 6397:                 my ($privilege,$restrictions)=split(/&/,$item);
 6398:                 if ($privilege eq 'adv') {
 6399:                     $is_adv = 1;
 6400:                     last;
 6401:                 }
 6402:             }
 6403:         }
 6404:     }
 6405:     if (wantarray) {
 6406:         return ($is_adv,$is_author);
 6407:     }
 6408:     return $is_adv;
 6409: }
 6410: 
 6411: sub check_can_request {
 6412:     my ($dom,$can_request,$request_domains) = @_;
 6413:     my $canreq = 0;
 6414:     my ($types,$typename) = &Apache::loncommon::course_types();
 6415:     my @options = ('approval','validate','autolimit');
 6416:     my $optregex = join('|',@options);
 6417:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6418:         foreach my $type (@{$types}) {
 6419:             if (&usertools_access($env{'user.name'},
 6420:                                   $env{'user.domain'},
 6421:                                   $type,undef,'requestcourses')) {
 6422:                 $canreq ++;
 6423:                 if (ref($request_domains) eq 'HASH') {
 6424:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6425:                 }
 6426:                 if ($dom eq $env{'user.domain'}) {
 6427:                     $can_request->{$type} = 1;
 6428:                 }
 6429:             }
 6430:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6431:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6432:                 if (@curr > 0) {
 6433:                     foreach my $item (@curr) {
 6434:                         if (ref($request_domains) eq 'HASH') {
 6435:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6436:                             if ($otherdom ne '') {
 6437:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6438:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6439:                                         push(@{$request_domains->{$type}},$otherdom);
 6440:                                     }
 6441:                                 } else {
 6442:                                     push(@{$request_domains->{$type}},$otherdom);
 6443:                                 }
 6444:                             }
 6445:                         }
 6446:                     }
 6447:                     unless($dom eq $env{'user.domain'}) {
 6448:                         $canreq ++;
 6449:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6450:                             $can_request->{$type} = 1;
 6451:                         }
 6452:                     }
 6453:                 }
 6454:             }
 6455:         }
 6456:     }
 6457:     return $canreq;
 6458: }
 6459: 
 6460: # ---------------------------------------------- Custom access rule evaluation
 6461: 
 6462: sub customaccess {
 6463:     my ($priv,$uri)=@_;
 6464:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6465:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6466:     $udom = &LONCAPA::clean_domain($udom);
 6467:     $ucrs = &LONCAPA::clean_username($ucrs);
 6468:     my $access=0;
 6469:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6470: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6471: 	if ($type eq 'user') {
 6472: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6473: 		my ($tdom,$tuname)=split(m{/},$scope);
 6474: 		if ($tdom) {
 6475: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6476: 		}
 6477: 		if ($tuname) {
 6478: 		    if ($tuname ne $env{'user.name'}) { next; }
 6479: 		}
 6480: 		$access=($effect eq 'allow');
 6481: 		last;
 6482: 	    }
 6483: 	} else {
 6484: 	    if ($role) {
 6485: 		if ($role ne $urole) { next; }
 6486: 	    }
 6487: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6488: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6489: 		if ($tdom) {
 6490: 		    if ($tdom ne $udom) { next; }
 6491: 		}
 6492: 		if ($tcrs) {
 6493: 		    if ($tcrs ne $ucrs) { next; }
 6494: 		}
 6495: 		if ($tsec) {
 6496: 		    if ($tsec ne $usec) { next; }
 6497: 		}
 6498: 		$access=($effect eq 'allow');
 6499: 		last;
 6500: 	    }
 6501: 	    if ($realm eq '' && $role eq '') {
 6502: 		$access=($effect eq 'allow');
 6503: 	    }
 6504: 	}
 6505:     }
 6506:     return $access;
 6507: }
 6508: 
 6509: # ------------------------------------------------- Check for a user privilege
 6510: 
 6511: sub allowed {
 6512:     my ($priv,$uri,$symb,$role)=@_;
 6513:     my $ver_orguri=$uri;
 6514:     $uri=&deversion($uri);
 6515:     my $orguri=$uri;
 6516:     $uri=&declutter($uri);
 6517: 
 6518:     if ($priv eq 'evb') {
 6519: # Evade communication block restrictions for specified role in a course
 6520:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6521:             return $1;
 6522:         } else {
 6523:             return;
 6524:         }
 6525:     }
 6526: 
 6527:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6528: # Free bre access to adm and meta resources
 6529:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6530: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6531: 	&& ($priv eq 'bre')) {
 6532: 	return 'F';
 6533:     }
 6534: 
 6535: # Free bre access to user's own portfolio contents
 6536:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6537:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6538: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6539:         my %setters;
 6540:         my ($startblock,$endblock) = 
 6541:             &Apache::loncommon::blockcheck(\%setters,'port');
 6542:         if ($startblock && $endblock) {
 6543:             return 'B';
 6544:         } else {
 6545:             return 'F';
 6546:         }
 6547:     }
 6548: 
 6549: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6550:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6551:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6552:         if (exists($env{'request.course.id'})) {
 6553:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6554:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6555:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6556:                 my $courseprivid=$env{'request.course.id'};
 6557:                 $courseprivid=~s/\_/\//;
 6558:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6559:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6560:                     return $1; 
 6561:                 } else {
 6562:                     if ($env{'request.course.sec'}) {
 6563:                         $courseprivid.='/'.$env{'request.course.sec'};
 6564:                     }
 6565:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6566:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6567:                         return $2;
 6568:                     }
 6569:                 }
 6570:             }
 6571:         }
 6572:     }
 6573: 
 6574: # Free bre to public access
 6575: 
 6576:     if ($priv eq 'bre') {
 6577:         my $copyright=&metadata($uri,'copyright');
 6578: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6579:            return 'F'; 
 6580:         }
 6581:         if ($copyright eq 'priv') {
 6582:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6583: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6584: 		return '';
 6585:             }
 6586:         }
 6587:         if ($copyright eq 'domain') {
 6588:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6589: 	    unless (($env{'user.domain'} eq $1) ||
 6590:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6591: 		return '';
 6592:             }
 6593:         }
 6594:         if ($env{'request.role'}=~ /li\.\//) {
 6595:             # Library role, so allow browsing of resources in this domain.
 6596:             return 'F';
 6597:         }
 6598:         if ($copyright eq 'custom') {
 6599: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6600:         }
 6601:     }
 6602:     # Domain coordinator is trying to create a course
 6603:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6604:         # uri is the requested domain in this case.
 6605:         # comparison to 'request.role.domain' shows if the user has selected
 6606:         # a role of dc for the domain in question.
 6607:         return 'F' if ($uri eq $env{'request.role.domain'});
 6608:     }
 6609: 
 6610:     my $thisallowed='';
 6611:     my $statecond=0;
 6612:     my $courseprivid='';
 6613: 
 6614:     my $ownaccess;
 6615:     # Community Coordinator or Assistant Co-author browsing resource space.
 6616:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6617:         if ($uri eq '') {
 6618:             $ownaccess = 1;
 6619:         } else {
 6620:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6621:                 my $udom = $env{'user.domain'};
 6622:                 my $uname = $env{'user.name'};
 6623:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6624:                     $ownaccess = 1;
 6625:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6626:                     unless ($uri =~ m{\.\./}) {
 6627:                         $ownaccess = 1;
 6628:                     }
 6629:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6630:                     my $now = time;
 6631:                     if ($uri =~ m{^([^/]+)/?$}) {
 6632:                         my $adom = $1;
 6633:                         foreach my $key (keys(%env)) {
 6634:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6635:                                 my ($start,$end) = split('.',$env{$key});
 6636:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6637:                                     $ownaccess = 1;
 6638:                                     last;
 6639:                                 }
 6640:                             }
 6641:                         }
 6642:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6643:                         my $adom = $1;
 6644:                         my $aname = $2;
 6645:                         foreach my $role ('ca','aa') { 
 6646:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6647:                                 my ($start,$end) =
 6648:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6649:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6650:                                     $ownaccess = 1;
 6651:                                     last;
 6652:                                 }
 6653:                             }
 6654:                         }
 6655:                     }
 6656:                 }
 6657:             }
 6658:         }
 6659:     }
 6660: 
 6661: # Course
 6662: 
 6663:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6664:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6665:             $thisallowed.=$1;
 6666:         }
 6667:     }
 6668: 
 6669: # Domain
 6670: 
 6671:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6672:        =~/\Q$priv\E\&([^\:]*)/) {
 6673:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6674:             $thisallowed.=$1;
 6675:         }
 6676:     }
 6677: 
 6678: # User who is not author or co-author might still be able to edit
 6679: # resource of an author in the domain (e.g., if Domain Coordinator).
 6680:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6681:         (&allowed('mdc',$env{'request.course.id'}))) {
 6682:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6683:             $thisallowed.=$1;
 6684:         }
 6685:     }
 6686: 
 6687: # Course: uri itself is a course
 6688:     my $courseuri=$uri;
 6689:     $courseuri=~s/\_(\d)/\/$1/;
 6690:     $courseuri=~s/^([^\/])/\/$1/;
 6691: 
 6692:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6693:        =~/\Q$priv\E\&([^\:]*)/) {
 6694:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6695:             $thisallowed.=$1;
 6696:         }
 6697:     }
 6698: 
 6699: # URI is an uploaded document for this course, default permissions don't matter
 6700: # not allowing 'edit' access (editupload) to uploaded course docs
 6701:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6702: 	$thisallowed='';
 6703:         my ($match)=&is_on_map($uri);
 6704:         if ($match) {
 6705:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6706:                   =~/\Q$priv\E\&([^\:]*)/) {
 6707:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6708:                 if (@blockers > 0) {
 6709:                     $thisallowed = 'B';
 6710:                 } else {
 6711:                     $thisallowed.=$1;
 6712:                 }
 6713:             }
 6714:         } else {
 6715:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6716:             if ($refuri) {
 6717:                 if ($refuri =~ m|^/adm/|) {
 6718:                     $thisallowed='F';
 6719:                 } else {
 6720:                     $refuri=&declutter($refuri);
 6721:                     my ($match) = &is_on_map($refuri);
 6722:                     if ($match) {
 6723:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6724:                         if (@blockers > 0) {
 6725:                             $thisallowed = 'B';
 6726:                         } else {
 6727:                             $thisallowed='F';
 6728:                         }
 6729:                     }
 6730:                 }
 6731:             }
 6732:         }
 6733:     }
 6734: 
 6735:     if ($priv eq 'bre'
 6736: 	&& $thisallowed ne 'F' 
 6737: 	&& $thisallowed ne '2'
 6738: 	&& &is_portfolio_url($uri)) {
 6739: 	$thisallowed = &portfolio_access($uri);
 6740:     }
 6741:     
 6742: # Full access at system, domain or course-wide level? Exit.
 6743:     if ($thisallowed=~/F/) {
 6744: 	return 'F';
 6745:     }
 6746: 
 6747: # If this is generating or modifying users, exit with special codes
 6748: 
 6749:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6750: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6751: 	    my ($audom,$auname)=split('/',$uri);
 6752: # no author name given, so this just checks on the general right to make a co-author in this domain
 6753: 	    unless ($auname) { return $thisallowed; }
 6754: # an author name is given, so we are about to actually make a co-author for a certain account
 6755: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6756: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6757: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6758: 	}
 6759: 	return $thisallowed;
 6760:     }
 6761: #
 6762: # Gathered so far: system, domain and course wide privileges
 6763: #
 6764: # Course: See if uri or referer is an individual resource that is part of 
 6765: # the course
 6766: 
 6767:     if ($env{'request.course.id'}) {
 6768: 
 6769:        $courseprivid=$env{'request.course.id'};
 6770:        if ($env{'request.course.sec'}) {
 6771:           $courseprivid.='/'.$env{'request.course.sec'};
 6772:        }
 6773:        $courseprivid=~s/\_/\//;
 6774:        my $checkreferer=1;
 6775:        my ($match,$cond)=&is_on_map($uri);
 6776:        if ($match) {
 6777:            $statecond=$cond;
 6778:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6779:                =~/\Q$priv\E\&([^\:]*)/) {
 6780:                my $value = $1;
 6781:                if ($priv eq 'bre') {
 6782:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6783:                    if (@blockers > 0) {
 6784:                        $thisallowed = 'B';
 6785:                    } else {
 6786:                        $thisallowed.=$value;
 6787:                    }
 6788:                } else {
 6789:                    $thisallowed.=$value;
 6790:                }
 6791:                $checkreferer=0;
 6792:            }
 6793:        }
 6794:        
 6795:        if ($checkreferer) {
 6796: 	  my $refuri=$env{'httpref.'.$orguri};
 6797:             unless ($refuri) {
 6798:                 foreach my $key (keys(%env)) {
 6799: 		    if ($key=~/^httpref\..*\*/) {
 6800: 			my $pattern=$key;
 6801:                         $pattern=~s/^httpref\.\/res\///;
 6802:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6803:                         $pattern=~s/\//\\\//g;
 6804:                         if ($orguri=~/$pattern/) {
 6805: 			    $refuri=$env{$key};
 6806:                         }
 6807:                     }
 6808:                 }
 6809:             }
 6810: 
 6811:          if ($refuri) { 
 6812: 	  $refuri=&declutter($refuri);
 6813:           my ($match,$cond)=&is_on_map($refuri);
 6814:             if ($match) {
 6815:               my $refstatecond=$cond;
 6816:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6817:                   =~/\Q$priv\E\&([^\:]*)/) {
 6818:                   my $value = $1;
 6819:                   if ($priv eq 'bre') {
 6820:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6821:                       if (@blockers > 0) {
 6822:                           $thisallowed = 'B';
 6823:                       } else {
 6824:                           $thisallowed.=$value;
 6825:                       }
 6826:                   } else {
 6827:                       $thisallowed.=$value;
 6828:                   }
 6829:                   $uri=$refuri;
 6830:                   $statecond=$refstatecond;
 6831:               }
 6832:           }
 6833:         }
 6834:        }
 6835:    }
 6836: 
 6837: #
 6838: # Gathered now: all privileges that could apply, and condition number
 6839: # 
 6840: #
 6841: # Full or no access?
 6842: #
 6843: 
 6844:     if ($thisallowed=~/F/) {
 6845: 	return 'F';
 6846:     }
 6847: 
 6848:     unless ($thisallowed) {
 6849:         return '';
 6850:     }
 6851: 
 6852: # Restrictions exist, deal with them
 6853: #
 6854: #   C:according to course preferences
 6855: #   R:according to resource settings
 6856: #   L:unless locked
 6857: #   X:according to user session state
 6858: #
 6859: 
 6860: # Possibly locked functionality, check all courses
 6861: # Locks might take effect only after 10 minutes cache expiration for other
 6862: # courses, and 2 minutes for current course
 6863: 
 6864:     my $envkey;
 6865:     if ($thisallowed=~/L/) {
 6866:         foreach $envkey (keys(%env)) {
 6867:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6868:                my $courseid=$2;
 6869:                my $roleid=$1.'.'.$2;
 6870:                $courseid=~s/^\///;
 6871:                my $expiretime=600;
 6872:                if ($env{'request.role'} eq $roleid) {
 6873: 		  $expiretime=120;
 6874:                }
 6875: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6876:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6877:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6878: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6879:                }
 6880:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6881:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6882: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6883:                        &log($env{'user.domain'},$env{'user.name'},
 6884:                             $env{'user.home'},
 6885:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6886:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6887:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6888: 		       return '';
 6889:                    }
 6890:                }
 6891:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6892:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6893: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6894:                        &log($env{'user.domain'},$env{'user.name'},
 6895:                             $env{'user.home'},
 6896:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6897:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6898:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6899: 		       return '';
 6900:                    }
 6901:                }
 6902: 	   }
 6903:        }
 6904:     }
 6905:    
 6906: #
 6907: # Rest of the restrictions depend on selected course
 6908: #
 6909: 
 6910:     unless ($env{'request.course.id'}) {
 6911: 	if ($thisallowed eq 'A') {
 6912: 	    return 'A';
 6913:         } elsif ($thisallowed eq 'B') {
 6914:             return 'B';
 6915: 	} else {
 6916: 	    return '1';
 6917: 	}
 6918:     }
 6919: 
 6920: #
 6921: # Now user is definitely in a course
 6922: #
 6923: 
 6924: 
 6925: # Course preferences
 6926: 
 6927:    if ($thisallowed=~/C/) {
 6928:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6929:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6930:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6931: 	   =~/\Q$rolecode\E/) {
 6932: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6933: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6934: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6935: 			$env{'request.course.id'});
 6936: 	   }
 6937:            return '';
 6938:        }
 6939: 
 6940:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6941: 	   =~/\Q$unamedom\E/) {
 6942: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6943: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6944: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6945: 			$env{'request.course.id'});
 6946: 	   }
 6947:            return '';
 6948:        }
 6949:    }
 6950: 
 6951: # Resource preferences
 6952: 
 6953:    if ($thisallowed=~/R/) {
 6954:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6955:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6956: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6957: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6958: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6959: 	   }
 6960: 	   return '';
 6961:        }
 6962:    }
 6963: 
 6964: # Restricted by state or randomout?
 6965: 
 6966:    if ($thisallowed=~/X/) {
 6967:       if ($env{'acc.randomout'}) {
 6968: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6969:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6970:             return ''; 
 6971:          }
 6972:       }
 6973:       if (&condval($statecond)) {
 6974: 	 return '2';
 6975:       } else {
 6976:          return '';
 6977:       }
 6978:    }
 6979: 
 6980:     if ($thisallowed eq 'A') {
 6981: 	return 'A';
 6982:     } elsif ($thisallowed eq 'B') {
 6983:         return 'B';
 6984:     }
 6985:    return 'F';
 6986: }
 6987: 
 6988: # ------------------------------------------- Check construction space access
 6989: 
 6990: sub constructaccess {
 6991:     my ($url,$setpriv)=@_;
 6992: 
 6993: # We do not allow editing of previous versions of files
 6994:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6995: 
 6996: # Get username and domain from URL
 6997:     my ($ownername,$ownerdomain,$ownerhome);
 6998: 
 6999:     ($ownerdomain,$ownername) =
 7000:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7001: 
 7002: # The URL does not really point to any authorspace, forget it
 7003:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7004: 
 7005: # Now we need to see if the user has access to the authorspace of
 7006: # $ownername at $ownerdomain
 7007: 
 7008:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7009: # Real author for this?
 7010:        $ownerhome = $env{'user.home'};
 7011:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7012:           return ($ownername,$ownerdomain,$ownerhome);
 7013:        }
 7014:     } else {
 7015: # Co-author for this?
 7016:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7017:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7018:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7019:             return ($ownername,$ownerdomain,$ownerhome);
 7020:         }
 7021:     }
 7022: 
 7023: # We don't have any access right now. If we are not possibly going to do anything about this,
 7024: # we might as well leave
 7025:    unless ($setpriv) { return ''; }
 7026: 
 7027: # Backdoor access?
 7028:     my $allowed=&allowed('eco',$ownerdomain);
 7029: # Nope
 7030:     unless ($allowed) { return ''; }
 7031: # Looks like we may have access, but could be locked by the owner of the construction space
 7032:     if ($allowed eq 'U') {
 7033:         my %blocked=&get('environment',['domcoord.author'],
 7034:                          $ownerdomain,$ownername);
 7035: # Is blocked by owner
 7036:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7037:     }
 7038:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7039: # Grant temporary access
 7040:         my $then=$env{'user.login.time'};
 7041:         my $update=$env{'user.update.time'};
 7042:         if (!$update) { $update = $then; }
 7043:         my $refresh=$env{'user.refresh.time'};
 7044:         if (!$refresh) { $refresh = $update; }
 7045:         my $now = time;
 7046:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7047:                            $now,'ca','constructaccess');
 7048:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7049:         return($ownername,$ownerdomain,$ownerhome);
 7050:     }
 7051: # No business here
 7052:     return '';
 7053: }
 7054: 
 7055: sub get_comm_blocks {
 7056:     my ($cdom,$cnum) = @_;
 7057:     if ($cdom eq '' || $cnum eq '') {
 7058:         return unless ($env{'request.course.id'});
 7059:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7060:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7061:     }
 7062:     my %commblocks;
 7063:     my $hashid=$cdom.'_'.$cnum;
 7064:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7065:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7066:         %commblocks = %{$blocksref};
 7067:     } else {
 7068:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7069:         my $cachetime = 600;
 7070:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7071:     }
 7072:     return %commblocks;
 7073: }
 7074: 
 7075: sub has_comm_blocking {
 7076:     my ($priv,$symb,$uri,$blocks) = @_;
 7077:     return unless ($env{'request.course.id'});
 7078:     return unless ($priv eq 'bre');
 7079:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7080:     my %commblocks;
 7081:     if (ref($blocks) eq 'HASH') {
 7082:         %commblocks = %{$blocks};
 7083:     } else {
 7084:         %commblocks = &get_comm_blocks();
 7085:     }
 7086:     return unless (keys(%commblocks) > 0);
 7087:     if (!$symb) { $symb=&symbread($uri,1); }
 7088:     my ($map,$resid,undef)=&decode_symb($symb);
 7089:     my %tocheck = (
 7090:                     maps      => $map,
 7091:                     resources => $symb,
 7092:                   );
 7093:     my @blockers;
 7094:     my $now = time;
 7095:     my $navmap = Apache::lonnavmaps::navmap->new();
 7096:     foreach my $block (keys(%commblocks)) {
 7097:         if ($block =~ /^(\d+)____(\d+)$/) {
 7098:             my ($start,$end) = ($1,$2);
 7099:             if ($start <= $now && $end >= $now) {
 7100:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7101:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7102:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7103:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7104:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7105:                                     push(@blockers,$block);
 7106:                                 }
 7107:                             }
 7108:                         }
 7109:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7110:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7111:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7112:                                     push(@blockers,$block);
 7113:                                 }
 7114:                             }
 7115:                         }
 7116:                     }
 7117:                 }
 7118:             }
 7119:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7120:             my $item = $1;
 7121:             my @to_test;
 7122:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7123:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7124:                     my $check_interval;
 7125:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7126:                         my @interval;
 7127:                         my $type = 'map';
 7128:                         if ($item eq 'course') {
 7129:                             $type = 'course';
 7130:                             @interval=&EXT("resource.0.interval");
 7131:                         } else {
 7132:                             if ($item =~ /___\d+___/) {
 7133:                                 $type = 'resource';
 7134:                                 @interval=&EXT("resource.0.interval",$item);
 7135:                                 if (ref($navmap)) {                        
 7136:                                     my $res = $navmap->getBySymb($item); 
 7137:                                     push(@to_test,$res);
 7138:                                 }
 7139:                             } else {
 7140:                                 my $mapsymb = &symbread($item,1);
 7141:                                 if ($mapsymb) {
 7142:                                     if (ref($navmap)) {
 7143:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7144:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7145:                                         foreach my $res (@to_test) {
 7146:                                             my $symb = $res->symb();
 7147:                                             next if ($symb eq $mapsymb);
 7148:                                             if ($symb ne '') {
 7149:                                                 @interval=&EXT("resource.0.interval",$symb);
 7150:                                                 last;
 7151:                                             }
 7152:                                         }
 7153:                                     }
 7154:                                 }
 7155:                             }
 7156:                         }
 7157:                         if ($interval[0] =~ /\d+/) {
 7158:                             my $first_access;
 7159:                             if ($type eq 'resource') {
 7160:                                 $first_access=&get_first_access($interval[1],$item);
 7161:                             } elsif ($type eq 'map') {
 7162:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7163:                             } else {
 7164:                                 $first_access=&get_first_access($interval[1]);
 7165:                             }
 7166:                             if ($first_access) {
 7167:                                 my $timesup = $first_access+$interval[0];
 7168:                                 if ($timesup > $now) {
 7169:                                     foreach my $res (@to_test) {
 7170:                                         if ($res->is_problem()) {
 7171:                                             if ($res->completable()) {
 7172:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7173:                                                     push(@blockers,$block);
 7174:                                                 }
 7175:                                                 last;
 7176:                                             }
 7177:                                         }
 7178:                                     }
 7179:                                 }
 7180:                             }
 7181:                         }
 7182:                     }
 7183:                 }
 7184:             }
 7185:         }
 7186:     }
 7187:     return @blockers;
 7188: }
 7189: 
 7190: sub check_docs_block {
 7191:     my ($docsblock,$tocheck) =@_;
 7192:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7193:         return;
 7194:     }
 7195:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7196:         if ($tocheck->{'maps'}) {
 7197:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7198:                 return 1;
 7199:             }
 7200:         }
 7201:     }
 7202:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7203:         if ($tocheck->{'resources'}) {
 7204:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7205:                 return 1;
 7206:             }
 7207:         }
 7208:     }
 7209:     return;
 7210: }
 7211: 
 7212: #
 7213: #   Removes the versino from a URI and
 7214: #   splits it in to its filename and path to the filename.
 7215: #   Seems like File::Basename could have done this more clearly.
 7216: #   Parameters:
 7217: #      $uri   - input URI
 7218: #   Returns:
 7219: #     Two element list consisting of 
 7220: #     $pathname  - the URI up to and excluding the trailing /
 7221: #     $filename  - The part of the URI following the last /
 7222: #  NOTE:
 7223: #    Another realization of this is simply:
 7224: #    use File::Basename;
 7225: #    ...
 7226: #    $uri = shift;
 7227: #    $filename = basename($uri);
 7228: #    $path     = dirname($uri);
 7229: #    return ($filename, $path);
 7230: #
 7231: #     The implementation below is probably faster however.
 7232: #
 7233: sub split_uri_for_cond {
 7234:     my $uri=&deversion(&declutter(shift));
 7235:     my @uriparts=split(/\//,$uri);
 7236:     my $filename=pop(@uriparts);
 7237:     my $pathname=join('/',@uriparts);
 7238:     return ($pathname,$filename);
 7239: }
 7240: # --------------------------------------------------- Is a resource on the map?
 7241: 
 7242: sub is_on_map {
 7243:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7244:     #Trying to find the conditional for the file
 7245:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7246: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7247:     if ($match) {
 7248: 	return (1,$1);
 7249:     } else {
 7250: 	return (0,0);
 7251:     }
 7252: }
 7253: 
 7254: # --------------------------------------------------------- Get symb from alias
 7255: 
 7256: sub get_symb_from_alias {
 7257:     my $symb=shift;
 7258:     my ($map,$resid,$url)=&decode_symb($symb);
 7259: # Already is a symb
 7260:     if ($url) { return $symb; }
 7261: # Must be an alias
 7262:     my $aliassymb='';
 7263:     my %bighash;
 7264:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7265:                             &GDBM_READER(),0640)) {
 7266:         my $rid=$bighash{'mapalias_'.$symb};
 7267: 	if ($rid) {
 7268: 	    my ($mapid,$resid)=split(/\./,$rid);
 7269: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7270: 				    $resid,$bighash{'src_'.$rid});
 7271: 	}
 7272:         untie %bighash;
 7273:     }
 7274:     return $aliassymb;
 7275: }
 7276: 
 7277: # ----------------------------------------------------------------- Define Role
 7278: 
 7279: sub definerole {
 7280:   if (allowed('mcr','/')) {
 7281:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7282:     foreach my $role (split(':',$sysrole)) {
 7283: 	my ($crole,$cqual)=split(/\&/,$role);
 7284:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7285:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7286: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7287:                return "refused:s:$crole&$cqual"; 
 7288:             }
 7289:         }
 7290:     }
 7291:     foreach my $role (split(':',$domrole)) {
 7292: 	my ($crole,$cqual)=split(/\&/,$role);
 7293:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7294:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7295: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7296:                return "refused:d:$crole&$cqual"; 
 7297:             }
 7298:         }
 7299:     }
 7300:     foreach my $role (split(':',$courole)) {
 7301: 	my ($crole,$cqual)=split(/\&/,$role);
 7302:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7303:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7304: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7305:                return "refused:c:$crole&$cqual"; 
 7306:             }
 7307:         }
 7308:     }
 7309:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7310:                 "$env{'user.domain'}:$env{'user.name'}:".
 7311: 	        "rolesdef_$rolename=".
 7312:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7313:     return reply($command,$env{'user.home'});
 7314:   } else {
 7315:     return 'refused';
 7316:   }
 7317: }
 7318: 
 7319: # ---------------- Make a metadata query against the network of library servers
 7320: 
 7321: sub metadata_query {
 7322:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7323:     my %rhash;
 7324:     my %libserv = &all_library();
 7325:     my @server_list = (defined($server_array) ? @$server_array
 7326:                                               : keys(%libserv) );
 7327:     for my $server (@server_list) {
 7328:         my $domains = ''; 
 7329:         if (ref($domains_hash) eq 'HASH') {
 7330:             $domains = $domains_hash->{$server}; 
 7331:         }
 7332: 	unless ($custom or $customshow) {
 7333: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7334: 	    $rhash{$server}=$reply;
 7335: 	}
 7336: 	else {
 7337: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7338: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7339: 			     $server);
 7340: 	    $rhash{$server}=$reply;
 7341: 	}
 7342:     }
 7343:     return \%rhash;
 7344: }
 7345: 
 7346: # ----------------------------------------- Send log queries and wait for reply
 7347: 
 7348: sub log_query {
 7349:     my ($uname,$udom,$query,%filters)=@_;
 7350:     my $uhome=&homeserver($uname,$udom);
 7351:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7352:     my $uhost=&hostname($uhome);
 7353:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7354:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7355:                        $uhome);
 7356:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7357:     return get_query_reply($queryid);
 7358: }
 7359: 
 7360: # -------------------------- Update MySQL table for portfolio file
 7361: 
 7362: sub update_portfolio_table {
 7363:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7364:     if ($group ne '') {
 7365:         $file_name =~s /^\Q$group\E//;
 7366:     }
 7367:     my $homeserver = &homeserver($uname,$udom);
 7368:     my $queryid=
 7369:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7370:                ':'.&escape($file_name).':'.$action,$homeserver);
 7371:     my $reply = &get_query_reply($queryid);
 7372:     return $reply;
 7373: }
 7374: 
 7375: # -------------------------- Update MySQL allusers table
 7376: 
 7377: sub update_allusers_table {
 7378:     my ($uname,$udom,$names) = @_;
 7379:     my $homeserver = &homeserver($uname,$udom);
 7380:     my $queryid=
 7381:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7382:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7383:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7384:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7385:                'generation='.&escape($names->{'generation'}).'%%'.
 7386:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7387:                'id='.&escape($names->{'id'}),$homeserver);
 7388:     return;
 7389: }
 7390: 
 7391: # ------- Request retrieval of institutional classlists for course(s)
 7392: 
 7393: sub fetch_enrollment_query {
 7394:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7395:     my $homeserver;
 7396:     my $maxtries = 1;
 7397:     if ($context eq 'automated') {
 7398:         $homeserver = $perlvar{'lonHostID'};
 7399:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7400:     } else {
 7401:         $homeserver = &homeserver($cnum,$dom);
 7402:     }
 7403:     my $host=&hostname($homeserver);
 7404:     my $cmd = '';
 7405:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7406:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7407:     }
 7408:     $cmd =~ s/%%$//;
 7409:     $cmd = &escape($cmd);
 7410:     my $query = 'fetchenrollment';
 7411:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7412:     unless ($queryid=~/^\Q$host\E\_/) { 
 7413:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7414:         return 'error: '.$queryid;
 7415:     }
 7416:     my $reply = &get_query_reply($queryid);
 7417:     my $tries = 1;
 7418:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7419:         $reply = &get_query_reply($queryid);
 7420:         $tries ++;
 7421:     }
 7422:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7423:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7424:     } else {
 7425:         my @responses = split(/:/,$reply);
 7426:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7427:             foreach my $line (@responses) {
 7428:                 my ($key,$value) = split(/=/,$line,2);
 7429:                 $$replyref{$key} = $value;
 7430:             }
 7431:         } else {
 7432:             my $pathname = LONCAPA::tempdir();
 7433:             foreach my $line (@responses) {
 7434:                 my ($key,$value) = split(/=/,$line);
 7435:                 $$replyref{$key} = $value;
 7436:                 if ($value > 0) {
 7437:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7438:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7439:                         my $destname = $pathname.'/'.$filename;
 7440:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7441:                         if ($xml_classlist =~ /^error/) {
 7442:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7443:                         } else {
 7444:                             if ( open(FILE,">$destname") ) {
 7445:                                 print FILE &unescape($xml_classlist);
 7446:                                 close(FILE);
 7447:                             } else {
 7448:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7449:                             }
 7450:                         }
 7451:                     }
 7452:                 }
 7453:             }
 7454:         }
 7455:         return 'ok';
 7456:     }
 7457:     return 'error';
 7458: }
 7459: 
 7460: sub get_query_reply {
 7461:     my $queryid=shift;
 7462:     my $replyfile=LONCAPA::tempdir().$queryid;
 7463:     my $reply='';
 7464:     for (1..100) {
 7465: 	sleep 2;
 7466:         if (-e $replyfile.'.end') {
 7467: 	    if (open(my $fh,$replyfile)) {
 7468: 		$reply = join('',<$fh>);
 7469: 		close($fh);
 7470: 	   } else { return 'error: reply_file_error'; }
 7471:            return &unescape($reply);
 7472: 	}
 7473:     }
 7474:     return 'timeout:'.$queryid;
 7475: }
 7476: 
 7477: sub courselog_query {
 7478: #
 7479: # possible filters:
 7480: # url: url or symb
 7481: # username
 7482: # domain
 7483: # action: view, submit, grade
 7484: # start: timestamp
 7485: # end: timestamp
 7486: #
 7487:     my (%filters)=@_;
 7488:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7489:     if ($filters{'url'}) {
 7490: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7491:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7492:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7493:     }
 7494:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7495:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7496:     return &log_query($cname,$cdom,'courselog',%filters);
 7497: }
 7498: 
 7499: sub userlog_query {
 7500: #
 7501: # possible filters:
 7502: # action: log check role
 7503: # start: timestamp
 7504: # end: timestamp
 7505: #
 7506:     my ($uname,$udom,%filters)=@_;
 7507:     return &log_query($uname,$udom,'userlog',%filters);
 7508: }
 7509: 
 7510: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7511: 
 7512: sub auto_run {
 7513:     my ($cnum,$cdom) = @_;
 7514:     my $response = 0;
 7515:     my $settings;
 7516:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7517:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7518:         $settings = $domconfig{'autoenroll'};
 7519:         if ($settings->{'run'} eq '1') {
 7520:             $response = 1;
 7521:         }
 7522:     } else {
 7523:         my $homeserver;
 7524:         if (&is_course($cdom,$cnum)) {
 7525:             $homeserver = &homeserver($cnum,$cdom);
 7526:         } else {
 7527:             $homeserver = &domain($cdom,'primary');
 7528:         }
 7529:         if ($homeserver ne 'no_host') {
 7530:             $response = &reply('autorun:'.$cdom,$homeserver);
 7531:         }
 7532:     }
 7533:     return $response;
 7534: }
 7535: 
 7536: sub auto_get_sections {
 7537:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7538:     my $homeserver;
 7539:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7540:         $homeserver = &homeserver($cnum,$cdom);
 7541:     }
 7542:     if (!defined($homeserver)) { 
 7543:         if ($cdom =~ /^$match_domain$/) {
 7544:             $homeserver = &domain($cdom,'primary');
 7545:         }
 7546:     }
 7547:     my @secs;
 7548:     if (defined($homeserver)) {
 7549:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7550:         unless ($response eq 'refused') {
 7551:             @secs = split(/:/,$response);
 7552:         }
 7553:     }
 7554:     return @secs;
 7555: }
 7556: 
 7557: sub auto_new_course {
 7558:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7559:     my $homeserver = &homeserver($cnum,$cdom);
 7560:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7561:     return $response;
 7562: }
 7563: 
 7564: sub auto_validate_courseID {
 7565:     my ($cnum,$cdom,$inst_course_id) = @_;
 7566:     my $homeserver = &homeserver($cnum,$cdom);
 7567:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7568:     return $response;
 7569: }
 7570: 
 7571: sub auto_validate_instcode {
 7572:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7573:     my ($homeserver,$response);
 7574:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7575:         $homeserver = &homeserver($cnum,$cdom);
 7576:     }
 7577:     if (!defined($homeserver)) {
 7578:         if ($cdom =~ /^$match_domain$/) {
 7579:             $homeserver = &domain($cdom,'primary');
 7580:         }
 7581:     }
 7582:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7583:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7584:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7585:     return ($outcome,$description,$defaultcredits);
 7586: }
 7587: 
 7588: sub auto_create_password {
 7589:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7590:     my ($homeserver,$response);
 7591:     my $create_passwd = 0;
 7592:     my $authchk = '';
 7593:     if ($udom =~ /^$match_domain$/) {
 7594:         $homeserver = &domain($udom,'primary');
 7595:     }
 7596:     if ($homeserver eq '') {
 7597:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7598:             $homeserver = &homeserver($cnum,$cdom);
 7599:         }
 7600:     }
 7601:     if ($homeserver eq '') {
 7602:         $authchk = 'nodomain';
 7603:     } else {
 7604:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7605:         if ($response eq 'refused') {
 7606:             $authchk = 'refused';
 7607:         } else {
 7608:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7609:         }
 7610:     }
 7611:     return ($authparam,$create_passwd,$authchk);
 7612: }
 7613: 
 7614: sub auto_photo_permission {
 7615:     my ($cnum,$cdom,$students) = @_;
 7616:     my $homeserver = &homeserver($cnum,$cdom);
 7617:     my ($outcome,$perm_reqd,$conditions) = 
 7618: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7619:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7620: 	return (undef,undef);
 7621:     }
 7622:     return ($outcome,$perm_reqd,$conditions);
 7623: }
 7624: 
 7625: sub auto_checkphotos {
 7626:     my ($uname,$udom,$pid) = @_;
 7627:     my $homeserver = &homeserver($uname,$udom);
 7628:     my ($result,$resulttype);
 7629:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7630: 				   &escape($uname).':'.&escape($pid),
 7631: 				   $homeserver));
 7632:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7633: 	return (undef,undef);
 7634:     }
 7635:     if ($outcome) {
 7636:         ($result,$resulttype) = split(/:/,$outcome);
 7637:     } 
 7638:     return ($result,$resulttype);
 7639: }
 7640: 
 7641: sub auto_photochoice {
 7642:     my ($cnum,$cdom) = @_;
 7643:     my $homeserver = &homeserver($cnum,$cdom);
 7644:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7645: 						       &escape($cdom),
 7646: 						       $homeserver)));
 7647:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7648: 	return (undef,undef);
 7649:     }
 7650:     return ($update,$comment);
 7651: }
 7652: 
 7653: sub auto_photoupdate {
 7654:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7655:     my $homeserver = &homeserver($cnum,$dom);
 7656:     my $host=&hostname($homeserver);
 7657:     my $cmd = '';
 7658:     my $maxtries = 1;
 7659:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7660:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7661:     }
 7662:     $cmd =~ s/%%$//;
 7663:     $cmd = &escape($cmd);
 7664:     my $query = 'institutionalphotos';
 7665:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7666:     unless ($queryid=~/^\Q$host\E\_/) {
 7667:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7668:         return 'error: '.$queryid;
 7669:     }
 7670:     my $reply = &get_query_reply($queryid);
 7671:     my $tries = 1;
 7672:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7673:         $reply = &get_query_reply($queryid);
 7674:         $tries ++;
 7675:     }
 7676:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7677:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7678:     } else {
 7679:         my @responses = split(/:/,$reply);
 7680:         my $outcome = shift(@responses); 
 7681:         foreach my $item (@responses) {
 7682:             my ($key,$value) = split(/=/,$item);
 7683:             $$photo{$key} = $value;
 7684:         }
 7685:         return $outcome;
 7686:     }
 7687:     return 'error';
 7688: }
 7689: 
 7690: sub auto_instcode_format {
 7691:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7692: 	$cat_order) = @_;
 7693:     my $courses = '';
 7694:     my @homeservers;
 7695:     if ($caller eq 'global') {
 7696: 	my %servers = &get_servers($codedom,'library');
 7697: 	foreach my $tryserver (keys(%servers)) {
 7698: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7699: 		push(@homeservers,$tryserver);
 7700: 	    }
 7701:         }
 7702:     } elsif ($caller eq 'requests') {
 7703:         if ($codedom =~ /^$match_domain$/) {
 7704:             my $chome = &domain($codedom,'primary');
 7705:             unless ($chome eq 'no_host') {
 7706:                 push(@homeservers,$chome);
 7707:             }
 7708:         }
 7709:     } else {
 7710:         push(@homeservers,&homeserver($caller,$codedom));
 7711:     }
 7712:     foreach my $code (keys(%{$instcodes})) {
 7713:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7714:     }
 7715:     chop($courses);
 7716:     my $ok_response = 0;
 7717:     my $response;
 7718:     while (@homeservers > 0 && $ok_response == 0) {
 7719:         my $server = shift(@homeservers); 
 7720:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7721:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7722:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7723: 		split(/:/,$response);
 7724:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7725:             push(@{$codetitles},&str2array($codetitles_str));
 7726:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7727:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7728:             $ok_response = 1;
 7729:         }
 7730:     }
 7731:     if ($ok_response) {
 7732:         return 'ok';
 7733:     } else {
 7734:         return $response;
 7735:     }
 7736: }
 7737: 
 7738: sub auto_instcode_defaults {
 7739:     my ($domain,$returnhash,$code_order) = @_;
 7740:     my @homeservers;
 7741: 
 7742:     my %servers = &get_servers($domain,'library');
 7743:     foreach my $tryserver (keys(%servers)) {
 7744: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7745: 	    push(@homeservers,$tryserver);
 7746: 	}
 7747:     }
 7748: 
 7749:     my $response;
 7750:     foreach my $server (@homeservers) {
 7751:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7752:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7753: 	
 7754: 	foreach my $pair (split(/\&/,$response)) {
 7755: 	    my ($name,$value)=split(/\=/,$pair);
 7756: 	    if ($name eq 'code_order') {
 7757: 		@{$code_order} = split(/\&/,&unescape($value));
 7758: 	    } else {
 7759: 		$returnhash->{&unescape($name)}=&unescape($value);
 7760: 	    }
 7761: 	}
 7762: 	return 'ok';
 7763:     }
 7764: 
 7765:     return $response;
 7766: }
 7767: 
 7768: sub auto_possible_instcodes {
 7769:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7770:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7771:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7772:         return;
 7773:     }
 7774:     my (@homeservers,$uhome);
 7775:     if (defined(&domain($domain,'primary'))) {
 7776:         $uhome=&domain($domain,'primary');
 7777:         push(@homeservers,&domain($domain,'primary'));
 7778:     } else {
 7779:         my %servers = &get_servers($domain,'library');
 7780:         foreach my $tryserver (keys(%servers)) {
 7781:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7782:                 push(@homeservers,$tryserver);
 7783:             }
 7784:         }
 7785:     }
 7786:     my $response;
 7787:     foreach my $server (@homeservers) {
 7788:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7789:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7790:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7791:             split(':',$response);
 7792:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7793:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7794:         foreach my $item (split('&',$cat_title)) {   
 7795:             my ($name,$value)=split('=',$item);
 7796:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7797:         }
 7798:         foreach my $item (split('&',$cat_order)) {
 7799:             my ($name,$value)=split('=',$item);
 7800:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7801:         }
 7802:         return 'ok';
 7803:     }
 7804:     return $response;
 7805: }
 7806: 
 7807: sub auto_courserequest_checks {
 7808:     my ($dom) = @_;
 7809:     my ($homeserver,%validations);
 7810:     if ($dom =~ /^$match_domain$/) {
 7811:         $homeserver = &domain($dom,'primary');
 7812:     }
 7813:     unless ($homeserver eq 'no_host') {
 7814:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7815:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7816:             my @items = split(/&/,$response);
 7817:             foreach my $item (@items) {
 7818:                 my ($key,$value) = split('=',$item);
 7819:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7820:             }
 7821:         }
 7822:     }
 7823:     return %validations; 
 7824: }
 7825: 
 7826: sub auto_courserequest_validation {
 7827:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7828:     my ($homeserver,$response);
 7829:     if ($dom =~ /^$match_domain$/) {
 7830:         $homeserver = &domain($dom,'primary');
 7831:     }
 7832:     unless ($homeserver eq 'no_host') {  
 7833:           
 7834:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7835:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7836:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7837:                                     $homeserver));
 7838:     }
 7839:     return $response;
 7840: }
 7841: 
 7842: sub auto_validate_class_sec {
 7843:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7844:     my $homeserver = &homeserver($cnum,$cdom);
 7845:     my $ownerlist;
 7846:     if (ref($owners) eq 'ARRAY') {
 7847:         $ownerlist = join(',',@{$owners});
 7848:     } else {
 7849:         $ownerlist = $owners;
 7850:     }
 7851:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7852:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7853:     return $response;
 7854: }
 7855: 
 7856: # ------------------------------------------------------- Course Group routines
 7857: 
 7858: sub get_coursegroups {
 7859:     my ($cdom,$cnum,$group,$namespace) = @_;
 7860:     return(&dump($namespace,$cdom,$cnum,$group));
 7861: }
 7862: 
 7863: sub modify_coursegroup {
 7864:     my ($cdom,$cnum,$groupsettings) = @_;
 7865:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7866: }
 7867: 
 7868: sub toggle_coursegroup_status {
 7869:     my ($cdom,$cnum,$group,$action) = @_;
 7870:     my ($from_namespace,$to_namespace);
 7871:     if ($action eq 'delete') {
 7872:         $from_namespace = 'coursegroups';
 7873:         $to_namespace = 'deleted_groups';
 7874:     } else {
 7875:         $from_namespace = 'deleted_groups';
 7876:         $to_namespace = 'coursegroups';
 7877:     }
 7878:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7879:     if (my $tmp = &error(%curr_group)) {
 7880:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7881:         return ('read error',$tmp);
 7882:     } else {
 7883:         my %savedsettings = %curr_group; 
 7884:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7885:         my $deloutcome;
 7886:         if ($result eq 'ok') {
 7887:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7888:         } else {
 7889:             return ('write error',$result);
 7890:         }
 7891:         if ($deloutcome eq 'ok') {
 7892:             return 'ok';
 7893:         } else {
 7894:             return ('delete error',$deloutcome);
 7895:         }
 7896:     }
 7897: }
 7898: 
 7899: sub modify_group_roles {
 7900:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7901:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7902:     my $role = 'gr/'.&escape($userprivs);
 7903:     my ($uname,$udom) = split(/:/,$user);
 7904:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7905:     if ($result eq 'ok') {
 7906:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7907:     }
 7908:     return $result;
 7909: }
 7910: 
 7911: sub modify_coursegroup_membership {
 7912:     my ($cdom,$cnum,$membership) = @_;
 7913:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7914:     return $result;
 7915: }
 7916: 
 7917: sub get_active_groups {
 7918:     my ($udom,$uname,$cdom,$cnum) = @_;
 7919:     my $now = time;
 7920:     my %groups = ();
 7921:     foreach my $key (keys(%env)) {
 7922:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7923:             my ($start,$end) = split(/\./,$env{$key});
 7924:             if (($end!=0) && ($end<$now)) { next; }
 7925:             if (($start!=0) && ($start>$now)) { next; }
 7926:             if ($1 eq $cdom && $2 eq $cnum) {
 7927:                 $groups{$3} = $env{$key} ;
 7928:             }
 7929:         }
 7930:     }
 7931:     return %groups;
 7932: }
 7933: 
 7934: sub get_group_membership {
 7935:     my ($cdom,$cnum,$group) = @_;
 7936:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7937: }
 7938: 
 7939: sub get_users_groups {
 7940:     my ($udom,$uname,$courseid) = @_;
 7941:     my @usersgroups;
 7942:     my $cachetime=1800;
 7943: 
 7944:     my $hashid="$udom:$uname:$courseid";
 7945:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7946:     if (defined($cached)) {
 7947:         @usersgroups = split(/:/,$grouplist);
 7948:     } else {  
 7949:         $grouplist = '';
 7950:         my $courseurl = &courseid_to_courseurl($courseid);
 7951:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7952:         my $access_end = $env{'course.'.$courseid.
 7953:                               '.default_enrollment_end_date'};
 7954:         my $now = time;
 7955:         foreach my $key (keys(%roleshash)) {
 7956:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7957:                 my $group = $1;
 7958:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7959:                     my $start = $2;
 7960:                     my $end = $1;
 7961:                     if ($start == -1) { next; } # deleted from group
 7962:                     if (($start!=0) && ($start>$now)) { next; }
 7963:                     if (($end!=0) && ($end<$now)) {
 7964:                         if ($access_end && $access_end < $now) {
 7965:                             if ($access_end - $end < 86400) {
 7966:                                 push(@usersgroups,$group);
 7967:                             }
 7968:                         }
 7969:                         next;
 7970:                     }
 7971:                     push(@usersgroups,$group);
 7972:                 }
 7973:             }
 7974:         }
 7975:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7976:         $grouplist = join(':',@usersgroups);
 7977:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7978:     }
 7979:     return @usersgroups;
 7980: }
 7981: 
 7982: sub devalidate_getgroups_cache {
 7983:     my ($udom,$uname,$cdom,$cnum)=@_;
 7984:     my $courseid = $cdom.'_'.$cnum;
 7985: 
 7986:     my $hashid="$udom:$uname:$courseid";
 7987:     &devalidate_cache_new('getgroups',$hashid);
 7988: }
 7989: 
 7990: # ------------------------------------------------------------------ Plain Text
 7991: 
 7992: sub plaintext {
 7993:     my ($short,$type,$cid,$forcedefault) = @_;
 7994:     if ($short =~ m{^cr/}) {
 7995: 	return (split('/',$short))[-1];
 7996:     }
 7997:     if (!defined($cid)) {
 7998:         $cid = $env{'request.course.id'};
 7999:     }
 8000:     my %rolenames = (
 8001:                       Course    => 'std',
 8002:                       Community => 'alt1',
 8003:                     );
 8004:     if ($cid ne '') {
 8005:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8006:             unless ($forcedefault) {
 8007:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8008:                 &Apache::lonlocal::mt_escape(\$roletext);
 8009:                 return &Apache::lonlocal::mt($roletext);
 8010:             }
 8011:         }
 8012:     }
 8013:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8014:         (defined($rolenames{$type})) && 
 8015:         (defined($prp{$short}{$rolenames{$type}}))) {
 8016:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8017:     } elsif ($cid ne '') {
 8018:         my $crstype = $env{'course.'.$cid.'.type'};
 8019:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8020:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8021:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8022:         }
 8023:     }
 8024:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8025: }
 8026: 
 8027: # ----------------------------------------------------------------- Assign Role
 8028: 
 8029: sub assignrole {
 8030:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8031:         $context)=@_;
 8032:     my $mrole;
 8033:     if ($role =~ /^cr\//) {
 8034:         my $cwosec=$url;
 8035:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8036: 	unless (&allowed('ccr',$cwosec)) {
 8037:            my $refused = 1;
 8038:            if ($context eq 'requestcourses') {
 8039:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8040:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8041:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8042:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8043:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8044:                            if ($crsenv{'internal.courseowner'} eq
 8045:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8046:                                $refused = '';
 8047:                            }
 8048:                        }
 8049:                    }
 8050:                }
 8051:            }
 8052:            if ($refused) {
 8053:                &logthis('Refused custom assignrole: '.
 8054:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8055:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8056:                return 'refused';
 8057:            }
 8058:         }
 8059:         $mrole='cr';
 8060:     } elsif ($role =~ /^gr\//) {
 8061:         my $cwogrp=$url;
 8062:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8063:         unless (&allowed('mdg',$cwogrp)) {
 8064:             &logthis('Refused group assignrole: '.
 8065:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8066:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8067:             return 'refused';
 8068:         }
 8069:         $mrole='gr';
 8070:     } else {
 8071:         my $cwosec=$url;
 8072:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8073:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8074:             my $refused;
 8075:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8076:                 if (!(&allowed('c'.$role,$url))) {
 8077:                     $refused = 1;
 8078:                 }
 8079:             } else {
 8080:                 $refused = 1;
 8081:             }
 8082:             if ($refused) {
 8083:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8084:                 if (!$selfenroll && $context eq 'course') {
 8085:                     my %crsenv;
 8086:                     if ($role eq 'cc' || $role eq 'co') {
 8087:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8088:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8089:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8090:                                 if ($crsenv{'internal.courseowner'} eq 
 8091:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8092:                                     $refused = '';
 8093:                                 }
 8094:                             }
 8095:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8096:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8097:                                 if ($crsenv{'internal.courseowner'} eq 
 8098:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8099:                                     $refused = '';
 8100:                                 }
 8101:                             }
 8102:                         }
 8103:                     }
 8104:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8105:                     $refused = '';
 8106:                 } elsif ($context eq 'requestcourses') {
 8107:                     my @possroles = ('st','ta','ep','in','cc','co');
 8108:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8109:                         my $wrongcc;
 8110:                         if ($cnum =~ /^$match_community$/) {
 8111:                             $wrongcc = 1 if ($role eq 'cc');
 8112:                         } else {
 8113:                             $wrongcc = 1 if ($role eq 'co');
 8114:                         }
 8115:                         unless ($wrongcc) {
 8116:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8117:                             if ($crsenv{'internal.courseowner'} eq 
 8118:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8119:                                 $refused = '';
 8120:                             }
 8121:                         }
 8122:                     }
 8123:                 } elsif ($context eq 'requestauthor') {
 8124:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8125:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8126:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8127:                             $refused = '';
 8128:                         } else {
 8129:                             my %domdefaults = &get_domain_defaults($udom);
 8130:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8131:                                 my $checkbystatus;
 8132:                                 if ($env{'user.adv'}) { 
 8133:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8134:                                     if ($disposition eq 'automatic') {
 8135:                                         $refused = '';
 8136:                                     } elsif ($disposition eq '') {
 8137:                                         $checkbystatus = 1;
 8138:                                     } 
 8139:                                 } else {
 8140:                                     $checkbystatus = 1;
 8141:                                 }
 8142:                                 if ($checkbystatus) {
 8143:                                     if ($env{'environment.inststatus'}) {
 8144:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8145:                                         foreach my $type (@inststatuses) {
 8146:                                             if (($type ne '') &&
 8147:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8148:                                                 $refused = '';
 8149:                                             }
 8150:                                         }
 8151:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8152:                                         $refused = '';
 8153:                                     }
 8154:                                 }
 8155:                             }
 8156:                         }
 8157:                     }
 8158:                 }
 8159:                 if ($refused) {
 8160:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8161:                              ' '.$role.' '.$end.' '.$start.' by '.
 8162: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8163:                     return 'refused';
 8164:                 }
 8165:             }
 8166:         } elsif ($role eq 'au') {
 8167:             if ($url ne '/'.$udom.'/') {
 8168:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8169:                          ' to assign author role for '.$uname.':'.$udom.
 8170:                          ' in domain: '.$url.' refused (wrong domain).');
 8171:                 return 'refused';
 8172:             }
 8173:         }
 8174:         $mrole=$role;
 8175:     }
 8176:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8177:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8178:     if ($end) { $command.='_'.$end; }
 8179:     if ($start) {
 8180: 	if ($end) { 
 8181:            $command.='_'.$start; 
 8182:         } else {
 8183:            $command.='_0_'.$start;
 8184:         }
 8185:     }
 8186:     my $origstart = $start;
 8187:     my $origend = $end;
 8188:     my $delflag;
 8189: # actually delete
 8190:     if ($deleteflag) {
 8191: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8192: # modify command to delete the role
 8193:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8194:                 "$udom:$uname:$url".'_'."$mrole";
 8195: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8196: # set start and finish to negative values for userrolelog
 8197:            $start=-1;
 8198:            $end=-1;
 8199:            $delflag = 1;
 8200:         }
 8201:     }
 8202: # send command
 8203:     my $answer=&reply($command,&homeserver($uname,$udom));
 8204: # log new user role if status is ok
 8205:     if ($answer eq 'ok') {
 8206: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8207:         if (($role eq 'cc') || ($role eq 'in') ||
 8208:             ($role eq 'ep') || ($role eq 'ad') ||
 8209:             ($role eq 'ta') || ($role eq 'st') ||
 8210:             ($role=~/^cr/) || ($role eq 'gr') ||
 8211:             ($role eq 'co')) {
 8212: # for course roles, perform group memberships changes triggered by role change.
 8213:             unless ($role =~ /^gr/) {
 8214:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8215:                                                  $origstart,$selfenroll,$context);
 8216:             }
 8217:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8218:                            $selfenroll,$context);
 8219:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8220:                  ($role eq 'au') || ($role eq 'dc')) {
 8221:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8222:                            $context);
 8223:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8224:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8225:                              $context); 
 8226:         }
 8227:         if ($role eq 'cc') {
 8228:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8229:         }
 8230:     }
 8231:     return $answer;
 8232: }
 8233: 
 8234: sub autoupdate_coowners {
 8235:     my ($url,$end,$start,$uname,$udom) = @_;
 8236:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8237:     if (($cdom ne '') && ($cnum ne '')) {
 8238:         my $now = time;
 8239:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8240:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8241:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8242:             my $instcode = $coursehash{'internal.coursecode'};
 8243:             if ($instcode ne '') {
 8244:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8245:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8246:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8247:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8248:                         if ($result eq 'valid') {
 8249:                             if ($coursehash{'internal.co-owners'}) {
 8250:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8251:                                     push(@newcoowners,$coowner);
 8252:                                 }
 8253:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8254:                                     push(@newcoowners,$uname.':'.$udom);
 8255:                                 }
 8256:                                 @newcoowners = sort(@newcoowners);
 8257:                             } else {
 8258:                                 push(@newcoowners,$uname.':'.$udom);
 8259:                             }
 8260:                         } else {
 8261:                             if ($coursehash{'internal.co-owners'}) {
 8262:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8263:                                     unless ($coowner eq $uname.':'.$udom) {
 8264:                                         push(@newcoowners,$coowner);
 8265:                                     }
 8266:                                 }
 8267:                                 unless (@newcoowners > 0) {
 8268:                                     $delcoowners = 1;
 8269:                                     $coowners = '';
 8270:                                 }
 8271:                             }
 8272:                         }
 8273:                         if (@newcoowners || $delcoowners) {
 8274:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8275:                                             $delcoowners,@newcoowners);
 8276:                         }
 8277:                     }
 8278:                 }
 8279:             }
 8280:         }
 8281:     }
 8282: }
 8283: 
 8284: sub store_coowners {
 8285:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8286:     my $cid = $cdom.'_'.$cnum;
 8287:     my ($coowners,$delresult,$putresult);
 8288:     if (@newcoowners) {
 8289:         $coowners = join(',',@newcoowners);
 8290:         my %coownershash = (
 8291:                             'internal.co-owners' => $coowners,
 8292:                            );
 8293:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8294:         if ($putresult eq 'ok') {
 8295:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8296:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8297:             }
 8298:         }
 8299:     }
 8300:     if ($delcoowners) {
 8301:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8302:         if ($delresult eq 'ok') {
 8303:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8304:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8305:             }
 8306:         }
 8307:     }
 8308:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8309:         my %crsinfo =
 8310:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8311:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8312:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8313:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8314:         }
 8315:     }
 8316: }
 8317: 
 8318: # -------------------------------------------------- Modify user authentication
 8319: # Overrides without validation
 8320: 
 8321: sub modifyuserauth {
 8322:     my ($udom,$uname,$umode,$upass)=@_;
 8323:     my $uhome=&homeserver($uname,$udom);
 8324:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8325:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8326:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8327:              ' in domain '.$env{'request.role.domain'});  
 8328:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8329: 		     &escape($upass),$uhome);
 8330:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8331:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8332:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8333:     &log($udom,,$uname,$uhome,
 8334:         'Authentication changed by '.$env{'user.domain'}.', '.
 8335:                                      $env{'user.name'}.', '.$umode.
 8336:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8337:     unless ($reply eq 'ok') {
 8338:         &logthis('Authentication mode error: '.$reply);
 8339: 	return 'error: '.$reply;
 8340:     }   
 8341:     return 'ok';
 8342: }
 8343: 
 8344: # --------------------------------------------------------------- Modify a user
 8345: 
 8346: sub modifyuser {
 8347:     my ($udom,    $uname, $uid,
 8348:         $umode,   $upass, $first,
 8349:         $middle,  $last,  $gene,
 8350:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8351:     $udom= &LONCAPA::clean_domain($udom);
 8352:     $uname=&LONCAPA::clean_username($uname);
 8353:     my $showcandelete = 'none';
 8354:     if (ref($candelete) eq 'ARRAY') {
 8355:         if (@{$candelete} > 0) {
 8356:             $showcandelete = join(', ',@{$candelete});
 8357:         }
 8358:     }
 8359:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8360:              $umode.', '.$first.', '.$middle.', '.
 8361: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8362:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8363:                                      ' desiredhome not specified'). 
 8364:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8365:              ' in domain '.$env{'request.role.domain'});
 8366:     my $uhome=&homeserver($uname,$udom,'true');
 8367:     my $newuser;
 8368:     if ($uhome eq 'no_host') {
 8369:         $newuser = 1;
 8370:     }
 8371: # ----------------------------------------------------------------- Create User
 8372:     if (($uhome eq 'no_host') && 
 8373: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8374:         my $unhome='';
 8375:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8376:             $unhome = $desiredhome;
 8377: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8378: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8379:         } else { # load balancing routine for determining $unhome
 8380:             my $loadm=10000000;
 8381: 	    my %servers = &get_servers($udom,'library');
 8382: 	    foreach my $tryserver (keys(%servers)) {
 8383: 		my $answer=reply('load',$tryserver);
 8384: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8385: 		    $loadm=$answer;
 8386: 		    $unhome=$tryserver;
 8387: 		}
 8388: 	    }
 8389:         }
 8390:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8391: 	    return 'error: unable to find a home server for '.$uname.
 8392:                    ' in domain '.$udom;
 8393:         }
 8394:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8395:                          &escape($upass),$unhome);
 8396: 	unless ($reply eq 'ok') {
 8397:             return 'error: '.$reply;
 8398:         }   
 8399:         $uhome=&homeserver($uname,$udom,'true');
 8400:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8401: 	    return 'error: unable verify users home machine.';
 8402:         }
 8403:     }   # End of creation of new user
 8404: # ---------------------------------------------------------------------- Add ID
 8405:     if ($uid) {
 8406:        $uid=~tr/A-Z/a-z/;
 8407:        my %uidhash=&idrget($udom,$uname);
 8408:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8409:          && (!$forceid)) {
 8410: 	  unless ($uid eq $uidhash{$uname}) {
 8411: 	      return 'error: user id "'.$uid.'" does not match '.
 8412:                   'current user id "'.$uidhash{$uname}.'".';
 8413:           }
 8414:        } else {
 8415: 	  &idput($udom,($uname => $uid));
 8416:        }
 8417:     }
 8418: # -------------------------------------------------------------- Add names, etc
 8419:     my @tmp=&get('environment',
 8420: 		   ['firstname','middlename','lastname','generation','id',
 8421:                     'permanentemail','inststatus'],
 8422: 		   $udom,$uname);
 8423:     my (%names,%oldnames);
 8424:     if ($tmp[0] =~ m/^error:.*/) { 
 8425:         %names=(); 
 8426:     } else {
 8427:         %names = @tmp;
 8428:         %oldnames = %names;
 8429:     }
 8430: #
 8431: # If name, email and/or uid are blank (e.g., because an uploaded file
 8432: # of users did not contain them), do not overwrite existing values
 8433: # unless field is in $candelete array ref.  
 8434: #
 8435: 
 8436:     my @fields = ('firstname','middlename','lastname','generation',
 8437:                   'permanentemail','id');
 8438:     my %newvalues;
 8439:     if (ref($candelete) eq 'ARRAY') {
 8440:         foreach my $field (@fields) {
 8441:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8442:                 if ($field eq 'firstname') {
 8443:                     $names{$field} = $first;
 8444:                 } elsif ($field eq 'middlename') {
 8445:                     $names{$field} = $middle;
 8446:                 } elsif ($field eq 'lastname') {
 8447:                     $names{$field} = $last;
 8448:                 } elsif ($field eq 'generation') { 
 8449:                     $names{$field} = $gene;
 8450:                 } elsif ($field eq 'permanentemail') {
 8451:                     $names{$field} = $email;
 8452:                 } elsif ($field eq 'id') {
 8453:                     $names{$field}  = $uid;
 8454:                 }
 8455:             }
 8456:         }
 8457:     }
 8458:     if ($first)  { $names{'firstname'}  = $first; }
 8459:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8460:     if ($last)   { $names{'lastname'}   = $last; }
 8461:     if (defined($gene))   { $names{'generation'} = $gene; }
 8462:     if ($email) {
 8463:        $email=~s/[^\w\@\.\-\,]//gs;
 8464:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8465:     }
 8466:     if ($uid) { $names{'id'}  = $uid; }
 8467:     if (defined($inststatus)) {
 8468:         $names{'inststatus'} = '';
 8469:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8470:         if (ref($usertypes) eq 'HASH') {
 8471:             my @okstatuses; 
 8472:             foreach my $item (split(/:/,$inststatus)) {
 8473:                 if (defined($usertypes->{$item})) {
 8474:                     push(@okstatuses,$item);  
 8475:                 }
 8476:             }
 8477:             if (@okstatuses) {
 8478:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8479:             }
 8480:         }
 8481:     }
 8482:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8483:                  $umode.', '.$first.', '.$middle.', '.
 8484:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8485:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8486:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8487:     } else {
 8488:         $logmsg .= ' during self creation';
 8489:     }
 8490:     my $changed;
 8491:     if ($newuser) {
 8492:         $changed = 1;
 8493:     } else {
 8494:         foreach my $field (@fields) {
 8495:             if ($names{$field} ne $oldnames{$field}) {
 8496:                 $changed = 1;
 8497:                 last;
 8498:             }
 8499:         }
 8500:     }
 8501:     unless ($changed) {
 8502:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8503:         &logthis($logmsg);
 8504:         return 'ok';
 8505:     }
 8506:     my $reply = &put('environment', \%names, $udom,$uname);
 8507:     if ($reply ne 'ok') { 
 8508:         return 'error: '.$reply;
 8509:     }
 8510:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8511:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8512:     }
 8513:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8514:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8515:     $logmsg = 'Success modifying user '.$logmsg;
 8516:     &logthis($logmsg);
 8517:     return 'ok';
 8518: }
 8519: 
 8520: # -------------------------------------------------------------- Modify student
 8521: 
 8522: sub modifystudent {
 8523:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8524:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8525:         $selfenroll,$context,$inststatus,$credits)=@_;
 8526:     if (!$cid) {
 8527: 	unless ($cid=$env{'request.course.id'}) {
 8528: 	    return 'not_in_class';
 8529: 	}
 8530:     }
 8531: # --------------------------------------------------------------- Make the user
 8532:     my $reply=&modifyuser
 8533: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8534:          $desiredhome,$email,$inststatus);
 8535:     unless ($reply eq 'ok') { return $reply; }
 8536:     # This will cause &modify_student_enrollment to get the uid from the
 8537:     # student's environment
 8538:     $uid = undef if (!$forceid);
 8539:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8540:                                         $gene,$usec,$end,$start,$type,$locktype,
 8541:                                         $cid,$selfenroll,$context,$credits);
 8542:     return $reply;
 8543: }
 8544: 
 8545: sub modify_student_enrollment {
 8546:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8547:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8548:     my ($cdom,$cnum,$chome);
 8549:     if (!$cid) {
 8550: 	unless ($cid=$env{'request.course.id'}) {
 8551: 	    return 'not_in_class';
 8552: 	}
 8553: 	$cdom=$env{'course.'.$cid.'.domain'};
 8554: 	$cnum=$env{'course.'.$cid.'.num'};
 8555:     } else {
 8556: 	($cdom,$cnum)=split(/_/,$cid);
 8557:     }
 8558:     $chome=$env{'course.'.$cid.'.home'};
 8559:     if (!$chome) {
 8560: 	$chome=&homeserver($cnum,$cdom);
 8561:     }
 8562:     if (!$chome) { return 'unknown_course'; }
 8563:     # Make sure the user exists
 8564:     my $uhome=&homeserver($uname,$udom);
 8565:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8566: 	return 'error: no such user';
 8567:     }
 8568:     # Get student data if we were not given enough information
 8569:     if (!defined($first)  || $first  eq '' || 
 8570:         !defined($last)   || $last   eq '' || 
 8571:         !defined($uid)    || $uid    eq '' || 
 8572:         !defined($middle) || $middle eq '' || 
 8573:         !defined($gene)   || $gene   eq '') {
 8574:         # They did not supply us with enough data to enroll the student, so
 8575:         # we need to pick up more information.
 8576:         my %tmp = &get('environment',
 8577:                        ['firstname','middlename','lastname', 'generation','id']
 8578:                        ,$udom,$uname);
 8579: 
 8580:         #foreach my $key (keys(%tmp)) {
 8581:         #    &logthis("key $key = ".$tmp{$key});
 8582:         #}
 8583:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8584:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8585:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8586:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8587:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8588:     }
 8589:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8590:     my $user = "$uname:$udom";
 8591:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8592:     my $reply=cput('classlist',
 8593: 		   {$user => 
 8594: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8595: 		   $cdom,$cnum);
 8596:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8597:         &devalidate_getsection_cache($udom,$uname,$cid);
 8598:     } else { 
 8599: 	return 'error: '.$reply;
 8600:     }
 8601:     # Add student role to user
 8602:     my $uurl='/'.$cid;
 8603:     $uurl=~s/\_/\//g;
 8604:     if ($usec) {
 8605: 	$uurl.='/'.$usec;
 8606:     }
 8607:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8608:                              $selfenroll,$context);
 8609:     if ($result ne 'ok') {
 8610:         if ($old_entry{$user} ne '') {
 8611:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8612:         } else {
 8613:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8614:         }
 8615:     }
 8616:     return $result; 
 8617: }
 8618: 
 8619: sub format_name {
 8620:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8621:     my $name;
 8622:     if ($first ne 'lastname') {
 8623: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8624:     } else {
 8625: 	if ($lastname=~/\S/) {
 8626: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8627: 	    $name=~s/\s+,/,/;
 8628: 	} else {
 8629: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8630: 	}
 8631:     }
 8632:     $name=~s/^\s+//;
 8633:     $name=~s/\s+$//;
 8634:     $name=~s/\s+/ /g;
 8635:     return $name;
 8636: }
 8637: 
 8638: # ------------------------------------------------- Write to course preferences
 8639: 
 8640: sub writecoursepref {
 8641:     my ($courseid,%prefs)=@_;
 8642:     $courseid=~s/^\///;
 8643:     $courseid=~s/\_/\//g;
 8644:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8645:     my $chome=homeserver($cnum,$cdomain);
 8646:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8647: 	return 'error: no such course';
 8648:     }
 8649:     my $cstring='';
 8650:     foreach my $pref (keys(%prefs)) {
 8651: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8652:     }
 8653:     $cstring=~s/\&$//;
 8654:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8655: }
 8656: 
 8657: # ---------------------------------------------------------- Make/modify course
 8658: 
 8659: sub createcourse {
 8660:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8661:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8662:     $url=&declutter($url);
 8663:     my $cid='';
 8664:     if ($context eq 'requestcourses') {
 8665:         my $can_create = 0;
 8666:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8667:         if ($udom eq $ownerdom) {
 8668:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8669:                                   $context)) {
 8670:                 $can_create = 1;
 8671:             }
 8672:         } else {
 8673:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8674:                                            $category);
 8675:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8676:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8677:                 if (@curr > 0) {
 8678:                     my @options = qw(approval validate autolimit);
 8679:                     my $optregex = join('|',@options);
 8680:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8681:                         $can_create = 1;
 8682:                     }
 8683:                 }
 8684:             }
 8685:         }
 8686:         if ($can_create) {
 8687:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8688:                 unless (&allowed('ccc',$udom)) {
 8689:                     return 'refused'; 
 8690:                 }
 8691:             }
 8692:         } else {
 8693:             return 'refused';
 8694:         }
 8695:     } elsif (!&allowed('ccc',$udom)) {
 8696:         return 'refused';
 8697:     }
 8698: # --------------------------------------------------------------- Get Unique ID
 8699:     my $uname;
 8700:     if ($cnum =~ /^$match_courseid$/) {
 8701:         my $chome=&homeserver($cnum,$udom,'true');
 8702:         if (($chome eq '') || ($chome eq 'no_host')) {
 8703:             $uname = $cnum;
 8704:         } else {
 8705:             $uname = &generate_coursenum($udom,$crstype);
 8706:         }
 8707:     } else {
 8708:         $uname = &generate_coursenum($udom,$crstype);
 8709:     }
 8710:     return $uname if ($uname =~ /^error/);
 8711: # -------------------------------------------------- Check supplied server name
 8712:     if (!defined($course_server)) {
 8713:         if (defined(&domain($udom,'primary'))) {
 8714:             $course_server = &domain($udom,'primary');
 8715:         } else {
 8716:             $course_server = $env{'user.home'}; 
 8717:         }
 8718:     }
 8719:     my %host_servers =
 8720:         &Apache::lonnet::get_servers($udom,'library');
 8721:     unless ($host_servers{$course_server}) {
 8722:         return 'error: invalid home server for course: '.$course_server;
 8723:     }
 8724: # ------------------------------------------------------------- Make the course
 8725:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8726:                       $course_server);
 8727:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8728:     my $uhome=&homeserver($uname,$udom,'true');
 8729:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8730: 	return 'error: no such course';
 8731:     }
 8732: # ----------------------------------------------------------------- Course made
 8733: # log existence
 8734:     my $now = time;
 8735:     my $newcourse = {
 8736:                     $udom.'_'.$uname => {
 8737:                                      description => $description,
 8738:                                      inst_code   => $inst_code,
 8739:                                      owner       => $course_owner,
 8740:                                      type        => $crstype,
 8741:                                      creator     => $env{'user.name'}.':'.
 8742:                                                     $env{'user.domain'},
 8743:                                      created     => $now,
 8744:                                      context     => $context,
 8745:                                                 },
 8746:                     };
 8747:     &courseidput($udom,$newcourse,$uhome,'notime');
 8748: # set toplevel url
 8749:     my $topurl=$url;
 8750:     unless ($nonstandard) {
 8751: # ------------------------------------------ For standard courses, make top url
 8752:         my $mapurl=&clutter($url);
 8753:         if ($mapurl eq '/res/') { $mapurl=''; }
 8754:         $env{'form.initmap'}=(<<ENDINITMAP);
 8755: <map>
 8756: <resource id="1" type="start"></resource>
 8757: <resource id="2" src="$mapurl"></resource>
 8758: <resource id="3" type="finish"></resource>
 8759: <link index="1" from="1" to="2"></link>
 8760: <link index="2" from="2" to="3"></link>
 8761: </map>
 8762: ENDINITMAP
 8763:         $topurl=&declutter(
 8764:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8765:                           );
 8766:     }
 8767: # ----------------------------------------------------------- Write preferences
 8768:     &writecoursepref($udom.'_'.$uname,
 8769:                      ('description'              => $description,
 8770:                       'url'                      => $topurl,
 8771:                       'internal.creator'         => $env{'user.name'}.':'.
 8772:                                                     $env{'user.domain'},
 8773:                       'internal.created'         => $now,
 8774:                       'internal.creationcontext' => $context)
 8775:                     );
 8776:     return '/'.$udom.'/'.$uname;
 8777: }
 8778: 
 8779: # ------------------------------------------------------------------- Create ID
 8780: sub generate_coursenum {
 8781:     my ($udom,$crstype) = @_;
 8782:     my $domdesc = &domain($udom);
 8783:     return 'error: invalid domain' if ($domdesc eq '');
 8784:     my $first;
 8785:     if ($crstype eq 'Community') {
 8786:         $first = '0';
 8787:     } else {
 8788:         $first = int(1+rand(9)); 
 8789:     } 
 8790:     my $uname=$first.
 8791:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8792:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8793:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8794: # ----------------------------------------------- Make sure that does not exist
 8795:     my $uhome=&homeserver($uname,$udom,'true');
 8796:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8797:         if ($crstype eq 'Community') {
 8798:             $first = '0';
 8799:         } else {
 8800:             $first = int(1+rand(9));
 8801:         }
 8802:         $uname=$first.
 8803:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8804:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8805:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8806:         $uhome=&homeserver($uname,$udom,'true');
 8807:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8808:             return 'error: unable to generate unique course-ID';
 8809:         }
 8810:     }
 8811:     return $uname;
 8812: }
 8813: 
 8814: sub is_course {
 8815:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8816:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8817: 
 8818:     return unless $cdom and $cnum;
 8819: 
 8820:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8821:         '.');
 8822: 
 8823:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8824:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8825: }
 8826: 
 8827: sub store_userdata {
 8828:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8829:     my $result;
 8830:     if ($datakey ne '') {
 8831:         if (ref($storehash) eq 'HASH') {
 8832:             if ($udom eq '' || $uname eq '') {
 8833:                 $udom = $env{'user.domain'};
 8834:                 $uname = $env{'user.name'};
 8835:             }
 8836:             my $uhome=&homeserver($uname,$udom);
 8837:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8838:                 $result = 'error: no_host';
 8839:             } else {
 8840:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8841:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8842: 
 8843:                 my $namevalue='';
 8844:                 foreach my $key (keys(%{$storehash})) {
 8845:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8846:                 }
 8847:                 $namevalue=~s/\&$//;
 8848:                 unless ($namespace eq 'courserequests') {
 8849:                     $datakey = &escape($datakey);
 8850:                 }
 8851:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8852:                                   $namevalue,$uhome);
 8853:             }
 8854:         } else {
 8855:             $result = 'error: data to store was not a hash reference'; 
 8856:         }
 8857:     } else {
 8858:         $result= 'error: invalid requestkey'; 
 8859:     }
 8860:     return $result;
 8861: }
 8862: 
 8863: # ---------------------------------------------------------- Assign Custom Role
 8864: 
 8865: sub assigncustomrole {
 8866:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8867:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8868:                        $end,$start,$deleteflag,$selfenroll,$context);
 8869: }
 8870: 
 8871: # ----------------------------------------------------------------- Revoke Role
 8872: 
 8873: sub revokerole {
 8874:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8875:     my $now=time;
 8876:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8877: }
 8878: 
 8879: # ---------------------------------------------------------- Revoke Custom Role
 8880: 
 8881: sub revokecustomrole {
 8882:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8883:     my $now=time;
 8884:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8885:            $deleteflag,$selfenroll,$context);
 8886: }
 8887: 
 8888: # ------------------------------------------------------------ Disk usage
 8889: sub diskusage {
 8890:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8891:     $directorypath =~ s/\/$//;
 8892:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8893:                        .&escape($getpropath).':'.&escape($uname).':'
 8894:                        .&escape($udom),homeserver($uname,$udom));
 8895:     if ($listing eq 'unknown_cmd') {
 8896:         if ($getpropath) {
 8897:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8898:         }
 8899:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8900:     }
 8901:     return $listing;
 8902: }
 8903: 
 8904: sub is_locked {
 8905:     my ($file_name, $domain, $user, $which) = @_;
 8906:     my @check;
 8907:     my $is_locked;
 8908:     push (@check,$file_name);
 8909:     my %locked = &get('file_permissions',\@check,
 8910: 		      $env{'user.domain'},$env{'user.name'});
 8911:     my ($tmp)=keys(%locked);
 8912:     if ($tmp=~/^error:/) { undef(%locked); }
 8913:     
 8914:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8915:         $is_locked = 'false';
 8916:         foreach my $entry (@{$locked{$file_name}}) {
 8917:            if (ref($entry) eq 'ARRAY') {
 8918:                $is_locked = 'true';
 8919:                if (ref($which) eq 'ARRAY') {
 8920:                    push(@{$which},$entry);
 8921:                } else {
 8922:                    last;
 8923:                }
 8924:            }
 8925:        }
 8926:     } else {
 8927:         $is_locked = 'false';
 8928:     }
 8929:     return $is_locked;
 8930: }
 8931: 
 8932: sub declutter_portfile {
 8933:     my ($file) = @_;
 8934:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8935:     return $file;
 8936: }
 8937: 
 8938: # ------------------------------------------------------------- Mark as Read Only
 8939: 
 8940: sub mark_as_readonly {
 8941:     my ($domain,$user,$files,$what) = @_;
 8942:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8943:     my ($tmp)=keys(%current_permissions);
 8944:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8945:     foreach my $file (@{$files}) {
 8946: 	$file = &declutter_portfile($file);
 8947:         push(@{$current_permissions{$file}},$what);
 8948:     }
 8949:     &put('file_permissions',\%current_permissions,$domain,$user);
 8950:     return;
 8951: }
 8952: 
 8953: # ------------------------------------------------------------Save Selected Files
 8954: 
 8955: sub save_selected_files {
 8956:     my ($user, $path, @files) = @_;
 8957:     my $filename = $user."savedfiles";
 8958:     my @other_files = &files_not_in_path($user, $path);
 8959:     open (OUT, '>'.$tmpdir.$filename);
 8960:     foreach my $file (@files) {
 8961:         print (OUT $env{'form.currentpath'}.$file."\n");
 8962:     }
 8963:     foreach my $file (@other_files) {
 8964:         print (OUT $file."\n");
 8965:     }
 8966:     close (OUT);
 8967:     return 'ok';
 8968: }
 8969: 
 8970: sub clear_selected_files {
 8971:     my ($user) = @_;
 8972:     my $filename = $user."savedfiles";
 8973:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8974:     print (OUT undef);
 8975:     close (OUT);
 8976:     return ("ok");    
 8977: }
 8978: 
 8979: sub files_in_path {
 8980:     my ($user, $path) = @_;
 8981:     my $filename = $user."savedfiles";
 8982:     my %return_files;
 8983:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8984:     while (my $line_in = <IN>) {
 8985:         chomp ($line_in);
 8986:         my @paths_and_file = split (m!/!, $line_in);
 8987:         my $file_part = pop (@paths_and_file);
 8988:         my $path_part = join ('/', @paths_and_file);
 8989:         $path_part.='/';
 8990:         my $path_and_file = $path_part.$file_part;
 8991:         if ($path_part eq $path) {
 8992:             $return_files{$file_part}= 'selected';
 8993:         }
 8994:     }
 8995:     close (IN);
 8996:     return (\%return_files);
 8997: }
 8998: 
 8999: # called in portfolio select mode, to show files selected NOT in current directory
 9000: sub files_not_in_path {
 9001:     my ($user, $path) = @_;
 9002:     my $filename = $user."savedfiles";
 9003:     my @return_files;
 9004:     my $path_part;
 9005:     open(IN, '<'.LONCAPA::.$filename);
 9006:     while (my $line = <IN>) {
 9007:         #ok, I know it's clunky, but I want it to work
 9008:         my @paths_and_file = split(m|/|, $line);
 9009:         my $file_part = pop(@paths_and_file);
 9010:         chomp($file_part);
 9011:         my $path_part = join('/', @paths_and_file);
 9012:         $path_part .= '/';
 9013:         my $path_and_file = $path_part.$file_part;
 9014:         if ($path_part ne $path) {
 9015:             push(@return_files, ($path_and_file));
 9016:         }
 9017:     }
 9018:     close(OUT);
 9019:     return (@return_files);
 9020: }
 9021: 
 9022: #----------------------------------------------Get portfolio file permissions
 9023: 
 9024: sub get_portfile_permissions {
 9025:     my ($domain,$user) = @_;
 9026:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9027:     my ($tmp)=keys(%current_permissions);
 9028:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9029:     return \%current_permissions;
 9030: }
 9031: 
 9032: #---------------------------------------------Get portfolio file access controls
 9033: 
 9034: sub get_access_controls {
 9035:     my ($current_permissions,$group,$file) = @_;
 9036:     my %access;
 9037:     my $real_file = $file;
 9038:     $file =~ s/\.meta$//;
 9039:     if (defined($file)) {
 9040:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9041:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9042:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9043:             }
 9044:         }
 9045:     } else {
 9046:         foreach my $key (keys(%{$current_permissions})) {
 9047:             if ($key =~ /\0accesscontrol$/) {
 9048:                 if (defined($group)) {
 9049:                     if ($key !~ m-^\Q$group\E/-) {
 9050:                         next;
 9051:                     }
 9052:                 }
 9053:                 my ($fullpath) = split(/\0/,$key);
 9054:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9055:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9056:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9057:                     }
 9058:                 }
 9059:             }
 9060:         }
 9061:     }
 9062:     return %access;
 9063: }
 9064: 
 9065: sub modify_access_controls {
 9066:     my ($file_name,$changes,$domain,$user)=@_;
 9067:     my ($outcome,$deloutcome);
 9068:     my %store_permissions;
 9069:     my %new_values;
 9070:     my %new_control;
 9071:     my %translation;
 9072:     my @deletions = ();
 9073:     my $now = time;
 9074:     if (exists($$changes{'activate'})) {
 9075:         if (ref($$changes{'activate'}) eq 'HASH') {
 9076:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9077:             my $numnew = scalar(@newitems);
 9078:             for (my $i=0; $i<$numnew; $i++) {
 9079:                 my $newkey = $newitems[$i];
 9080:                 my $newid = &Apache::loncommon::get_cgi_id();
 9081:                 if ($newkey =~ /^\d+:/) { 
 9082:                     $newkey =~ s/^(\d+)/$newid/;
 9083:                     $translation{$1} = $newid;
 9084:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9085:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9086:                     $translation{$1} = $newid;
 9087:                 }
 9088:                 $new_values{$file_name."\0".$newkey} = 
 9089:                                           $$changes{'activate'}{$newitems[$i]};
 9090:                 $new_control{$newkey} = $now;
 9091:             }
 9092:         }
 9093:     }
 9094:     my %todelete;
 9095:     my %changed_items;
 9096:     foreach my $action ('delete','update') {
 9097:         if (exists($$changes{$action})) {
 9098:             if (ref($$changes{$action}) eq 'HASH') {
 9099:                 foreach my $key (keys(%{$$changes{$action}})) {
 9100:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9101:                     if ($action eq 'delete') { 
 9102:                         $todelete{$itemnum} = 1;
 9103:                     } else {
 9104:                         $changed_items{$itemnum} = $key;
 9105:                     }
 9106:                 }
 9107:             }
 9108:         }
 9109:     }
 9110:     # get lock on access controls for file.
 9111:     my $lockhash = {
 9112:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9113:                                                        ':'.$env{'user.domain'},
 9114:                    }; 
 9115:     my $tries = 0;
 9116:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9117:    
 9118:     while (($gotlock ne 'ok') && $tries <3) {
 9119:         $tries ++;
 9120:         sleep 1;
 9121:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9122:     }
 9123:     if ($gotlock eq 'ok') {
 9124:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9125:         my ($tmp)=keys(%curr_permissions);
 9126:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9127:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9128:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9129:             if (ref($curr_controls) eq 'HASH') {
 9130:                 foreach my $control_item (keys(%{$curr_controls})) {
 9131:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9132:                     if (defined($todelete{$itemnum})) {
 9133:                         push(@deletions,$file_name."\0".$control_item);
 9134:                     } else {
 9135:                         if (defined($changed_items{$itemnum})) {
 9136:                             $new_control{$changed_items{$itemnum}} = $now;
 9137:                             push(@deletions,$file_name."\0".$control_item);
 9138:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9139:                         } else {
 9140:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9141:                         }
 9142:                     }
 9143:                 }
 9144:             }
 9145:         }
 9146:         my ($group);
 9147:         if (&is_course($domain,$user)) {
 9148:             ($group,my $file) = split(/\//,$file_name,2);
 9149:         }
 9150:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9151:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9152:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9153:         #  remove lock
 9154:         my @del_lock = ($file_name."\0".'locked_access_records');
 9155:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9156:         my $sqlresult =
 9157:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9158:                                     $group);
 9159:     } else {
 9160:         $outcome = "error: could not obtain lockfile\n";  
 9161:     }
 9162:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9163: }
 9164: 
 9165: sub make_public_indefinitely {
 9166:     my ($requrl) = @_;
 9167:     my $now = time;
 9168:     my $action = 'activate';
 9169:     my $aclnum = 0;
 9170:     if (&is_portfolio_url($requrl)) {
 9171:         my (undef,$udom,$unum,$file_name,$group) =
 9172:             &parse_portfolio_url($requrl);
 9173:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9174:         my %access_controls = &get_access_controls($current_perms,
 9175:                                                    $group,$file_name);
 9176:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9177:             my ($num,$scope,$end,$start) = 
 9178:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9179:             if ($scope eq 'public') {
 9180:                 if ($start <= $now && $end == 0) {
 9181:                     $action = 'none';
 9182:                 } else {
 9183:                     $action = 'update';
 9184:                     $aclnum = $num;
 9185:                 }
 9186:                 last;
 9187:             }
 9188:         }
 9189:         if ($action eq 'none') {
 9190:              return 'ok';
 9191:         } else {
 9192:             my %changes;
 9193:             my $newend = 0;
 9194:             my $newstart = $now;
 9195:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9196:             $changes{$action}{$newkey} = {
 9197:                 type => 'public',
 9198:                 time => {
 9199:                     start => $newstart,
 9200:                     end   => $newend,
 9201:                 },
 9202:             };
 9203:             my ($outcome,$deloutcome,$new_values,$translation) =
 9204:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9205:             return $outcome;
 9206:         }
 9207:     } else {
 9208:         return 'invalid';
 9209:     }
 9210: }
 9211: 
 9212: #------------------------------------------------------Get Marked as Read Only
 9213: 
 9214: sub get_marked_as_readonly {
 9215:     my ($domain,$user,$what,$group) = @_;
 9216:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9217:     my @readonly_files;
 9218:     my $cmp1=$what;
 9219:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9220:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9221:         if (defined($group)) {
 9222:             if ($file_name !~ m-^\Q$group\E/-) {
 9223:                 next;
 9224:             }
 9225:         }
 9226:         if (ref($value) eq "ARRAY"){
 9227:             foreach my $stored_what (@{$value}) {
 9228:                 my $cmp2=$stored_what;
 9229:                 if (ref($stored_what) eq 'ARRAY') {
 9230:                     $cmp2=join('',@{$stored_what});
 9231:                 }
 9232:                 if ($cmp1 eq $cmp2) {
 9233:                     push(@readonly_files, $file_name);
 9234:                     last;
 9235:                 } elsif (!defined($what)) {
 9236:                     push(@readonly_files, $file_name);
 9237:                     last;
 9238:                 }
 9239:             }
 9240:         }
 9241:     }
 9242:     return @readonly_files;
 9243: }
 9244: #-----------------------------------------------------------Get Marked as Read Only Hash
 9245: 
 9246: sub get_marked_as_readonly_hash {
 9247:     my ($current_permissions,$group,$what) = @_;
 9248:     my %readonly_files;
 9249:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9250:         if (defined($group)) {
 9251:             if ($file_name !~ m-^\Q$group\E/-) {
 9252:                 next;
 9253:             }
 9254:         }
 9255:         if (ref($value) eq "ARRAY"){
 9256:             foreach my $stored_what (@{$value}) {
 9257:                 if (ref($stored_what) eq 'ARRAY') {
 9258:                     foreach my $lock_descriptor(@{$stored_what}) {
 9259:                         if ($lock_descriptor eq 'graded') {
 9260:                             $readonly_files{$file_name} = 'graded';
 9261:                         } elsif ($lock_descriptor eq 'handback') {
 9262:                             $readonly_files{$file_name} = 'handback';
 9263:                         } else {
 9264:                             if (!exists($readonly_files{$file_name})) {
 9265:                                 $readonly_files{$file_name} = 'locked';
 9266:                             }
 9267:                         }
 9268:                     }
 9269:                 } 
 9270:             }
 9271:         } 
 9272:     }
 9273:     return %readonly_files;
 9274: }
 9275: # ------------------------------------------------------------ Unmark as Read Only
 9276: 
 9277: sub unmark_as_readonly {
 9278:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9279:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9280:     my ($domain,$user,$what,$file_name,$group) = @_;
 9281:     $file_name = &declutter_portfile($file_name);
 9282:     my $symb_crs = $what;
 9283:     if (ref($what)) { $symb_crs=join('',@$what); }
 9284:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9285:     my ($tmp)=keys(%current_permissions);
 9286:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9287:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9288:     foreach my $file (@readonly_files) {
 9289: 	my $clean_file = &declutter_portfile($file);
 9290: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9291: 	my $current_locks = $current_permissions{$file};
 9292:         my @new_locks;
 9293:         my @del_keys;
 9294:         if (ref($current_locks) eq "ARRAY"){
 9295:             foreach my $locker (@{$current_locks}) {
 9296:                 my $compare=$locker;
 9297:                 if (ref($locker) eq 'ARRAY') {
 9298:                     $compare=join('',@{$locker});
 9299:                     if ($compare ne $symb_crs) {
 9300:                         push(@new_locks, $locker);
 9301:                     }
 9302:                 }
 9303:             }
 9304:             if (scalar(@new_locks) > 0) {
 9305:                 $current_permissions{$file} = \@new_locks;
 9306:             } else {
 9307:                 push(@del_keys, $file);
 9308:                 &del('file_permissions',\@del_keys, $domain, $user);
 9309:                 delete($current_permissions{$file});
 9310:             }
 9311:         }
 9312:     }
 9313:     &put('file_permissions',\%current_permissions,$domain,$user);
 9314:     return;
 9315: }
 9316: 
 9317: # ------------------------------------------------------------ Directory lister
 9318: 
 9319: sub dirlist {
 9320:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9321:     $uri=~s/^\///;
 9322:     $uri=~s/\/$//;
 9323:     my ($udom, $uname);
 9324:     if ($getuserdir) {
 9325:         $udom = $userdomain;
 9326:         $uname = $username;
 9327:     } else {
 9328:         (undef,$udom,$uname)=split(/\//,$uri);
 9329:         if(defined($userdomain)) {
 9330:             $udom = $userdomain;
 9331:         }
 9332:         if(defined($username)) {
 9333:             $uname = $username;
 9334:         }
 9335:     }
 9336:     my ($dirRoot,$listing,@listing_results);
 9337: 
 9338:     $dirRoot = $perlvar{'lonDocRoot'};
 9339:     if (defined($getpropath)) {
 9340:         $dirRoot = &propath($udom,$uname);
 9341:         $dirRoot =~ s/\/$//;
 9342:     } elsif (defined($getuserdir)) {
 9343:         my $subdir=$uname.'__';
 9344:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9345:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9346:                    ."/$udom/$subdir/$uname";
 9347:     } elsif (defined($alternateRoot)) {
 9348:         $dirRoot = $alternateRoot;
 9349:     }
 9350: 
 9351:     if($udom) {
 9352:         if($uname) {
 9353:             my $uhome = &homeserver($uname,$udom);
 9354:             if ($uhome eq 'no_host') {
 9355:                 return ([],'no_host');
 9356:             }
 9357:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9358:                               .$getuserdir.':'.&escape($dirRoot)
 9359:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9360:             if ($listing eq 'unknown_cmd') {
 9361:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9362:             } else {
 9363:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9364:             }
 9365:             if ($listing eq 'unknown_cmd') {
 9366:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9367:                 @listing_results = split(/:/,$listing);
 9368:             } else {
 9369:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9370:             }
 9371:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9372:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9373:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9374:                 return ([],$listing);
 9375:             } else {
 9376:                 return (\@listing_results);
 9377:             }
 9378:         } elsif(!$alternateRoot) {
 9379:             my (%allusers,%listerror);
 9380: 	    my %servers = &get_servers($udom,'library');
 9381:  	    foreach my $tryserver (keys(%servers)) {
 9382:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9383:                                   &escape($udom),$tryserver);
 9384:                 if ($listing eq 'unknown_cmd') {
 9385: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9386: 				      $udom, $tryserver);
 9387:                 } else {
 9388:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9389:                 }
 9390: 		if ($listing eq 'unknown_cmd') {
 9391: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9392: 				      $udom, $tryserver);
 9393: 		    @listing_results = split(/:/,$listing);
 9394: 		} else {
 9395: 		    @listing_results =
 9396: 			map { &unescape($_); } split(/:/,$listing);
 9397: 		}
 9398:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9399:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9400:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9401:                     $listerror{$tryserver} = $listing;
 9402:                 } else {
 9403: 		    foreach my $line (@listing_results) {
 9404: 			my ($entry) = split(/&/,$line,2);
 9405: 			$allusers{$entry} = 1;
 9406: 		    }
 9407: 		}
 9408:             }
 9409:             my @alluserslist=();
 9410:             foreach my $user (sort(keys(%allusers))) {
 9411:                 push(@alluserslist,$user.'&user');
 9412:             }
 9413:             return (\@alluserslist);
 9414:         } else {
 9415:             return ([],'missing username');
 9416:         }
 9417:     } elsif(!defined($getpropath)) {
 9418:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9419:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9420:         return (\@all_domains);
 9421:     } else {
 9422:         return ([],'missing domain');
 9423:     }
 9424: }
 9425: 
 9426: # --------------------------------------------- GetFileTimestamp
 9427: # This function utilizes dirlist and returns the date stamp for
 9428: # when it was last modified.  It will also return an error of -1
 9429: # if an error occurs
 9430: 
 9431: sub GetFileTimestamp {
 9432:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9433:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9434:     $studentName   = &LONCAPA::clean_username($studentName);
 9435:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9436:                                     undef,$getuserdir);
 9437:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9438:         return -1;
 9439:     }
 9440:     if (ref($fileref) eq 'ARRAY') {
 9441:         my @stats = split('&',$fileref->[0]);
 9442:         # @stats contains first the filename, then the stat output
 9443:         return $stats[10]; # so this is 10 instead of 9.
 9444:     } else {
 9445:         return -1;
 9446:     }
 9447: }
 9448: 
 9449: sub stat_file {
 9450:     my ($uri) = @_;
 9451:     $uri = &clutter_with_no_wrapper($uri);
 9452: 
 9453:     my ($udom,$uname,$file);
 9454:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9455: 	($udom,$uname,$file) =
 9456: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9457: 	$file = 'userfiles/'.$file;
 9458:     }
 9459:     if ($uri =~ m-^/res/-) {
 9460: 	($udom,$uname) = 
 9461: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9462: 	$file = $uri;
 9463:     }
 9464: 
 9465:     if (!$udom || !$uname || !$file) {
 9466: 	# unable to handle the uri
 9467: 	return ();
 9468:     }
 9469:     my $getpropath;
 9470:     if ($file =~ /^userfiles\//) {
 9471:         $getpropath = 1;
 9472:     }
 9473:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9474:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9475:         return ();
 9476:     } else {
 9477:         if (ref($listref) eq 'ARRAY') {
 9478:             my @stats = split('&',$listref->[0]);
 9479: 	    shift(@stats); #filename is first
 9480: 	    return @stats;
 9481:         }
 9482:     }
 9483:     return ();
 9484: }
 9485: 
 9486: # -------------------------------------------------------- Value of a Condition
 9487: 
 9488: # gets the value of a specific preevaluated condition
 9489: #    stored in the string  $env{user.state.<cid>}
 9490: # or looks up a condition reference in the bighash and if if hasn't
 9491: # already been evaluated recurses into docondval to get the value of
 9492: # the condition, then memoizing it to 
 9493: #   $env{user.state.<cid>.<condition>}
 9494: sub directcondval {
 9495:     my $number=shift;
 9496:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9497: 	&Apache::lonuserstate::evalstate();
 9498:     }
 9499:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9500: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9501:     } elsif ($number =~ /^_/) {
 9502: 	my $sub_condition;
 9503: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9504: 		&GDBM_READER(),0640)) {
 9505: 	    $sub_condition=$bighash{'conditions'.$number};
 9506: 	    untie(%bighash);
 9507: 	}
 9508: 	my $value = &docondval($sub_condition);
 9509: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9510: 	return $value;
 9511:     }
 9512:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9513:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9514:     } else {
 9515:        return 2;
 9516:     }
 9517: }
 9518: 
 9519: # get the collection of conditions for this resource
 9520: sub condval {
 9521:     my $condidx=shift;
 9522:     my $allpathcond='';
 9523:     foreach my $cond (split(/\|/,$condidx)) {
 9524: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9525: 	    $allpathcond.=
 9526: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9527: 	}
 9528:     }
 9529:     $allpathcond=~s/\|$//;
 9530:     return &docondval($allpathcond);
 9531: }
 9532: 
 9533: #evaluates an expression of conditions
 9534: sub docondval {
 9535:     my ($allpathcond) = @_;
 9536:     my $result=0;
 9537:     if ($env{'request.course.id'}
 9538: 	&& defined($allpathcond)) {
 9539: 	my $operand='|';
 9540: 	my @stack;
 9541: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9542: 	    if ($chunk eq '(') {
 9543: 		push @stack,($operand,$result);
 9544: 	    } elsif ($chunk eq ')') {
 9545: 		my $before=pop @stack;
 9546: 		if (pop @stack eq '&') {
 9547: 		    $result=$result>$before?$before:$result;
 9548: 		} else {
 9549: 		    $result=$result>$before?$result:$before;
 9550: 		}
 9551: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9552: 		$operand=$chunk;
 9553: 	    } else {
 9554: 		my $new=directcondval($chunk);
 9555: 		if ($operand eq '&') {
 9556: 		    $result=$result>$new?$new:$result;
 9557: 		} else {
 9558: 		    $result=$result>$new?$result:$new;
 9559: 		}
 9560: 	    }
 9561: 	}
 9562:     }
 9563:     return $result;
 9564: }
 9565: 
 9566: # ---------------------------------------------------- Devalidate courseresdata
 9567: 
 9568: sub devalidatecourseresdata {
 9569:     my ($coursenum,$coursedomain)=@_;
 9570:     my $hashid=$coursenum.':'.$coursedomain;
 9571:     &devalidate_cache_new('courseres',$hashid);
 9572: }
 9573: 
 9574: 
 9575: # --------------------------------------------------- Course Resourcedata Query
 9576: #
 9577: #  Parameters:
 9578: #      $coursenum    - Number of the course.
 9579: #      $coursedomain - Domain at which the course was created.
 9580: #  Returns:
 9581: #     A hash of the course parameters along (I think) with timestamps
 9582: #     and version info.
 9583: 
 9584: sub get_courseresdata {
 9585:     my ($coursenum,$coursedomain)=@_;
 9586:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9587:     my $hashid=$coursenum.':'.$coursedomain;
 9588:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9589:     my %dumpreply;
 9590:     unless (defined($cached)) {
 9591: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9592: 	$result=\%dumpreply;
 9593: 	my ($tmp) = keys(%dumpreply);
 9594: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9595: 	    &do_cache_new('courseres',$hashid,$result,600);
 9596: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9597: 	    return $tmp;
 9598: 	} elsif ($tmp =~ /^(error)/) {
 9599: 	    $result=undef;
 9600: 	    &do_cache_new('courseres',$hashid,$result,600);
 9601: 	}
 9602:     }
 9603:     return $result;
 9604: }
 9605: 
 9606: sub devalidateuserresdata {
 9607:     my ($uname,$udom)=@_;
 9608:     my $hashid="$udom:$uname";
 9609:     &devalidate_cache_new('userres',$hashid);
 9610: }
 9611: 
 9612: sub get_userresdata {
 9613:     my ($uname,$udom)=@_;
 9614:     #most student don\'t have any data set, check if there is some data
 9615:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9616: 
 9617:     my $hashid="$udom:$uname";
 9618:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9619:     if (!defined($cached)) {
 9620: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9621: 	$result=\%resourcedata;
 9622: 	&do_cache_new('userres',$hashid,$result,600);
 9623:     }
 9624:     my ($tmp)=keys(%$result);
 9625:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9626: 	return $result;
 9627:     }
 9628:     #error 2 occurs when the .db doesn't exist
 9629:     if ($tmp!~/error: 2 /) {
 9630: 	&logthis("<font color=\"blue\">WARNING:".
 9631: 		 " Trying to get resource data for ".
 9632: 		 $uname." at ".$udom.": ".
 9633: 		 $tmp."</font>");
 9634:     } elsif ($tmp=~/error: 2 /) {
 9635: 	#&EXT_cache_set($udom,$uname);
 9636: 	&do_cache_new('userres',$hashid,undef,600);
 9637: 	undef($tmp); # not really an error so don't send it back
 9638:     }
 9639:     return $tmp;
 9640: }
 9641: #----------------------------------------------- resdata - return resource data
 9642: #  Purpose:
 9643: #    Return resource data for either users or for a course.
 9644: #  Parameters:
 9645: #     $name      - Course/user name.
 9646: #     $domain    - Name of the domain the user/course is registered on.
 9647: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9648: #     @which     - Array of names of resources desired.
 9649: #  Returns:
 9650: #     The value of the first reasource in @which that is found in the
 9651: #     resource hash.
 9652: #  Exceptional Conditions:
 9653: #     If the $type passed in is not valid (not the string 'course' or 
 9654: #     'user', an undefined  reference is returned.
 9655: #     If none of the resources are found, an undef is returned
 9656: sub resdata {
 9657:     my ($name,$domain,$type,@which)=@_;
 9658:     my $result;
 9659:     if ($type eq 'course') {
 9660: 	$result=&get_courseresdata($name,$domain);
 9661:     } elsif ($type eq 'user') {
 9662: 	$result=&get_userresdata($name,$domain);
 9663:     }
 9664:     if (!ref($result)) { return $result; }    
 9665:     foreach my $item (@which) {
 9666: 	if (defined($result->{$item->[0]})) {
 9667: 	    return [$result->{$item->[0]},$item->[1]];
 9668: 	}
 9669:     }
 9670:     return undef;
 9671: }
 9672: 
 9673: sub get_numsuppfiles {
 9674:     my ($cnum,$cdom,$ignorecache)=@_;
 9675:     my $hashid=$cnum.':'.$cdom;
 9676:     my ($suppcount,$cached);
 9677:     unless ($ignorecache) {
 9678:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9679:     }
 9680:     unless (defined($cached)) {
 9681:         my $chome=&homeserver($cnum,$cdom);
 9682:         unless ($chome eq 'no_host') {
 9683:             ($suppcount,my $errors) = (0,0);
 9684:             my $suppmap = 'supplemental.sequence';
 9685:             ($suppcount,$errors) = 
 9686:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9687:         }
 9688:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9689:     }
 9690:     return $suppcount;
 9691: }
 9692: 
 9693: #
 9694: # EXT resource caching routines
 9695: #
 9696: 
 9697: sub clear_EXT_cache_status {
 9698:     &delenv('cache.EXT.');
 9699: }
 9700: 
 9701: sub EXT_cache_status {
 9702:     my ($target_domain,$target_user) = @_;
 9703:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9704:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9705:         # We know already the user has no data
 9706:         return 1;
 9707:     } else {
 9708:         return 0;
 9709:     }
 9710: }
 9711: 
 9712: sub EXT_cache_set {
 9713:     my ($target_domain,$target_user) = @_;
 9714:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9715:     #&appenv({$cachename => time});
 9716: }
 9717: 
 9718: # --------------------------------------------------------- Value of a Variable
 9719: sub EXT {
 9720: 
 9721:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9722:     unless ($varname) { return ''; }
 9723:     #get real user name/domain, courseid and symb
 9724:     my $courseid;
 9725:     my $publicuser;
 9726:     if ($symbparm) {
 9727: 	$symbparm=&get_symb_from_alias($symbparm);
 9728:     }
 9729:     if (!($uname && $udom)) {
 9730:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9731:       if (!$symbparm) {	$symbparm=$cursymb; }
 9732:     } else {
 9733: 	$courseid=$env{'request.course.id'};
 9734:     }
 9735:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9736:     my $rest;
 9737:     if (defined($therest[0])) {
 9738:        $rest=join('.',@therest);
 9739:     } else {
 9740:        $rest='';
 9741:     }
 9742: 
 9743:     my $qualifierrest=$qualifier;
 9744:     if ($rest) { $qualifierrest.='.'.$rest; }
 9745:     my $spacequalifierrest=$space;
 9746:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9747:     if ($realm eq 'user') {
 9748: # --------------------------------------------------------------- user.resource
 9749: 	if ($space eq 'resource') {
 9750: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9751: 		  || defined($Apache::lonhomework::parsing_a_task))
 9752: 		 &&
 9753: 		 ($symbparm eq &symbread()) ) {	
 9754: 		# if we are in the middle of processing the resource the
 9755: 		# get the value we are planning on committing
 9756:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9757:                     return $Apache::lonhomework::results{$qualifierrest};
 9758:                 } else {
 9759:                     return $Apache::lonhomework::history{$qualifierrest};
 9760:                 }
 9761: 	    } else {
 9762: 		my %restored;
 9763: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9764: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9765: 		} else {
 9766: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9767: 		}
 9768: 		return $restored{$qualifierrest};
 9769: 	    }
 9770: # ----------------------------------------------------------------- user.access
 9771:         } elsif ($space eq 'access') {
 9772: 	    # FIXME - not supporting calls for a specific user
 9773:             return &allowed($qualifier,$rest);
 9774: # ------------------------------------------ user.preferences, user.environment
 9775:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9776: 	    if (($uname eq $env{'user.name'}) &&
 9777: 		($udom eq $env{'user.domain'})) {
 9778: 		return $env{join('.',('environment',$qualifierrest))};
 9779: 	    } else {
 9780: 		my %returnhash;
 9781: 		if (!$publicuser) {
 9782: 		    %returnhash=&userenvironment($udom,$uname,
 9783: 						 $qualifierrest);
 9784: 		}
 9785: 		return $returnhash{$qualifierrest};
 9786: 	    }
 9787: # ----------------------------------------------------------------- user.course
 9788:         } elsif ($space eq 'course') {
 9789: 	    # FIXME - not supporting calls for a specific user
 9790:             return $env{join('.',('request.course',$qualifier))};
 9791: # ------------------------------------------------------------------- user.role
 9792:         } elsif ($space eq 'role') {
 9793: 	    # FIXME - not supporting calls for a specific user
 9794:             my ($role,$where)=split(/\./,$env{'request.role'});
 9795:             if ($qualifier eq 'value') {
 9796: 		return $role;
 9797:             } elsif ($qualifier eq 'extent') {
 9798:                 return $where;
 9799:             }
 9800: # ----------------------------------------------------------------- user.domain
 9801:         } elsif ($space eq 'domain') {
 9802:             return $udom;
 9803: # ------------------------------------------------------------------- user.name
 9804:         } elsif ($space eq 'name') {
 9805:             return $uname;
 9806: # ---------------------------------------------------- Any other user namespace
 9807:         } else {
 9808: 	    my %reply;
 9809: 	    if (!$publicuser) {
 9810: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9811: 	    }
 9812: 	    return $reply{$qualifierrest};
 9813:         }
 9814:     } elsif ($realm eq 'query') {
 9815: # ---------------------------------------------- pull stuff out of query string
 9816:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9817: 						[$spacequalifierrest]);
 9818: 	return $env{'form.'.$spacequalifierrest}; 
 9819:    } elsif ($realm eq 'request') {
 9820: # ------------------------------------------------------------- request.browser
 9821:         if ($space eq 'browser') {
 9822:             return $env{'browser.'.$qualifier};
 9823: # ------------------------------------------------------------ request.filename
 9824:         } else {
 9825:             return $env{'request.'.$spacequalifierrest};
 9826:         }
 9827:     } elsif ($realm eq 'course') {
 9828: # ---------------------------------------------------------- course.description
 9829:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9830:     } elsif ($realm eq 'resource') {
 9831: 
 9832: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9833: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9834: 	}
 9835: 
 9836:         if ($qualifier eq '') {
 9837: 	    if ($space eq 'title') {
 9838: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9839: 	        return &gettitle($symbparm);
 9840: 	    }
 9841: 	
 9842: 	    if ($space eq 'map') {
 9843: 	        my ($map) = &decode_symb($symbparm);
 9844: 	        return &symbread($map);
 9845: 	    }
 9846:             if ($space eq 'maptitle') {
 9847:                 my ($map) = &decode_symb($symbparm);
 9848:                 return &gettitle($map);
 9849:             }
 9850: 	    if ($space eq 'filename') {
 9851: 	        if ($symbparm) {
 9852: 		    return &clutter((&decode_symb($symbparm))[2]);
 9853: 	        }
 9854: 	        return &hreflocation('',$env{'request.filename'});
 9855: 	    }
 9856: 
 9857:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9858:                 if ($space eq 'visibleparts') {
 9859:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9860:                     my $item;
 9861:                     if (ref($navmap)) {
 9862:                         my $res = $navmap->getBySymb($symbparm);
 9863:                         my $parts = $res->parts();
 9864:                         if (ref($parts) eq 'ARRAY') {
 9865:                             $item = join(',',@{$parts});
 9866:                         }
 9867:                         undef($navmap);
 9868:                     }
 9869:                     return $item;
 9870:                 }
 9871:             }
 9872:         }
 9873: 
 9874: 	my ($section, $group, @groups);
 9875: 	my ($courselevelm,$courselevel);
 9876:         if (($courseid eq '') && ($cid)) {
 9877:             $courseid = $cid;
 9878:         }
 9879: 	if (($symbparm && $courseid) && 
 9880: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9881: 
 9882: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9883: 
 9884: # ----------------------------------------------------- Cascading lookup scheme
 9885: 	    my $symbp=$symbparm;
 9886: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9887: 
 9888: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9889: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9890: 
 9891: 	    if (($env{'user.name'} eq $uname) &&
 9892: 		($env{'user.domain'} eq $udom)) {
 9893: 		$section=$env{'request.course.sec'};
 9894:                 @groups = split(/:/,$env{'request.course.groups'});  
 9895:                 @groups=&sort_course_groups($courseid,@groups); 
 9896: 	    } else {
 9897: 		if (! defined($usection)) {
 9898: 		    $section=&getsection($udom,$uname,$courseid);
 9899: 		} else {
 9900: 		    $section = $usection;
 9901: 		}
 9902:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9903: 	    }
 9904: 
 9905: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9906: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9907: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9908: 
 9909: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9910: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9911: 	    $courselevelm=$courseid.'.'.$mapparm;
 9912: 
 9913: # ----------------------------------------------------------- first, check user
 9914: 
 9915: 	    my $userreply=&resdata($uname,$udom,'user',
 9916: 				       ([$courselevelr,'resource'],
 9917: 					[$courselevelm,'map'     ],
 9918: 					[$courselevel, 'course'  ]));
 9919: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9920: 
 9921: # ------------------------------------------------ second, check some of course
 9922:             my $coursereply;
 9923:             if (@groups > 0) {
 9924:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9925:                                        $mapparm,$spacequalifierrest);
 9926:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9927:             }
 9928: 
 9929: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9930: 				  $env{'course.'.$courseid.'.domain'},
 9931: 				  'course',
 9932: 				  ([$seclevelr,   'resource'],
 9933: 				   [$seclevelm,   'map'     ],
 9934: 				   [$seclevel,    'course'  ],
 9935: 				   [$courselevelr,'resource']));
 9936: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9937: 
 9938: # ------------------------------------------------------ third, check map parms
 9939: 	    my %parmhash=();
 9940: 	    my $thisparm='';
 9941: 	    if (tie(%parmhash,'GDBM_File',
 9942: 		    $env{'request.course.fn'}.'_parms.db',
 9943: 		    &GDBM_READER(),0640)) {
 9944: 		$thisparm=$parmhash{$symbparm};
 9945: 		untie(%parmhash);
 9946: 	    }
 9947: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9948: 	}
 9949: # ------------------------------------------ fourth, look in resource metadata
 9950: 
 9951: 	$spacequalifierrest=~s/\./\_/;
 9952: 	my $filename;
 9953: 	if (!$symbparm) { $symbparm=&symbread(); }
 9954: 	if ($symbparm) {
 9955: 	    $filename=(&decode_symb($symbparm))[2];
 9956: 	} else {
 9957: 	    $filename=$env{'request.filename'};
 9958: 	}
 9959: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9960: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9961: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9962: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9963: 
 9964: # ---------------------------------------------- fourth, look in rest of course
 9965: 	if ($symbparm && defined($courseid) && 
 9966: 	    $courseid eq $env{'request.course.id'}) {
 9967: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9968: 				     $env{'course.'.$courseid.'.domain'},
 9969: 				     'course',
 9970: 				     ([$courselevelm,'map'   ],
 9971: 				      [$courselevel, 'course']));
 9972: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9973: 	}
 9974: # ------------------------------------------------------------------ Cascade up
 9975: 	unless ($space eq '0') {
 9976: 	    my @parts=split(/_/,$space);
 9977: 	    my $id=pop(@parts);
 9978: 	    my $part=join('_',@parts);
 9979: 	    if ($part eq '') { $part='0'; }
 9980: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9981: 				 $symbparm,$udom,$uname,$section,1);
 9982: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9983: 	}
 9984: 	if ($recurse) { return undef; }
 9985: 	my $pack_def=&packages_tab_default($filename,$varname);
 9986: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9987: # ---------------------------------------------------- Any other user namespace
 9988:     } elsif ($realm eq 'environment') {
 9989: # ----------------------------------------------------------------- environment
 9990: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9991: 	    return $env{'environment.'.$spacequalifierrest};
 9992: 	} else {
 9993: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9994: 		return '';
 9995: 	    }
 9996: 	    my %returnhash=&userenvironment($udom,$uname,
 9997: 					    $spacequalifierrest);
 9998: 	    return $returnhash{$spacequalifierrest};
 9999: 	}
10000:     } elsif ($realm eq 'system') {
10001: # ----------------------------------------------------------------- system.time
10002: 	if ($space eq 'time') {
10003: 	    return time;
10004:         }
10005:     } elsif ($realm eq 'server') {
10006: # ----------------------------------------------------------------- system.time
10007: 	if ($space eq 'name') {
10008: 	    return $ENV{'SERVER_NAME'};
10009:         }
10010:     }
10011:     return '';
10012: }
10013: 
10014: sub get_reply {
10015:     my ($reply_value) = @_;
10016:     if (ref($reply_value) eq 'ARRAY') {
10017:         if (wantarray) {
10018: 	    return @$reply_value;
10019:         }
10020:         return $reply_value->[0];
10021:     } else {
10022:         return $reply_value;
10023:     }
10024: }
10025: 
10026: sub check_group_parms {
10027:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10028:     my @groupitems = ();
10029:     my $resultitem;
10030:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10031:     foreach my $group (@{$groups}) {
10032:         foreach my $level (@levels) {
10033:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10034:              push(@groupitems,[$item,$level->[1]]);
10035:         }
10036:     }
10037:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10038:                             $env{'course.'.$courseid.'.domain'},
10039:                                      'course',@groupitems);
10040:     return $coursereply;
10041: }
10042: 
10043: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10044:     my ($courseid,@groups) = @_;
10045:     @groups = sort(@groups);
10046:     return @groups;
10047: }
10048: 
10049: sub packages_tab_default {
10050:     my ($uri,$varname)=@_;
10051:     my (undef,$part,$name)=split(/\./,$varname);
10052: 
10053:     my (@extension,@specifics,$do_default);
10054:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10055: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10056: 	if ($pack_type eq 'default') {
10057: 	    $do_default=1;
10058: 	} elsif ($pack_type eq 'extension') {
10059: 	    push(@extension,[$package,$pack_type,$pack_part]);
10060: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10061: 	    # only look at packages defaults for packages that this id is
10062: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10063: 	}
10064:     }
10065:     # first look for a package that matches the requested part id
10066:     foreach my $package (@specifics) {
10067: 	my (undef,$pack_type,$pack_part)=@{$package};
10068: 	next if ($pack_part ne $part);
10069: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10070: 	    return $packagetab{"$pack_type&$name&default"};
10071: 	}
10072:     }
10073:     # look for any possible matching non extension_ package
10074:     foreach my $package (@specifics) {
10075: 	my (undef,$pack_type,$pack_part)=@{$package};
10076: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10077: 	    return $packagetab{"$pack_type&$name&default"};
10078: 	}
10079: 	if ($pack_type eq 'part') { $pack_part='0'; }
10080: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10081: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10082: 	}
10083:     }
10084:     # look for any posible extension_ match
10085:     foreach my $package (@extension) {
10086: 	my ($package,$pack_type)=@{$package};
10087: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10088: 	    return $packagetab{"$pack_type&$name&default"};
10089: 	}
10090: 	if (defined($packagetab{$package."&$name&default"})) {
10091: 	    return $packagetab{$package."&$name&default"};
10092: 	}
10093:     }
10094:     # look for a global default setting
10095:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10096: 	return $packagetab{"default&$name&default"};
10097:     }
10098:     return undef;
10099: }
10100: 
10101: sub add_prefix_and_part {
10102:     my ($prefix,$part)=@_;
10103:     my $keyroot;
10104:     if (defined($prefix) && $prefix !~ /^__/) {
10105: 	# prefix that has a part already
10106: 	$keyroot=$prefix;
10107:     } elsif (defined($prefix)) {
10108: 	# prefix that is missing a part
10109: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10110:     } else {
10111: 	# no prefix at all
10112: 	if (defined($part)) { $keyroot='_'.$part; }
10113:     }
10114:     return $keyroot;
10115: }
10116: 
10117: # ---------------------------------------------------------------- Get metadata
10118: 
10119: my %metaentry;
10120: my %importedpartids;
10121: sub metadata {
10122:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10123:     $uri=&declutter($uri);
10124:     # if it is a non metadata possible uri return quickly
10125:     if (($uri eq '') || 
10126: 	(($uri =~ m|^/*adm/|) && 
10127: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10128:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10129: 	return undef;
10130:     }
10131:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10132: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10133: 	return undef;
10134:     }
10135:     my $filename=$uri;
10136:     $uri=~s/\.meta$//;
10137: #
10138: # Is the metadata already cached?
10139: # Look at timestamp of caching
10140: # Everything is cached by the main uri, libraries are never directly cached
10141: #
10142:     if (!defined($liburi)) {
10143: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10144: 	if (defined($cached)) { return $result->{':'.$what}; }
10145:     }
10146:     {
10147: # Imported parts would go here
10148:         my %importedids=();
10149:         my @origfileimportpartids=();
10150:         my $importedparts=0;
10151: #
10152: # Is this a recursive call for a library?
10153: #
10154: #	if (! exists($metacache{$uri})) {
10155: #	    $metacache{$uri}={};
10156: #	}
10157: 	my $cachetime = 60*60;
10158:         if ($liburi) {
10159: 	    $liburi=&declutter($liburi);
10160:             $filename=$liburi;
10161:         } else {
10162: 	    &devalidate_cache_new('meta',$uri);
10163: 	    undef(%metaentry);
10164: 	}
10165:         my %metathesekeys=();
10166:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10167: 	my $metastring;
10168: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10169: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10170: 	    $metastring = 
10171: 		&Apache::lonnet::ssi_body($which,
10172: 					  ('grade_target' => 'meta'));
10173: 	    $cachetime = 1; # only want this cached in the child not long term
10174: 	} elsif (($uri !~ m -^(editupload)/-) && 
10175:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10176: 	    my $file=&filelocation('',&clutter($filename));
10177: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10178: 	    $metastring=&getfile($file);
10179: 	}
10180:         my $parser=HTML::LCParser->new(\$metastring);
10181:         my $token;
10182:         undef %metathesekeys;
10183:         while ($token=$parser->get_token) {
10184: 	    if ($token->[0] eq 'S') {
10185: 		if (defined($token->[2]->{'package'})) {
10186: #
10187: # This is a package - get package info
10188: #
10189: 		    my $package=$token->[2]->{'package'};
10190: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10191: 		    if (defined($token->[2]->{'id'})) { 
10192: 			$keyroot.='_'.$token->[2]->{'id'}; 
10193: 		    }
10194: 		    if ($metaentry{':packages'}) {
10195: 			$metaentry{':packages'}.=','.$package.$keyroot;
10196: 		    } else {
10197: 			$metaentry{':packages'}=$package.$keyroot;
10198: 		    }
10199: 		    foreach my $pack_entry (keys(%packagetab)) {
10200: 			my $part=$keyroot;
10201: 			$part=~s/^\_//;
10202: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10203: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10204: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10205: 			    # ignore package.tab specified default values
10206:                             # here &package_tab_default() will fetch those
10207: 			    if ($subp eq 'default') { next; }
10208: 			    my $value=$packagetab{$pack_entry};
10209: 			    my $unikey;
10210: 			    if ($pack =~ /_0$/) {
10211: 				$unikey='parameter_0_'.$name;
10212: 				$part=0;
10213: 			    } else {
10214: 				$unikey='parameter'.$keyroot.'_'.$name;
10215: 			    }
10216: 			    if ($subp eq 'display') {
10217: 				$value.=' [Part: '.$part.']';
10218: 			    }
10219: 			    $metaentry{':'.$unikey.'.part'}=$part;
10220: 			    $metathesekeys{$unikey}=1;
10221: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10222: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10223: 			    }
10224: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10225: 				$metaentry{':'.$unikey}=
10226: 				    $metaentry{':'.$unikey.'.default'};
10227: 			    }
10228: 			}
10229: 		    }
10230: 		} else {
10231: #
10232: # This is not a package - some other kind of start tag
10233: #
10234: 		    my $entry=$token->[1];
10235: 		    my $unikey='';
10236: 
10237: 		    if ($entry eq 'import') {
10238: #
10239: # Importing a library here
10240: #
10241:                         my $location=$parser->get_text('/import');
10242:                         my $dir=$filename;
10243:                         $dir=~s|[^/]*$||;
10244:                         $location=&filelocation($dir,$location);
10245:                        
10246:                         my $importmode=$token->[2]->{'importmode'};
10247:                         if ($importmode eq 'problem') {
10248: # Import as problem/response
10249:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10250:                         } elsif ($importmode eq 'part') {
10251: # Import as part(s)
10252:                            $importedparts=1;
10253: # We need to get the original file and the imported file to get the part order correct
10254: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10255: # Load and inspect original file
10256:                            if ($#origfileimportpartids<0) {
10257:                               undef(%importedpartids);
10258:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10259:                               my $origfile=&getfile($origfilelocation);
10260:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10261:                            }
10262: 
10263: # Load and inspect imported file
10264:                            my $impfile=&getfile($location);
10265:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10266:                            if ($#impfilepartids>=0) {
10267: # This problem had parts
10268:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10269:                            } else {
10270: # Importing by turning a single problem into a problem part
10271: # It gets the import-tags ID as part-ID
10272:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10273:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10274:                            }
10275:                         } else {
10276: # Normal import
10277:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10278:                            if (defined($token->[2]->{'id'})) {
10279:                               $unikey.='_'.$token->[2]->{'id'};
10280:                            }
10281:                         }
10282: 
10283: 			if ($depthcount<20) {
10284: 			    my $metadata = 
10285: 				&metadata($uri,'keys', $location,$unikey,
10286: 					  $depthcount+1);
10287: 			    foreach my $meta (split(',',$metadata)) {
10288: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10289: 				$metathesekeys{$meta}=1;
10290: 			    }
10291: 			
10292:                         }
10293: 		    } else {
10294: #
10295: # Not importing, some other kind of non-package, non-library start tag
10296: # 
10297:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10298:                         if (defined($token->[2]->{'id'})) {
10299:                             $unikey.='_'.$token->[2]->{'id'};
10300:                         }
10301: 			if (defined($token->[2]->{'name'})) { 
10302: 			    $unikey.='_'.$token->[2]->{'name'}; 
10303: 			}
10304: 			$metathesekeys{$unikey}=1;
10305: 			foreach my $param (@{$token->[3]}) {
10306: 			    $metaentry{':'.$unikey.'.'.$param} =
10307: 				$token->[2]->{$param};
10308: 			}
10309: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10310: 			my $default=$metaentry{':'.$unikey.'.default'};
10311: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10312: 		 # only ws inside the tag, and not in default, so use default
10313: 		 # as value
10314: 			    $metaentry{':'.$unikey}=$default;
10315: 			} elsif ( $internaltext =~ /\S/ ) {
10316: 		  # something interesting inside the tag
10317: 			    $metaentry{':'.$unikey}=$internaltext;
10318: 			} else {
10319: 		  # no interesting values, don't set a default
10320: 			}
10321: # end of not-a-package not-a-library import
10322: 		    }
10323: # end of not-a-package start tag
10324: 		}
10325: # the next is the end of "start tag"
10326: 	    }
10327: 	}
10328: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10329: 	$extension = lc($extension);
10330: 	if ($extension eq 'htm') { $extension='html'; }
10331: 
10332: 	foreach my $key (keys(%packagetab)) {
10333: 	    #no specific packages #how's our extension
10334: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10335: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10336: 					 \%metathesekeys);
10337: 	}
10338: 
10339: 	if (!exists($metaentry{':packages'})
10340: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10341: 	    foreach my $key (keys(%packagetab)) {
10342: 		#no specific packages well let's get default then
10343: 		if ($key!~/^default&/) { next; }
10344: 		&metadata_create_package_def($uri,$key,'default',
10345: 					     \%metathesekeys);
10346: 	    }
10347: 	}
10348: # are there custom rights to evaluate
10349: 	if ($metaentry{':copyright'} eq 'custom') {
10350: 
10351:     #
10352:     # Importing a rights file here
10353:     #
10354: 	    unless ($depthcount) {
10355: 		my $location=$metaentry{':customdistributionfile'};
10356: 		my $dir=$filename;
10357: 		$dir=~s|[^/]*$||;
10358: 		$location=&filelocation($dir,$location);
10359: 		my $rights_metadata =
10360: 		    &metadata($uri,'keys',$location,'_rights',
10361: 			      $depthcount+1);
10362: 		foreach my $rights (split(',',$rights_metadata)) {
10363: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10364: 		    $metathesekeys{$rights}=1;
10365: 		}
10366: 	    }
10367: 	}
10368: 	# uniqifiy package listing
10369: 	my %seen;
10370: 	my @uniq_packages =
10371: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10372: 	$metaentry{':packages'} = join(',',@uniq_packages);
10373: 
10374:         if ($importedparts) {
10375: # We had imported parts and need to rebuild partorder
10376:            $metaentry{':partorder'}='';
10377:            $metathesekeys{'partorder'}=1;
10378:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10379:                if ($origfileimportpartids[$index] eq 'part') {
10380: # original part, part of the problem
10381:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10382:                } else {
10383: # we have imported parts at this position
10384:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10385:                }
10386:            }
10387:            $metaentry{':partorder'}=~s/^\,//;
10388:         }
10389: 
10390: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10391: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10392: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10393: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10394: # this is the end of "was not already recently cached
10395:     }
10396:     return $metaentry{':'.$what};
10397: }
10398: 
10399: sub metadata_create_package_def {
10400:     my ($uri,$key,$package,$metathesekeys)=@_;
10401:     my ($pack,$name,$subp)=split(/\&/,$key);
10402:     if ($subp eq 'default') { next; }
10403:     
10404:     if (defined($metaentry{':packages'})) {
10405: 	$metaentry{':packages'}.=','.$package;
10406:     } else {
10407: 	$metaentry{':packages'}=$package;
10408:     }
10409:     my $value=$packagetab{$key};
10410:     my $unikey;
10411:     $unikey='parameter_0_'.$name;
10412:     $metaentry{':'.$unikey.'.part'}=0;
10413:     $$metathesekeys{$unikey}=1;
10414:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10415: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10416:     }
10417:     if (defined($metaentry{':'.$unikey.'.default'})) {
10418: 	$metaentry{':'.$unikey}=
10419: 	    $metaentry{':'.$unikey.'.default'};
10420:     }
10421: }
10422: 
10423: sub metadata_generate_part0 {
10424:     my ($metadata,$metacache,$uri) = @_;
10425:     my %allnames;
10426:     foreach my $metakey (keys(%$metadata)) {
10427: 	if ($metakey=~/^parameter\_(.*)/) {
10428: 	  my $part=$$metacache{':'.$metakey.'.part'};
10429: 	  my $name=$$metacache{':'.$metakey.'.name'};
10430: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10431: 	    $allnames{$name}=$part;
10432: 	  }
10433: 	}
10434:     }
10435:     foreach my $name (keys(%allnames)) {
10436:       $$metadata{"parameter_0_$name"}=1;
10437:       my $key=":parameter_0_$name";
10438:       $$metacache{"$key.part"}='0';
10439:       $$metacache{"$key.name"}=$name;
10440:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10441: 					   $allnames{$name}.'_'.$name.
10442: 					   '.type'};
10443:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10444: 			     '.display'};
10445:       my $expr='[Part: '.$allnames{$name}.']';
10446:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10447:       $$metacache{"$key.display"}=$olddis;
10448:     }
10449: }
10450: 
10451: # ------------------------------------------------------ Devalidate title cache
10452: 
10453: sub devalidate_title_cache {
10454:     my ($url)=@_;
10455:     if (!$env{'request.course.id'}) { return; }
10456:     my $symb=&symbread($url);
10457:     if (!$symb) { return; }
10458:     my $key=$env{'request.course.id'}."\0".$symb;
10459:     &devalidate_cache_new('title',$key);
10460: }
10461: 
10462: # ------------------------------------------------- Get the title of a course
10463: 
10464: sub current_course_title {
10465:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10466: }
10467: # ------------------------------------------------- Get the title of a resource
10468: 
10469: sub gettitle {
10470:     my $urlsymb=shift;
10471:     my $symb=&symbread($urlsymb);
10472:     if ($symb) {
10473: 	my $key=$env{'request.course.id'}."\0".$symb;
10474: 	my ($result,$cached)=&is_cached_new('title',$key);
10475: 	if (defined($cached)) { 
10476: 	    return $result;
10477: 	}
10478: 	my ($map,$resid,$url)=&decode_symb($symb);
10479: 	my $title='';
10480: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10481: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10482: 	} else {
10483: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10484: 		    &GDBM_READER(),0640)) {
10485: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10486: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10487: 		untie(%bighash);
10488: 	    }
10489: 	}
10490: 	$title=~s/\&colon\;/\:/gs;
10491: 	if ($title) {
10492: # Remember both $symb and $title for dynamic metadata
10493:             $accesshash{$symb.'___crstitle'}=$title;
10494:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10495: # Cache this title and then return it
10496: 	    return &do_cache_new('title',$key,$title,600);
10497: 	}
10498: 	$urlsymb=$url;
10499:     }
10500:     my $title=&metadata($urlsymb,'title');
10501:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10502:     return $title;
10503: }
10504: 
10505: sub get_slot {
10506:     my ($which,$cnum,$cdom)=@_;
10507:     if (!$cnum || !$cdom) {
10508: 	(undef,my $courseid)=&whichuser();
10509: 	$cdom=$env{'course.'.$courseid.'.domain'};
10510: 	$cnum=$env{'course.'.$courseid.'.num'};
10511:     }
10512:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10513:     my %slotinfo;
10514:     if (exists($remembered{$key})) {
10515: 	$slotinfo{$which} = $remembered{$key};
10516:     } else {
10517: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10518: 	&Apache::lonhomework::showhash(%slotinfo);
10519: 	my ($tmp)=keys(%slotinfo);
10520: 	if ($tmp=~/^error:/) { return (); }
10521: 	$remembered{$key} = $slotinfo{$which};
10522:     }
10523:     if (ref($slotinfo{$which}) eq 'HASH') {
10524: 	return %{$slotinfo{$which}};
10525:     }
10526:     return $slotinfo{$which};
10527: }
10528: 
10529: sub get_reservable_slots {
10530:     my ($cnum,$cdom,$uname,$udom) = @_;
10531:     my $now = time;
10532:     my $reservable_info;
10533:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10534:     if (exists($remembered{$key})) {
10535:         $reservable_info = $remembered{$key};
10536:     } else {
10537:         my %resv;
10538:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10539:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10540:         $reservable_info = \%resv;
10541:         $remembered{$key} = $reservable_info;
10542:     }
10543:     return $reservable_info;
10544: }
10545: 
10546: sub get_course_slots {
10547:     my ($cnum,$cdom) = @_;
10548:     my $hashid=$cnum.':'.$cdom;
10549:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10550:     if (defined($cached)) {
10551:         if (ref($result) eq 'HASH') {
10552:             return %{$result};
10553:         }
10554:     } else {
10555:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10556:         my ($tmp) = keys(%slots);
10557:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10558:             &do_cache_new('allslots',$hashid,\%slots,600);
10559:             return %slots;
10560:         }
10561:     }
10562:     return;
10563: }
10564: 
10565: sub devalidate_slots_cache {
10566:     my ($cnum,$cdom)=@_;
10567:     my $hashid=$cnum.':'.$cdom;
10568:     &devalidate_cache_new('allslots',$hashid);
10569: }
10570: 
10571: sub get_coursechange {
10572:     my ($cdom,$cnum) = @_;
10573:     if ($cdom eq '' || $cnum eq '') {
10574:         return unless ($env{'request.course.id'});
10575:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10576:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10577:     }
10578:     my $hashid=$cdom.'_'.$cnum;
10579:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10580:     if ((defined($cached)) && ($change ne '')) {
10581:         return $change;
10582:     } else {
10583:         my %crshash;
10584:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10585:         if ($crshash{'internal.contentchange'} eq '') {
10586:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10587:             if ($change eq '') {
10588:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10589:                 $change = $crshash{'internal.created'};
10590:             }
10591:         } else {
10592:             $change = $crshash{'internal.contentchange'};
10593:         }
10594:         my $cachetime = 600;
10595:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10596:     }
10597:     return $change;
10598: }
10599: 
10600: sub devalidate_coursechange_cache {
10601:     my ($cnum,$cdom)=@_;
10602:     my $hashid=$cnum.':'.$cdom;
10603:     &devalidate_cache_new('crschange',$hashid);
10604: }
10605: 
10606: # ------------------------------------------------- Update symbolic store links
10607: 
10608: sub symblist {
10609:     my ($mapname,%newhash)=@_;
10610:     $mapname=&deversion(&declutter($mapname));
10611:     my %hash;
10612:     if (($env{'request.course.fn'}) && (%newhash)) {
10613:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10614:                       &GDBM_WRCREAT(),0640)) {
10615: 	    foreach my $url (keys(%newhash)) {
10616: 		next if ($url eq 'last_known'
10617: 			 && $env{'form.no_update_last_known'});
10618: 		$hash{declutter($url)}=&encode_symb($mapname,
10619: 						    $newhash{$url}->[1],
10620: 						    $newhash{$url}->[0]);
10621:             }
10622:             if (untie(%hash)) {
10623: 		return 'ok';
10624:             }
10625:         }
10626:     }
10627:     return 'error';
10628: }
10629: 
10630: # --------------------------------------------------------------- Verify a symb
10631: 
10632: sub symbverify {
10633:     my ($symb,$thisurl,$encstate)=@_;
10634:     my $thisfn=$thisurl;
10635:     $thisfn=&declutter($thisfn);
10636: # direct jump to resource in page or to a sequence - will construct own symbs
10637:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10638: # check URL part
10639:     my ($map,$resid,$url)=&decode_symb($symb);
10640: 
10641:     unless ($url eq $thisfn) { return 0; }
10642: 
10643:     $symb=&symbclean($symb);
10644:     $thisurl=&deversion($thisurl);
10645:     $thisfn=&deversion($thisfn);
10646: 
10647:     my %bighash;
10648:     my $okay=0;
10649: 
10650:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10651:                             &GDBM_READER(),0640)) {
10652:         my $noclutter;
10653:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10654:             $thisurl =~ s/\?.+$//;
10655:             if ($map =~ m{^uploaded/.+\.page$}) {
10656:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10657:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10658:                 $noclutter = 1;
10659:             }
10660:         }
10661:         my $ids;
10662:         if ($noclutter) {
10663:             $ids=$bighash{'ids_'.$thisurl};
10664:         } else {
10665:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10666:         }
10667:         unless ($ids) {
10668:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10669:             $ids=$bighash{$idkey};
10670:         }
10671:         if ($ids) {
10672: # ------------------------------------------------------------------- Has ID(s)
10673:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10674:                 $symb =~ s/\?.+$//;
10675:             }
10676: 	    foreach my $id (split(/\,/,$ids)) {
10677: 	       my ($mapid,$resid)=split(/\./,$id);
10678:                if (
10679:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10680:    eq $symb) {
10681:                    if (ref($encstate)) {
10682:                        $$encstate = $bighash{'encrypted_'.$id};
10683:                    }
10684: 		   if (($env{'request.role.adv'}) ||
10685: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10686:                        ($thisurl eq '/adm/navmaps')) {
10687: 		       $okay=1;
10688:                        last;
10689: 		   }
10690: 	       }
10691: 	   }
10692:         }
10693: 	untie(%bighash);
10694:     }
10695:     return $okay;
10696: }
10697: 
10698: # --------------------------------------------------------------- Clean-up symb
10699: 
10700: sub symbclean {
10701:     my $symb=shift;
10702:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10703: # remove version from map
10704:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10705: 
10706: # remove version from URL
10707:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10708: 
10709: # remove wrapper
10710: 
10711:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10712:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10713:     return $symb;
10714: }
10715: 
10716: # ---------------------------------------------- Split symb to find map and url
10717: 
10718: sub encode_symb {
10719:     my ($map,$resid,$url)=@_;
10720:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10721: }
10722: 
10723: sub decode_symb {
10724:     my $symb=shift;
10725:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10726:     my ($map,$resid,$url)=split(/___/,$symb);
10727:     return (&fixversion($map),$resid,&fixversion($url));
10728: }
10729: 
10730: sub fixversion {
10731:     my $fn=shift;
10732:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10733:     my %bighash;
10734:     my $uri=&clutter($fn);
10735:     my $key=$env{'request.course.id'}.'_'.$uri;
10736: # is this cached?
10737:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10738:     if (defined($cached)) { return $result; }
10739: # unfortunately not cached, or expired
10740:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10741: 	    &GDBM_READER(),0640)) {
10742:  	if ($bighash{'version_'.$uri}) {
10743:  	    my $version=$bighash{'version_'.$uri};
10744:  	    unless (($version eq 'mostrecent') || 
10745: 		    ($version==&getversion($uri))) {
10746:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10747:  	    }
10748:  	}
10749:  	untie %bighash;
10750:     }
10751:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10752: }
10753: 
10754: sub deversion {
10755:     my $url=shift;
10756:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10757:     return $url;
10758: }
10759: 
10760: # ------------------------------------------------------ Return symb list entry
10761: 
10762: sub symbread {
10763:     my ($thisfn,$donotrecurse)=@_;
10764:     my $cache_str;
10765:     if ($thisfn ne '') {
10766:         $cache_str='request.symbread.cached.'.$thisfn;
10767:         if ($env{$cache_str} ne '') {
10768:             return $env{$cache_str};
10769:         }
10770:     } else {
10771: # no filename provided? try from environment
10772:         if ($env{'request.symb'}) {
10773: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10774: 	}
10775: 	$thisfn=$env{'request.filename'};
10776:     }
10777:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10778: # is that filename actually a symb? Verify, clean, and return
10779:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10780: 	if (&symbverify($thisfn,$1)) {
10781: 	    return $env{$cache_str}=&symbclean($thisfn);
10782: 	}
10783:     }
10784:     $thisfn=declutter($thisfn);
10785:     my %hash;
10786:     my %bighash;
10787:     my $syval='';
10788:     if (($env{'request.course.fn'}) && ($thisfn)) {
10789:         my $targetfn = $thisfn;
10790:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10791:             $targetfn = 'adm/wrapper/'.$thisfn;
10792:         }
10793: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10794: 	    $targetfn=$1;
10795: 	}
10796:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10797:                       &GDBM_READER(),0640)) {
10798: 	    $syval=$hash{$targetfn};
10799:             untie(%hash);
10800:         }
10801: # ---------------------------------------------------------- There was an entry
10802:         if ($syval) {
10803: 	    #unless ($syval=~/\_\d+$/) {
10804: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10805: 		    #&appenv({'request.ambiguous' => $thisfn});
10806: 		    #return $env{$cache_str}='';
10807: 		#}    
10808: 		#$syval.=$1;
10809: 	    #}
10810:         } else {
10811: # ------------------------------------------------------- Was not in symb table
10812:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10813:                             &GDBM_READER(),0640)) {
10814: # ---------------------------------------------- Get ID(s) for current resource
10815:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10816:               unless ($ids) { 
10817:                  $ids=$bighash{'ids_/'.$thisfn};
10818:               }
10819:               unless ($ids) {
10820: # alias?
10821: 		  $ids=$bighash{'mapalias_'.$thisfn};
10822:               }
10823:               if ($ids) {
10824: # ------------------------------------------------------------------- Has ID(s)
10825:                  my @possibilities=split(/\,/,$ids);
10826:                  if ($#possibilities==0) {
10827: # ----------------------------------------------- There is only one possibility
10828: 		     my ($mapid,$resid)=split(/\./,$ids);
10829: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10830: 						    $resid,$thisfn);
10831:                  } elsif (!$donotrecurse) {
10832: # ------------------------------------------ There is more than one possibility
10833:                      my $realpossible=0;
10834:                      foreach my $id (@possibilities) {
10835: 			 my $file=$bighash{'src_'.$id};
10836:                          if (&allowed('bre',$file)) {
10837:          		    my ($mapid,$resid)=split(/\./,$id);
10838:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10839: 				$realpossible++;
10840:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10841: 						    $resid,$thisfn);
10842:                             }
10843: 			 }
10844:                      }
10845: 		     if ($realpossible!=1) { $syval=''; }
10846:                  } else {
10847:                      $syval='';
10848:                  }
10849: 	      }
10850:               untie(%bighash)
10851:            }
10852:         }
10853:         if ($syval) {
10854: 	    return $env{$cache_str}=$syval;
10855:         }
10856:     }
10857:     &appenv({'request.ambiguous' => $thisfn});
10858:     return $env{$cache_str}='';
10859: }
10860: 
10861: # ---------------------------------------------------------- Return random seed
10862: 
10863: sub numval {
10864:     my $txt=shift;
10865:     $txt=~tr/A-J/0-9/;
10866:     $txt=~tr/a-j/0-9/;
10867:     $txt=~tr/K-T/0-9/;
10868:     $txt=~tr/k-t/0-9/;
10869:     $txt=~tr/U-Z/0-5/;
10870:     $txt=~tr/u-z/0-5/;
10871:     $txt=~s/\D//g;
10872:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10873:     return int($txt);
10874: }
10875: 
10876: sub numval2 {
10877:     my $txt=shift;
10878:     $txt=~tr/A-J/0-9/;
10879:     $txt=~tr/a-j/0-9/;
10880:     $txt=~tr/K-T/0-9/;
10881:     $txt=~tr/k-t/0-9/;
10882:     $txt=~tr/U-Z/0-5/;
10883:     $txt=~tr/u-z/0-5/;
10884:     $txt=~s/\D//g;
10885:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10886:     my $total;
10887:     foreach my $val (@txts) { $total+=$val; }
10888:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10889:     return int($total);
10890: }
10891: 
10892: sub numval3 {
10893:     use integer;
10894:     my $txt=shift;
10895:     $txt=~tr/A-J/0-9/;
10896:     $txt=~tr/a-j/0-9/;
10897:     $txt=~tr/K-T/0-9/;
10898:     $txt=~tr/k-t/0-9/;
10899:     $txt=~tr/U-Z/0-5/;
10900:     $txt=~tr/u-z/0-5/;
10901:     $txt=~s/\D//g;
10902:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10903:     my $total;
10904:     foreach my $val (@txts) { $total+=$val; }
10905:     if ($_64bit) { $total=(($total<<32)>>32); }
10906:     return $total;
10907: }
10908: 
10909: sub digest {
10910:     my ($data)=@_;
10911:     my $digest=&Digest::MD5::md5($data);
10912:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10913:     my ($e,$f);
10914:     {
10915:         use integer;
10916:         $e=($a+$b);
10917:         $f=($c+$d);
10918:         if ($_64bit) {
10919:             $e=(($e<<32)>>32);
10920:             $f=(($f<<32)>>32);
10921:         }
10922:     }
10923:     if (wantarray) {
10924: 	return ($e,$f);
10925:     } else {
10926: 	my $g;
10927: 	{
10928: 	    use integer;
10929: 	    $g=($e+$f);
10930: 	    if ($_64bit) {
10931: 		$g=(($g<<32)>>32);
10932: 	    }
10933: 	}
10934: 	return $g;
10935:     }
10936: }
10937: 
10938: sub latest_rnd_algorithm_id {
10939:     return '64bit5';
10940: }
10941: 
10942: sub get_rand_alg {
10943:     my ($courseid)=@_;
10944:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10945:     if ($courseid) {
10946: 	return $env{"course.$courseid.rndseed"};
10947:     }
10948:     return &latest_rnd_algorithm_id();
10949: }
10950: 
10951: sub validCODE {
10952:     my ($CODE)=@_;
10953:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10954:     return 0;
10955: }
10956: 
10957: sub getCODE {
10958:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10959:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10960: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10961: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10962: 	return $Apache::lonhomework::history{'resource.CODE'};
10963:     }
10964:     return undef;
10965: }
10966: #
10967: #  Determines the random seed for a specific context:
10968: #
10969: # parameters:
10970: #   symb      - in course context the symb for the seed.
10971: #   course_id - The course id of the form domain_coursenum.
10972: #   domain    - Domain for the user.
10973: #   course    - Course for the user.
10974: #   cenv      - environment of the course.
10975: #
10976: # NOTE:
10977: #   All parameters are picked out of the environment if missing
10978: #   or not defined.
10979: #   If a symb cannot be determined the current time is used instead.
10980: #
10981: #  For a given well defined symb, courside, domain, username,
10982: #  and course environment, the seed is reproducible.
10983: #
10984: sub rndseed {
10985:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10986:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10987:     if (!defined($symb)) {
10988: 	unless ($symb=$wsymb) { return time; }
10989:     }
10990:     if (!defined $courseid) { 
10991: 	$courseid=$wcourseid; 
10992:     }
10993:     if (!defined $domain) { $domain=$wdomain; }
10994:     if (!defined $username) { $username=$wusername }
10995: 
10996:     my $which;
10997:     if (defined($cenv->{'rndseed'})) {
10998: 	$which = $cenv->{'rndseed'};
10999:     } else {
11000: 	$which =&get_rand_alg($courseid);
11001:     }
11002:     if (defined(&getCODE())) {
11003: 
11004: 	if ($which eq '64bit5') {
11005: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11006: 	} elsif ($which eq '64bit4') {
11007: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11008: 	} else {
11009: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11010: 	}
11011:     } elsif ($which eq '64bit5') {
11012: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11013:     } elsif ($which eq '64bit4') {
11014: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11015:     } elsif ($which eq '64bit3') {
11016: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11017:     } elsif ($which eq '64bit2') {
11018: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11019:     } elsif ($which eq '64bit') {
11020: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11021:     }
11022:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11023: }
11024: 
11025: sub rndseed_32bit {
11026:     my ($symb,$courseid,$domain,$username)=@_;
11027:     {
11028: 	use integer;
11029: 	my $symbchck=unpack("%32C*",$symb) << 27;
11030: 	my $symbseed=numval($symb) << 22;
11031: 	my $namechck=unpack("%32C*",$username) << 17;
11032: 	my $nameseed=numval($username) << 12;
11033: 	my $domainseed=unpack("%32C*",$domain) << 7;
11034: 	my $courseseed=unpack("%32C*",$courseid);
11035: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11036: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11037: 	#&logthis("rndseed :$num:$symb");
11038: 	if ($_64bit) { $num=(($num<<32)>>32); }
11039: 	return $num;
11040:     }
11041: }
11042: 
11043: sub rndseed_64bit {
11044:     my ($symb,$courseid,$domain,$username)=@_;
11045:     {
11046: 	use integer;
11047: 	my $symbchck=unpack("%32S*",$symb) << 21;
11048: 	my $symbseed=numval($symb) << 10;
11049: 	my $namechck=unpack("%32S*",$username);
11050: 	
11051: 	my $nameseed=numval($username) << 21;
11052: 	my $domainseed=unpack("%32S*",$domain) << 10;
11053: 	my $courseseed=unpack("%32S*",$courseid);
11054: 	
11055: 	my $num1=$symbchck+$symbseed+$namechck;
11056: 	my $num2=$nameseed+$domainseed+$courseseed;
11057: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11058: 	#&logthis("rndseed :$num:$symb");
11059: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11060: 	return "$num1,$num2";
11061:     }
11062: }
11063: 
11064: sub rndseed_64bit2 {
11065:     my ($symb,$courseid,$domain,$username)=@_;
11066:     {
11067: 	use integer;
11068: 	# strings need to be an even # of cahracters long, it it is odd the
11069:         # last characters gets thrown away
11070: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11071: 	my $symbseed=numval($symb) << 10;
11072: 	my $namechck=unpack("%32S*",$username.' ');
11073: 	
11074: 	my $nameseed=numval($username) << 21;
11075: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11076: 	my $courseseed=unpack("%32S*",$courseid.' ');
11077: 	
11078: 	my $num1=$symbchck+$symbseed+$namechck;
11079: 	my $num2=$nameseed+$domainseed+$courseseed;
11080: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11081: 	#&logthis("rndseed :$num:$symb");
11082: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11083: 	return "$num1,$num2";
11084:     }
11085: }
11086: 
11087: sub rndseed_64bit3 {
11088:     my ($symb,$courseid,$domain,$username)=@_;
11089:     {
11090: 	use integer;
11091: 	# strings need to be an even # of cahracters long, it it is odd the
11092:         # last characters gets thrown away
11093: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11094: 	my $symbseed=numval2($symb) << 10;
11095: 	my $namechck=unpack("%32S*",$username.' ');
11096: 	
11097: 	my $nameseed=numval2($username) << 21;
11098: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11099: 	my $courseseed=unpack("%32S*",$courseid.' ');
11100: 	
11101: 	my $num1=$symbchck+$symbseed+$namechck;
11102: 	my $num2=$nameseed+$domainseed+$courseseed;
11103: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11104: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11105: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11106: 	
11107: 	return "$num1:$num2";
11108:     }
11109: }
11110: 
11111: sub rndseed_64bit4 {
11112:     my ($symb,$courseid,$domain,$username)=@_;
11113:     {
11114: 	use integer;
11115: 	# strings need to be an even # of cahracters long, it it is odd the
11116:         # last characters gets thrown away
11117: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11118: 	my $symbseed=numval3($symb) << 10;
11119: 	my $namechck=unpack("%32S*",$username.' ');
11120: 	
11121: 	my $nameseed=numval3($username) << 21;
11122: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11123: 	my $courseseed=unpack("%32S*",$courseid.' ');
11124: 	
11125: 	my $num1=$symbchck+$symbseed+$namechck;
11126: 	my $num2=$nameseed+$domainseed+$courseseed;
11127: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11128: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11129: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11130: 	
11131: 	return "$num1:$num2";
11132:     }
11133: }
11134: 
11135: sub rndseed_64bit5 {
11136:     my ($symb,$courseid,$domain,$username)=@_;
11137:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11138:     return "$num1:$num2";
11139: }
11140: 
11141: sub rndseed_CODE_64bit {
11142:     my ($symb,$courseid,$domain,$username)=@_;
11143:     {
11144: 	use integer;
11145: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11146: 	my $symbseed=numval2($symb);
11147: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11148: 	my $CODEseed=numval(&getCODE());
11149: 	my $courseseed=unpack("%32S*",$courseid.' ');
11150: 	my $num1=$symbseed+$CODEchck;
11151: 	my $num2=$CODEseed+$courseseed+$symbchck;
11152: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11153: 	#&logthis("rndseed :$num1:$num2:$symb");
11154: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11155: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11156: 	return "$num1:$num2";
11157:     }
11158: }
11159: 
11160: sub rndseed_CODE_64bit4 {
11161:     my ($symb,$courseid,$domain,$username)=@_;
11162:     {
11163: 	use integer;
11164: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11165: 	my $symbseed=numval3($symb);
11166: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11167: 	my $CODEseed=numval3(&getCODE());
11168: 	my $courseseed=unpack("%32S*",$courseid.' ');
11169: 	my $num1=$symbseed+$CODEchck;
11170: 	my $num2=$CODEseed+$courseseed+$symbchck;
11171: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11172: 	#&logthis("rndseed :$num1:$num2:$symb");
11173: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11174: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11175: 	return "$num1:$num2";
11176:     }
11177: }
11178: 
11179: sub rndseed_CODE_64bit5 {
11180:     my ($symb,$courseid,$domain,$username)=@_;
11181:     my $code = &getCODE();
11182:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11183:     return "$num1:$num2";
11184: }
11185: 
11186: sub setup_random_from_rndseed {
11187:     my ($rndseed)=@_;
11188:     if ($rndseed =~/([,:])/) {
11189: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11190: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11191:     } else {
11192: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11193:     }
11194: }
11195: 
11196: sub latest_receipt_algorithm_id {
11197:     return 'receipt3';
11198: }
11199: 
11200: sub recunique {
11201:     my $fucourseid=shift;
11202:     my $unique;
11203:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11204: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11205: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11206:     } else {
11207: 	$unique=$perlvar{'lonReceipt'};
11208:     }
11209:     return unpack("%32C*",$unique);
11210: }
11211: 
11212: sub recprefix {
11213:     my $fucourseid=shift;
11214:     my $prefix;
11215:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11216: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11217: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11218:     } else {
11219: 	$prefix=$perlvar{'lonHostID'};
11220:     }
11221:     return unpack("%32C*",$prefix);
11222: }
11223: 
11224: sub ireceipt {
11225:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11226: 
11227:     my $return =&recprefix($fucourseid).'-';
11228: 
11229:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11230: 	$env{'request.state'} eq 'construct') {
11231: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11232: 	return $return;
11233:     }
11234: 
11235:     my $cuname=unpack("%32C*",$funame);
11236:     my $cudom=unpack("%32C*",$fudom);
11237:     my $cucourseid=unpack("%32C*",$fucourseid);
11238:     my $cusymb=unpack("%32C*",$fusymb);
11239:     my $cunique=&recunique($fucourseid);
11240:     my $cpart=unpack("%32S*",$part);
11241:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11242: 
11243: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11244: 			       
11245: 	$return.= ($cunique%$cuname+
11246: 		   $cunique%$cudom+
11247: 		   $cusymb%$cuname+
11248: 		   $cusymb%$cudom+
11249: 		   $cucourseid%$cuname+
11250: 		   $cucourseid%$cudom+
11251: 		   $cpart%$cuname+
11252: 		   $cpart%$cudom);
11253:     } else {
11254: 	$return.= ($cunique%$cuname+
11255: 		   $cunique%$cudom+
11256: 		   $cusymb%$cuname+
11257: 		   $cusymb%$cudom+
11258: 		   $cucourseid%$cuname+
11259: 		   $cucourseid%$cudom);
11260:     }
11261:     return $return;
11262: }
11263: 
11264: sub receipt {
11265:     my ($part)=@_;
11266:     my ($symb,$courseid,$domain,$name) = &whichuser();
11267:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11268: }
11269: 
11270: sub whichuser {
11271:     my ($passedsymb)=@_;
11272:     my ($symb,$courseid,$domain,$name,$publicuser);
11273:     if (defined($env{'form.grade_symb'})) {
11274: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11275: 	my $allowed=&allowed('vgr',$tmp_courseid);
11276: 	if (!$allowed &&
11277: 	    exists($env{'request.course.sec'}) &&
11278: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11279: 	    $allowed=&allowed('vgr',$tmp_courseid.
11280: 			      '/'.$env{'request.course.sec'});
11281: 	}
11282: 	if ($allowed) {
11283: 	    ($symb)=&get_env_multiple('form.grade_symb');
11284: 	    $courseid=$tmp_courseid;
11285: 	    ($domain)=&get_env_multiple('form.grade_domain');
11286: 	    ($name)=&get_env_multiple('form.grade_username');
11287: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11288: 	}
11289:     }
11290:     if (!$passedsymb) {
11291: 	$symb=&symbread();
11292:     } else {
11293: 	$symb=$passedsymb;
11294:     }
11295:     $courseid=$env{'request.course.id'};
11296:     $domain=$env{'user.domain'};
11297:     $name=$env{'user.name'};
11298:     if ($name eq 'public' && $domain eq 'public') {
11299: 	if (!defined($env{'form.username'})) {
11300: 	    $env{'form.username'}.=time.rand(10000000);
11301: 	}
11302: 	$name.=$env{'form.username'};
11303:     }
11304:     return ($symb,$courseid,$domain,$name,$publicuser);
11305: 
11306: }
11307: 
11308: # ------------------------------------------------------------ Serves up a file
11309: # returns either the contents of the file or 
11310: # -1 if the file doesn't exist
11311: #
11312: # if the target is a file that was uploaded via DOCS, 
11313: # a check will be made to see if a current copy exists on the local server,
11314: # if it does this will be served, otherwise a copy will be retrieved from
11315: # the home server for the course and stored in /home/httpd/html/userfiles on
11316: # the local server.   
11317: 
11318: sub getfile {
11319:     my ($file) = @_;
11320:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11321:     &repcopy($file);
11322:     return &readfile($file);
11323: }
11324: 
11325: sub repcopy_userfile {
11326:     my ($file)=@_;
11327:     my $londocroot = $perlvar{'lonDocRoot'};
11328:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11329:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11330:     my ($cdom,$cnum,$filename) = 
11331: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11332:     my $uri="/uploaded/$cdom/$cnum/$filename";
11333:     if (-e "$file") {
11334: # we already have a local copy, check it out
11335: 	my @fileinfo = stat($file);
11336: 	my $rtncode;
11337: 	my $info;
11338: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11339: 	if ($lwpresp ne 'ok') {
11340: # there is no such file anymore, even though we had a local copy
11341: 	    if ($rtncode eq '404') {
11342: 		unlink($file);
11343: 	    }
11344: 	    return -1;
11345: 	}
11346: 	if ($info < $fileinfo[9]) {
11347: # nice, the file we have is up-to-date, just say okay
11348: 	    return 'ok';
11349: 	} else {
11350: # the file is outdated, get rid of it
11351: 	    unlink($file);
11352: 	}
11353:     }
11354: # one way or the other, at this point, we don't have the file
11355: # construct the correct path for the file
11356:     my @parts = ($cdom,$cnum); 
11357:     if ($filename =~ m|^(.+)/[^/]+$|) {
11358: 	push @parts, split(/\//,$1);
11359:     }
11360:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11361:     foreach my $part (@parts) {
11362: 	$path .= '/'.$part;
11363: 	if (!-e $path) {
11364: 	    mkdir($path,0770);
11365: 	}
11366:     }
11367: # now the path exists for sure
11368: # get a user agent
11369:     my $ua=new LWP::UserAgent;
11370:     my $transferfile=$file.'.in.transfer';
11371: # FIXME: this should flock
11372:     if (-e $transferfile) { return 'ok'; }
11373:     my $request;
11374:     $uri=~s/^\///;
11375:     my $homeserver = &homeserver($cnum,$cdom);
11376:     my $protocol = $protocol{$homeserver};
11377:     $protocol = 'http' if ($protocol ne 'https');
11378:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11379:     my $response=$ua->request($request,$transferfile);
11380: # did it work?
11381:     if ($response->is_error()) {
11382: 	unlink($transferfile);
11383: 	&logthis("Userfile repcopy failed for $uri");
11384: 	return -1;
11385:     }
11386: # worked, rename the transfer file
11387:     rename($transferfile,$file);
11388:     return 'ok';
11389: }
11390: 
11391: sub tokenwrapper {
11392:     my $uri=shift;
11393:     $uri=~s|^https?\://([^/]+)||;
11394:     $uri=~s|^/||;
11395:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11396:     my $token=$1;
11397:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11398:     if ($udom && $uname && $file) {
11399: 	$file=~s|(\?\.*)*$||;
11400:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11401:         my $homeserver = &homeserver($uname,$udom);
11402:         my $protocol = $protocol{$homeserver};
11403:         $protocol = 'http' if ($protocol ne 'https');
11404:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11405:                (($uri=~/\?/)?'&':'?').'token='.$token.
11406:                                '&tokenissued='.$perlvar{'lonHostID'};
11407:     } else {
11408:         return '/adm/notfound.html';
11409:     }
11410: }
11411: 
11412: # call with reqtype HEAD: get last modification time
11413: # call with reqtype GET: get the file contents
11414: # Do not call this with reqtype GET for large files! It loads everything into memory
11415: #
11416: sub getuploaded {
11417:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11418:     $uri=~s/^\///;
11419:     my $homeserver = &homeserver($cnum,$cdom);
11420:     my $protocol = $protocol{$homeserver};
11421:     $protocol = 'http' if ($protocol ne 'https');
11422:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11423:     my $ua=new LWP::UserAgent;
11424:     my $request=new HTTP::Request($reqtype,$uri);
11425:     my $response=$ua->request($request);
11426:     $$rtncode = $response->code;
11427:     if (! $response->is_success()) {
11428: 	return 'failed';
11429:     }      
11430:     if ($reqtype eq 'HEAD') {
11431: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11432:     } elsif ($reqtype eq 'GET') {
11433: 	$$info = $response->content;
11434:     }
11435:     return 'ok';
11436: }
11437: 
11438: sub readfile {
11439:     my $file = shift;
11440:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11441:     my $fh;
11442:     open($fh,"<$file");
11443:     my $a='';
11444:     while (my $line = <$fh>) { $a .= $line; }
11445:     return $a;
11446: }
11447: 
11448: sub filelocation {
11449:     my ($dir,$file) = @_;
11450:     my $location;
11451:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11452: 
11453:     if ($file =~ m-^/adm/-) {
11454: 	$file=~s-^/adm/wrapper/-/-;
11455: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11456:     }
11457: 
11458:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11459:         $location = $file;
11460:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11461:         my ($udom,$uname,$filename)=
11462:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11463:         my $home=&homeserver($uname,$udom);
11464:         my $is_me=0;
11465:         my @ids=&current_machine_ids();
11466:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11467:         if ($is_me) {
11468:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11469:         } else {
11470:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11471:   	      $udom.'/'.$uname.'/'.$filename;
11472:         }
11473:     } elsif ($file =~ m-^/adm/-) {
11474: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11475:     } else {
11476:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11477:         $file=~s:^/(res|priv)/:/:;
11478:         my $space=$1;
11479:         if ( !( $file =~ m:^/:) ) {
11480:             $location = $dir. '/'.$file;
11481:         } else {
11482:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11483:         }
11484:     }
11485:     $location=~s://+:/:g; # remove duplicate /
11486:     while ($location=~m{/\.\./}) {
11487: 	if ($location =~ m{/[^/]+/\.\./}) {
11488: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11489: 	} else {
11490: 	    $location=~ s{/\.\./}{/}g;
11491: 	}
11492:     } #remove dir/..
11493:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11494:     return $location;
11495: }
11496: 
11497: sub hreflocation {
11498:     my ($dir,$file)=@_;
11499:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11500: 	$file=filelocation($dir,$file);
11501:     } elsif ($file=~m-^/adm/-) {
11502: 	$file=~s-^/adm/wrapper/-/-;
11503: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11504:     }
11505:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11506: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11507:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11508: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11509: 	        {/uploaded/$1/$2/}x;
11510:     }
11511:     if ($file=~ m{^/userfiles/}) {
11512: 	$file =~ s{^/userfiles/}{/uploaded/};
11513:     }
11514:     return $file;
11515: }
11516: 
11517: 
11518: 
11519: 
11520: 
11521: sub current_machine_domains {
11522:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11523: }
11524: 
11525: sub machine_domains {
11526:     my ($hostname) = @_;
11527:     my @domains;
11528:     my %hostname = &all_hostnames();
11529:     while( my($id, $name) = each(%hostname)) {
11530: #	&logthis("-$id-$name-$hostname-");
11531: 	if ($hostname eq $name) {
11532: 	    push(@domains,&host_domain($id));
11533: 	}
11534:     }
11535:     return @domains;
11536: }
11537: 
11538: sub current_machine_ids {
11539:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11540: }
11541: 
11542: sub machine_ids {
11543:     my ($hostname) = @_;
11544:     $hostname ||= &hostname($perlvar{'lonHostID'});
11545:     my @ids;
11546:     my %name_to_host = &all_names();
11547:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11548: 	return @{ $name_to_host{$hostname} };
11549:     }
11550:     return;
11551: }
11552: 
11553: sub additional_machine_domains {
11554:     my @domains;
11555:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11556:     while( my $line = <$fh>) {
11557:         $line =~ s/\s//g;
11558:         push(@domains,$line);
11559:     }
11560:     return @domains;
11561: }
11562: 
11563: sub default_login_domain {
11564:     my $domain = $perlvar{'lonDefDomain'};
11565:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11566:     foreach my $posdom (&current_machine_domains(),
11567:                         &additional_machine_domains()) {
11568:         if (lc($posdom) eq lc($testdomain)) {
11569:             $domain=$posdom;
11570:             last;
11571:         }
11572:     }
11573:     return $domain;
11574: }
11575: 
11576: # ------------------------------------------------------------- Declutters URLs
11577: 
11578: sub declutter {
11579:     my $thisfn=shift;
11580:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11581:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11582:     $thisfn=~s/^\///;
11583:     $thisfn=~s|^adm/wrapper/||;
11584:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11585:     $thisfn=~s/^res\///;
11586:     $thisfn=~s/^priv\///;
11587:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11588:         $thisfn=~s/\?.+$//;
11589:     }
11590:     return $thisfn;
11591: }
11592: 
11593: # ------------------------------------------------------------- Clutter up URLs
11594: 
11595: sub clutter {
11596:     my $thisfn='/'.&declutter(shift);
11597:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11598: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11599:        $thisfn='/res'.$thisfn; 
11600:     }
11601:     if ($thisfn !~m|^/adm|) {
11602: 	if ($thisfn =~ m|^/ext/|) {
11603: 	    $thisfn='/adm/wrapper'.$thisfn;
11604: 	} else {
11605: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11606: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11607: 	    if ($embstyle eq 'ssi'
11608: 		|| ($embstyle eq 'hdn')
11609: 		|| ($embstyle eq 'rat')
11610: 		|| ($embstyle eq 'prv')
11611: 		|| ($embstyle eq 'ign')) {
11612: 		#do nothing with these
11613: 	    } elsif (($embstyle eq 'img') 
11614: 		|| ($embstyle eq 'emb')
11615: 		|| ($embstyle eq 'wrp')) {
11616: 		$thisfn='/adm/wrapper'.$thisfn;
11617: 	    } elsif ($embstyle eq 'unk'
11618: 		     && $thisfn!~/\.(sequence|page)$/) {
11619: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11620: 	    } else {
11621: #		&logthis("Got a blank emb style");
11622: 	    }
11623: 	}
11624:     }
11625:     return $thisfn;
11626: }
11627: 
11628: sub clutter_with_no_wrapper {
11629:     my $uri = &clutter(shift);
11630:     if ($uri =~ m-^/adm/-) {
11631: 	$uri =~ s-^/adm/wrapper/-/-;
11632: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11633:     }
11634:     return $uri;
11635: }
11636: 
11637: sub freeze_escape {
11638:     my ($value)=@_;
11639:     if (ref($value)) {
11640: 	$value=&nfreeze($value);
11641: 	return '__FROZEN__'.&escape($value);
11642:     }
11643:     return &escape($value);
11644: }
11645: 
11646: 
11647: sub thaw_unescape {
11648:     my ($value)=@_;
11649:     if ($value =~ /^__FROZEN__/) {
11650: 	substr($value,0,10,undef);
11651: 	$value=&unescape($value);
11652: 	return &thaw($value);
11653:     }
11654:     return &unescape($value);
11655: }
11656: 
11657: sub correct_line_ends {
11658:     my ($result)=@_;
11659:     $$result =~s/\r\n/\n/mg;
11660:     $$result =~s/\r/\n/mg;
11661: }
11662: # ================================================================ Main Program
11663: 
11664: sub goodbye {
11665:    &logthis("Starting Shut down");
11666: #not converted to using infrastruture and probably shouldn't be
11667:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11668: #converted
11669: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11670:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11671: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11672: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11673: #1.1 only
11674: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11675: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11676: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11677: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11678:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11679:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11680:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11681:    &flushcourselogs();
11682:    &logthis("Shutting down");
11683: }
11684: 
11685: sub get_dns {
11686:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11687:     if (!$ignore_cache) {
11688: 	my ($content,$cached)=
11689: 	    &Apache::lonnet::is_cached_new('dns',$url);
11690: 	if ($cached) {
11691: 	    &$func($content,$hashref);
11692: 	    return;
11693: 	}
11694:     }
11695: 
11696:     my %alldns;
11697:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11698:     foreach my $dns (<$config>) {
11699: 	next if ($dns !~ /^\^(\S*)/x);
11700:         my $line = $1;
11701:         my ($host,$protocol) = split(/:/,$line);
11702:         if ($protocol ne 'https') {
11703:             $protocol = 'http';
11704:         }
11705: 	$alldns{$host} = $protocol;
11706:     }
11707:     while (%alldns) {
11708: 	my ($dns) = keys(%alldns);
11709: 	my $ua=new LWP::UserAgent;
11710:         $ua->timeout(30);
11711: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11712: 	my $response=$ua->request($request);
11713:         delete($alldns{$dns});
11714: 	next if ($response->is_error());
11715: 	my @content = split("\n",$response->content);
11716: 	unless ($nocache) {
11717: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11718: 	}
11719: 	&$func(\@content,$hashref);
11720: 	return;
11721:     }
11722:     close($config);
11723:     my $which = (split('/',$url))[3];
11724:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11725:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11726:     my @content = <$config>;
11727:     &$func(\@content,$hashref);
11728:     return;
11729: }
11730: 
11731: # ------------------------------------------------------Get DNS checksums file
11732: sub parse_dns_checksums_tab {
11733:     my ($lines,$hashref) = @_;
11734:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11735:     my $loncaparev = &get_server_loncaparev($machine_dom);
11736:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11737:     my (%chksum,%revnum);
11738:     if (ref($lines) eq 'ARRAY') {
11739:         chomp(@{$lines});
11740:         my $version = shift(@{$lines});
11741:         if ($version eq $release) {  
11742:             foreach my $line (@{$lines}) {
11743:                 my ($file,$version,$shasum) = split(/,/,$line);
11744:                 $chksum{$file} = $shasum;
11745:                 $revnum{$file} = $version;
11746:             }
11747:             if (ref($hashref) eq 'HASH') {
11748:                 %{$hashref} = (
11749:                                 sums     => \%chksum,
11750:                                 versions => \%revnum,
11751:                               );
11752:             }
11753:         }
11754:     }
11755:     return;
11756: }
11757: 
11758: sub fetch_dns_checksums {
11759:     my %checksums;
11760:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11761:     my $loncaparev = &get_server_loncaparev($machine_dom);
11762:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11763:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11764:              \%checksums);
11765:     return \%checksums;
11766: }
11767: 
11768: # ------------------------------------------------------------ Read domain file
11769: {
11770:     my $loaded;
11771:     my %domain;
11772: 
11773:     sub parse_domain_tab {
11774: 	my ($lines) = @_;
11775: 	foreach my $line (@$lines) {
11776: 	    next if ($line =~ /^(\#|\s*$ )/x);
11777: 
11778: 	    chomp($line);
11779: 	    my ($name,@elements) = split(/:/,$line,9);
11780: 	    my %this_domain;
11781: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11782: 			       'lang_def', 'city', 'longi', 'lati',
11783: 			       'primary') {
11784: 		$this_domain{$field} = shift(@elements);
11785: 	    }
11786: 	    $domain{$name} = \%this_domain;
11787: 	}
11788:     }
11789: 
11790:     sub reset_domain_info {
11791: 	undef($loaded);
11792: 	undef(%domain);
11793:     }
11794: 
11795:     sub load_domain_tab {
11796: 	my ($ignore_cache) = @_;
11797: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11798: 	my $fh;
11799: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11800: 	    my @lines = <$fh>;
11801: 	    &parse_domain_tab(\@lines);
11802: 	}
11803: 	close($fh);
11804: 	$loaded = 1;
11805:     }
11806: 
11807:     sub domain {
11808: 	&load_domain_tab() if (!$loaded);
11809: 
11810: 	my ($name,$what) = @_;
11811: 	return if ( !exists($domain{$name}) );
11812: 
11813: 	if (!$what) {
11814: 	    return $domain{$name}{'description'};
11815: 	}
11816: 	return $domain{$name}{$what};
11817:     }
11818: 
11819:     sub domain_info {
11820:         &load_domain_tab() if (!$loaded);
11821:         return %domain;
11822:     }
11823: 
11824: }
11825: 
11826: 
11827: # ------------------------------------------------------------- Read hosts file
11828: {
11829:     my %hostname;
11830:     my %hostdom;
11831:     my %libserv;
11832:     my $loaded;
11833:     my %name_to_host;
11834:     my %internetdom;
11835:     my %LC_dns_serv;
11836: 
11837:     sub parse_hosts_tab {
11838: 	my ($file) = @_;
11839: 	foreach my $configline (@$file) {
11840: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11841:             chomp($configline);
11842: 	    if ($configline =~ /^\^/) {
11843:                 if ($configline =~ /^\^([\w.\-]+)/) {
11844:                     $LC_dns_serv{$1} = 1;
11845:                 }
11846:                 next;
11847:             }
11848: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11849: 	    $name=~s/\s//g;
11850: 	    if ($id && $domain && $role && $name) {
11851: 		$hostname{$id}=$name;
11852: 		push(@{$name_to_host{$name}}, $id);
11853: 		$hostdom{$id}=$domain;
11854: 		if ($role eq 'library') { $libserv{$id}=$name; }
11855:                 if (defined($protocol)) {
11856:                     if ($protocol eq 'https') {
11857:                         $protocol{$id} = $protocol;
11858:                     } else {
11859:                         $protocol{$id} = 'http'; 
11860:                     }
11861:                 } else {
11862:                     $protocol{$id} = 'http';
11863:                 }
11864:                 if (defined($intdom)) {
11865:                     $internetdom{$id} = $intdom;
11866:                 }
11867: 	    }
11868: 	}
11869:     }
11870:     
11871:     sub reset_hosts_info {
11872: 	&purge_remembered();
11873: 	&reset_domain_info();
11874: 	&reset_hosts_ip_info();
11875: 	undef(%name_to_host);
11876: 	undef(%hostname);
11877: 	undef(%hostdom);
11878: 	undef(%libserv);
11879: 	undef($loaded);
11880:     }
11881: 
11882:     sub load_hosts_tab {
11883: 	my ($ignore_cache) = @_;
11884: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11885: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11886: 	my @config = <$config>;
11887: 	&parse_hosts_tab(\@config);
11888: 	close($config);
11889: 	$loaded=1;
11890:     }
11891: 
11892:     sub hostname {
11893: 	&load_hosts_tab() if (!$loaded);
11894: 
11895: 	my ($lonid) = @_;
11896: 	return $hostname{$lonid};
11897:     }
11898: 
11899:     sub all_hostnames {
11900: 	&load_hosts_tab() if (!$loaded);
11901: 
11902: 	return %hostname;
11903:     }
11904: 
11905:     sub all_names {
11906: 	&load_hosts_tab() if (!$loaded);
11907: 
11908: 	return %name_to_host;
11909:     }
11910: 
11911:     sub all_host_domain {
11912:         &load_hosts_tab() if (!$loaded);
11913:         return %hostdom;
11914:     }
11915: 
11916:     sub is_library {
11917: 	&load_hosts_tab() if (!$loaded);
11918: 
11919: 	return exists($libserv{$_[0]});
11920:     }
11921: 
11922:     sub all_library {
11923: 	&load_hosts_tab() if (!$loaded);
11924: 
11925: 	return %libserv;
11926:     }
11927: 
11928:     sub unique_library {
11929: 	#2x reverse removes all hostnames that appear more than once
11930:         my %unique = reverse &all_library();
11931:         return reverse %unique;
11932:     }
11933: 
11934:     sub get_servers {
11935: 	&load_hosts_tab() if (!$loaded);
11936: 
11937: 	my ($domain,$type) = @_;
11938: 	my %possible_hosts = ($type eq 'library') ? %libserv
11939: 	                                          : %hostname;
11940: 	my %result;
11941: 	if (ref($domain) eq 'ARRAY') {
11942: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11943: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11944: 		    $result{$host} = $hostname;
11945: 		}
11946: 	    }
11947: 	} else {
11948: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11949: 		if ($hostdom{$host} eq $domain) {
11950: 		    $result{$host} = $hostname;
11951: 		}
11952: 	    }
11953: 	}
11954: 	return %result;
11955:     }
11956: 
11957:     sub get_unique_servers {
11958:         my %unique = reverse &get_servers(@_);
11959: 	return reverse %unique;
11960:     }
11961: 
11962:     sub host_domain {
11963: 	&load_hosts_tab() if (!$loaded);
11964: 
11965: 	my ($lonid) = @_;
11966: 	return $hostdom{$lonid};
11967:     }
11968: 
11969:     sub all_domains {
11970: 	&load_hosts_tab() if (!$loaded);
11971: 
11972: 	my %seen;
11973: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11974: 	return @uniq;
11975:     }
11976: 
11977:     sub internet_dom {
11978:         &load_hosts_tab() if (!$loaded);
11979: 
11980:         my ($lonid) = @_;
11981:         return $internetdom{$lonid};
11982:     }
11983: 
11984:     sub is_LC_dns {
11985:         &load_hosts_tab() if (!$loaded);
11986: 
11987:         my ($hostname) = @_;
11988:         return exists($LC_dns_serv{$hostname});
11989:     }
11990: 
11991: }
11992: 
11993: { 
11994:     my %iphost;
11995:     my %name_to_ip;
11996:     my %lonid_to_ip;
11997: 
11998:     sub get_hosts_from_ip {
11999: 	my ($ip) = @_;
12000: 	my %iphosts = &get_iphost();
12001: 	if (ref($iphosts{$ip})) {
12002: 	    return @{$iphosts{$ip}};
12003: 	}
12004: 	return;
12005:     }
12006:     
12007:     sub reset_hosts_ip_info {
12008: 	undef(%iphost);
12009: 	undef(%name_to_ip);
12010: 	undef(%lonid_to_ip);
12011:     }
12012: 
12013:     sub get_host_ip {
12014: 	my ($lonid) = @_;
12015: 	if (exists($lonid_to_ip{$lonid})) {
12016: 	    return $lonid_to_ip{$lonid};
12017: 	}
12018: 	my $name=&hostname($lonid);
12019:    	my $ip = gethostbyname($name);
12020: 	return if (!$ip || length($ip) ne 4);
12021: 	$ip=inet_ntoa($ip);
12022: 	$name_to_ip{$name}   = $ip;
12023: 	$lonid_to_ip{$lonid} = $ip;
12024: 	return $ip;
12025:     }
12026:     
12027:     sub get_iphost {
12028: 	my ($ignore_cache) = @_;
12029: 
12030: 	if (!$ignore_cache) {
12031: 	    if (%iphost) {
12032: 		return %iphost;
12033: 	    }
12034: 	    my ($ip_info,$cached)=
12035: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12036: 	    if ($cached) {
12037: 		%iphost      = %{$ip_info->[0]};
12038: 		%name_to_ip  = %{$ip_info->[1]};
12039: 		%lonid_to_ip = %{$ip_info->[2]};
12040: 		return %iphost;
12041: 	    }
12042: 	}
12043: 
12044: 	# get yesterday's info for fallback
12045: 	my %old_name_to_ip;
12046: 	my ($ip_info,$cached)=
12047: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12048: 	if ($cached) {
12049: 	    %old_name_to_ip = %{$ip_info->[1]};
12050: 	}
12051: 
12052: 	my %name_to_host = &all_names();
12053: 	foreach my $name (keys(%name_to_host)) {
12054: 	    my $ip;
12055: 	    if (!exists($name_to_ip{$name})) {
12056: 		$ip = gethostbyname($name);
12057: 		if (!$ip || length($ip) ne 4) {
12058: 		    if (defined($old_name_to_ip{$name})) {
12059: 			$ip = $old_name_to_ip{$name};
12060: 			&logthis("Can't find $name defaulting to old $ip");
12061: 		    } else {
12062: 			&logthis("Name $name no IP found");
12063: 			next;
12064: 		    }
12065: 		} else {
12066: 		    $ip=inet_ntoa($ip);
12067: 		}
12068: 		$name_to_ip{$name} = $ip;
12069: 	    } else {
12070: 		$ip = $name_to_ip{$name};
12071: 	    }
12072: 	    foreach my $id (@{ $name_to_host{$name} }) {
12073: 		$lonid_to_ip{$id} = $ip;
12074: 	    }
12075: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12076: 	}
12077: 	&do_cache_new('iphost','iphost',
12078: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12079: 		      48*60*60);
12080: 
12081: 	return %iphost;
12082:     }
12083: 
12084:     #
12085:     #  Given a DNS returns the loncapa host name for that DNS 
12086:     # 
12087:     sub host_from_dns {
12088:         my ($dns) = @_;
12089:         my @hosts;
12090:         my $ip;
12091: 
12092:         if (exists($name_to_ip{$dns})) {
12093:             $ip = $name_to_ip{$dns};
12094:         }
12095:         if (!$ip) {
12096:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12097:             if (length($ip) == 4) { 
12098: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12099:             }
12100:         }
12101:         if ($ip) {
12102: 	    @hosts = get_hosts_from_ip($ip);
12103: 	    return $hosts[0];
12104:         }
12105:         return undef;
12106:     }
12107: 
12108:     sub get_internet_names {
12109:         my ($lonid) = @_;
12110:         return if ($lonid eq '');
12111:         my ($idnref,$cached)=
12112:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12113:         if ($cached) {
12114:             return $idnref;
12115:         }
12116:         my $ip = &get_host_ip($lonid);
12117:         my @hosts = &get_hosts_from_ip($ip);
12118:         my %iphost = &get_iphost();
12119:         my (@idns,%seen);
12120:         foreach my $id (@hosts) {
12121:             my $dom = &host_domain($id);
12122:             my $prim_id = &domain($dom,'primary');
12123:             my $prim_ip = &get_host_ip($prim_id);
12124:             next if ($seen{$prim_ip});
12125:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12126:                 foreach my $id (@{$iphost{$prim_ip}}) {
12127:                     my $intdom = &internet_dom($id);
12128:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12129:                         push(@idns,$intdom);
12130:                     }
12131:                 }
12132:             }
12133:             $seen{$prim_ip} = 1;
12134:         }
12135:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12136:     }
12137: 
12138: }
12139: 
12140: sub all_loncaparevs {
12141:     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);
12142: }
12143: 
12144: # ---------------------------------------------------------- Read loncaparev table
12145: {
12146:     sub load_loncaparevs { 
12147:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12148:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12149:                 while (my $configline=<$config>) {
12150:                     chomp($configline);
12151:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12152:                     $loncaparevs{$hostid}=$loncaparev;
12153:                 }
12154:                 close($config);
12155:             }
12156:         }
12157:     }
12158: }
12159: 
12160: # ---------------------------------------------------------- Read serverhostID table
12161: {
12162:     sub load_serverhomeIDs {
12163:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12164:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12165:                 while (my $configline=<$config>) {
12166:                     chomp($configline);
12167:                     my ($name,$id)=split(/:/,$configline);
12168:                     $serverhomeIDs{$name}=$id;
12169:                 }
12170:                 close($config);
12171:             }
12172:         }
12173:     }
12174: }
12175: 
12176: 
12177: BEGIN {
12178: 
12179: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12180:     unless ($readit) {
12181: {
12182:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12183:     %perlvar = (%perlvar,%{$configvars});
12184: }
12185: 
12186: 
12187: # ------------------------------------------------------ Read spare server file
12188: {
12189:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12190: 
12191:     while (my $configline=<$config>) {
12192:        chomp($configline);
12193:        if ($configline) {
12194: 	   my ($host,$type) = split(':',$configline,2);
12195: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12196: 	   push(@{ $spareid{$type} }, $host);
12197:        }
12198:     }
12199:     close($config);
12200: }
12201: # ------------------------------------------------------------ Read permissions
12202: {
12203:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12204: 
12205:     while (my $configline=<$config>) {
12206: 	chomp($configline);
12207: 	if ($configline) {
12208: 	    my ($role,$perm)=split(/ /,$configline);
12209: 	    if ($perm ne '') { $pr{$role}=$perm; }
12210: 	}
12211:     }
12212:     close($config);
12213: }
12214: 
12215: # -------------------------------------------- Read plain texts for permissions
12216: {
12217:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12218: 
12219:     while (my $configline=<$config>) {
12220: 	chomp($configline);
12221: 	if ($configline) {
12222: 	    my ($short,@plain)=split(/:/,$configline);
12223:             %{$prp{$short}} = ();
12224: 	    if (@plain > 0) {
12225:                 $prp{$short}{'std'} = $plain[0];
12226:                 for (my $i=1; $i<@plain; $i++) {
12227:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12228:                 }
12229:             }
12230: 	}
12231:     }
12232:     close($config);
12233: }
12234: 
12235: # ---------------------------------------------------------- Read package table
12236: {
12237:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12238: 
12239:     while (my $configline=<$config>) {
12240: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12241: 	chomp($configline);
12242: 	my ($short,$plain)=split(/:/,$configline);
12243: 	my ($pack,$name)=split(/\&/,$short);
12244: 	if ($plain ne '') {
12245: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12246: 	    $packagetab{$short}=$plain; 
12247: 	}
12248:     }
12249:     close($config);
12250: }
12251: 
12252: # ---------------------------------------------------------- Read loncaparev table
12253: 
12254: &load_loncaparevs();
12255: 
12256: # ---------------------------------------------------------- Read serverhostID table
12257: 
12258: &load_serverhomeIDs();
12259: 
12260: # ---------------------------------------------------------- Read releaseslist XML
12261: {
12262:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12263:     if (-e $file) {
12264:         my $parser = HTML::LCParser->new($file);
12265:         while (my $token = $parser->get_token()) {
12266:             if ($token->[0] eq 'S') {
12267:                 my $item = $token->[1];
12268:                 my $name = $token->[2]{'name'};
12269:                 my $value = $token->[2]{'value'};
12270:                 if ($item ne '' && $name ne '' && $value ne '') {
12271:                     my $release = $parser->get_text();
12272:                     $release =~ s/(^\s*|\s*$ )//gx;
12273:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12274:                 }
12275:             }
12276:         }
12277:     }
12278: }
12279: 
12280: # ---------------------------------------------------------- Read managers table
12281: {
12282:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12283:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12284:             while (my $configline=<$config>) {
12285:                 chomp($configline);
12286:                 next if ($configline =~ /^\#/);
12287:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12288:                     $managerstab{$configline} = 1;
12289:                 }
12290:             }
12291:             close($config);
12292:         }
12293:     }
12294: }
12295: 
12296: # ------------- set up temporary directory
12297: {
12298:     $tmpdir = LONCAPA::tempdir();
12299: 
12300: }
12301: 
12302: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12303: 				'compress_threshold'=> 20_000,
12304:  			        });
12305: 
12306: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12307: $dumpcount=0;
12308: $locknum=0;
12309: 
12310: &logtouch();
12311: &logthis('<font color="yellow">INFO: Read configuration</font>');
12312: $readit=1;
12313:     {
12314: 	use integer;
12315: 	my $test=(2**32)+1;
12316: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12317: 	&logthis(" Detected 64bit platform ($_64bit)");
12318:     }
12319: 
12320:     {
12321:         eval {
12322:             ($apache) =
12323:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12324:         };
12325:         if ($@) {
12326:            $apache = 1.3;
12327:         }
12328:     }
12329: 
12330: }
12331: }
12332: 
12333: 1;
12334: __END__
12335: 
12336: =pod
12337: 
12338: =head1 NAME
12339: 
12340: Apache::lonnet - Subroutines to ask questions about things in the network.
12341: 
12342: =head1 SYNOPSIS
12343: 
12344: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12345: 
12346:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12347: 
12348: Common parameters:
12349: 
12350: =over 4
12351: 
12352: =item *
12353: 
12354: $uname : an internal username (if $cname expecting a course Id specifically)
12355: 
12356: =item *
12357: 
12358: $udom : a domain (if $cdom expecting a course's domain specifically)
12359: 
12360: =item *
12361: 
12362: $symb : a resource instance identifier
12363: 
12364: =item *
12365: 
12366: $namespace : the name of a .db file that contains the data needed or
12367: being set.
12368: 
12369: =back
12370: 
12371: =head1 OVERVIEW
12372: 
12373: lonnet provides subroutines which interact with the
12374: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12375: about classes, users, and resources.
12376: 
12377: For many of these objects you can also use this to store data about
12378: them or modify them in various ways.
12379: 
12380: =head2 Symbs
12381: 
12382: To identify a specific instance of a resource, LON-CAPA uses symbols
12383: or "symbs"X<symb>. These identifiers are built from the URL of the
12384: map, the resource number of the resource in the map, and the URL of
12385: the resource itself. The latter is somewhat redundant, but might help
12386: if maps change.
12387: 
12388: An example is
12389: 
12390:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12391: 
12392: The respective map entry is
12393: 
12394:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12395:   title="Problem 2">
12396:  </resource>
12397: 
12398: Symbs are used by the random number generator, as well as to store and
12399: restore data specific to a certain instance of for example a problem.
12400: 
12401: =head2 Storing And Retrieving Data
12402: 
12403: X<store()>X<cstore()>X<restore()>Three of the most important functions
12404: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12405: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12406: is is the non-critical message twin of cstore. These functions are for
12407: handlers to store a perl hash to a user's permanent data space in an
12408: easy manner, and to retrieve it again on another call. It is expected
12409: that a handler would use this once at the beginning to retrieve data,
12410: and then again once at the end to send only the new data back.
12411: 
12412: The data is stored in the user's data directory on the user's
12413: homeserver under the ID of the course.
12414: 
12415: The hash that is returned by restore will have all of the previous
12416: value for all of the elements of the hash.
12417: 
12418: Example:
12419: 
12420:  #creating a hash
12421:  my %hash;
12422:  $hash{'foo'}='bar';
12423: 
12424:  #storing it
12425:  &Apache::lonnet::cstore(\%hash);
12426: 
12427:  #changing a value
12428:  $hash{'foo'}='notbar';
12429: 
12430:  #adding a new value
12431:  $hash{'bar'}='foo';
12432:  &Apache::lonnet::cstore(\%hash);
12433: 
12434:  #retrieving the hash
12435:  my %history=&Apache::lonnet::restore();
12436: 
12437:  #print the hash
12438:  foreach my $key (sort(keys(%history))) {
12439:    print("\%history{$key} = $history{$key}");
12440:  }
12441: 
12442: Will print out:
12443: 
12444:  %history{1:foo} = bar
12445:  %history{1:keys} = foo:timestamp
12446:  %history{1:timestamp} = 990455579
12447:  %history{2:bar} = foo
12448:  %history{2:foo} = notbar
12449:  %history{2:keys} = foo:bar:timestamp
12450:  %history{2:timestamp} = 990455580
12451:  %history{bar} = foo
12452:  %history{foo} = notbar
12453:  %history{timestamp} = 990455580
12454:  %history{version} = 2
12455: 
12456: Note that the special hash entries C<keys>, C<version> and
12457: C<timestamp> were added to the hash. C<version> will be equal to the
12458: total number of versions of the data that have been stored. The
12459: C<timestamp> attribute will be the UNIX time the hash was
12460: stored. C<keys> is available in every historical section to list which
12461: keys were added or changed at a specific historical revision of a
12462: hash.
12463: 
12464: B<Warning>: do not store the hash that restore returns directly. This
12465: will cause a mess since it will restore the historical keys as if the
12466: were new keys. I.E. 1:foo will become 1:1:foo etc.
12467: 
12468: Calling convention:
12469: 
12470:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12471:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12472: 
12473: For more detailed information, see lonnet specific documentation.
12474: 
12475: =head1 RETURN MESSAGES
12476: 
12477: =over 4
12478: 
12479: =item * B<con_lost>: unable to contact remote host
12480: 
12481: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12482: when the connection is brought back up
12483: 
12484: =item * B<con_failed>: unable to contact remote host and unable to save message
12485: for later delivery
12486: 
12487: =item * B<error:>: an error a occurred, a description of the error follows the :
12488: 
12489: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12490: that was requested
12491: 
12492: =back
12493: 
12494: =head1 PUBLIC SUBROUTINES
12495: 
12496: =head2 Session Environment Functions
12497: 
12498: =over 4
12499: 
12500: =item * 
12501: X<appenv()>
12502: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12503: the user envirnoment file, and will be restored for each access this
12504: user makes during this session, also modifies the %env for the current
12505: process. Optional rolesarrayref - if defined contains a reference to an array
12506: of roles which are exempt from the restriction on modifying user.role entries 
12507: in the user's environment.db and in %env.    
12508: 
12509: =item *
12510: X<delenv()>
12511: B<delenv($delthis,$regexp)>: removes all items from the session
12512: environment file that begin with $delthis. If the 
12513: optional second arg - $regexp - is true, $delthis is treated as a 
12514: regular expression, otherwise \Q$delthis\E is used. 
12515: The values are also deleted from the current processes %env.
12516: 
12517: =item * get_env_multiple($name) 
12518: 
12519: gets $name from the %env hash, it seemlessly handles the cases where multiple
12520: values may be defined and end up as an array ref.
12521: 
12522: returns an array of values
12523: 
12524: =back
12525: 
12526: =head2 User Information
12527: 
12528: =over 4
12529: 
12530: =item *
12531: X<queryauthenticate()>
12532: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12533: authentication scheme
12534: 
12535: =item *
12536: X<authenticate()>
12537: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12538: authenticate user from domain's lib servers (first use the current
12539: one). C<$upass> should be the users password.
12540: $checkdefauth is optional (value is 1 if a check should be made to
12541:    authenticate user using default authentication method, and allow
12542:    account creation if username does not have account in the domain).
12543: $clientcancheckhost is optional (value is 1 if checking whether the
12544:    server can host will occur on the client side in lonauth.pm).   
12545: 
12546: =item *
12547: X<homeserver()>
12548: B<homeserver($uname,$udom)>: find the server which has
12549: the user's directory and files (there must be only one), this caches
12550: the answer, and also caches if there is a borken connection.
12551: 
12552: =item *
12553: X<idget()>
12554: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12555: (IDs are a unique resource in a domain, there must be only 1 ID per
12556: username, and only 1 username per ID in a specific domain) (returns
12557: hash: id=>name,id=>name)
12558: 
12559: =item *
12560: X<idrget()>
12561: B<idrget($udom,@unames)>: find the IDs behind a list of
12562: usernames (returns hash: name=>id,name=>id)
12563: 
12564: =item *
12565: X<idput()>
12566: B<idput($udom,%ids)>: store away a list of names and associated IDs
12567: 
12568: =item *
12569: X<rolesinit()>
12570: B<rolesinit($udom,$username)>: get user privileges.
12571: returns user role, first access and timer interval hashes
12572: 
12573: =item *
12574: X<privileged()>
12575: B<privileged($username,$domain)>: returns a true if user has a
12576: privileged and active role (i.e. su or dc), false otherwise.
12577: 
12578: =item *
12579: X<getsection()>
12580: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12581: course $cname, return section name/number or '' for "not in course"
12582: and '-1' for "no section"
12583: 
12584: =item *
12585: X<userenvironment()>
12586: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12587: passed in @what from the requested user's environment, returns a hash
12588: 
12589: =item * 
12590: X<userlog_query()>
12591: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12592: activity.log file. %filters defines filters applied when parsing the
12593: log file. These can be start or end timestamps, or the type of action
12594: - log to look for Login or Logout events, check for Checkin or
12595: Checkout, role for role selection. The response is in the form
12596: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12597: escaped strings of the action recorded in the activity.log file.
12598: 
12599: =back
12600: 
12601: =head2 User Roles
12602: 
12603: =over 4
12604: 
12605: =item *
12606: 
12607: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12608:  F: full access
12609:  U,I,K: authentication modes (cxx only)
12610:  '': forbidden
12611:  1: user needs to choose course
12612:  2: browse allowed
12613:  A: passphrase authentication needed
12614: 
12615: =item *
12616: 
12617: constructaccess($url,$setpriv) : check for access to construction space URL
12618: 
12619: See if the owner domain and name in the URL match those in the
12620: expected environment.  If so, return three element list
12621: ($ownername,$ownerdomain,$ownerhome).
12622: 
12623: Otherwise return the null string.
12624: 
12625: If second argument 'setpriv' is true, it assigns the privileges,
12626: and returns the same three element list, unless the owner has
12627: blocked "ad hoc" Domain Coordinator access to the Author Space,
12628: in which case the null string is returned.
12629: 
12630: =item *
12631: 
12632: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12633: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12634: and course level
12635: 
12636: =item *
12637: 
12638: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12639: (rolesplain.tab); plain text explanation of a user role term.
12640: $type is Course (default) or Community.
12641: If $forcedefault evaluates to true, text returned will be default 
12642: text for $type. Otherwise, if this is a course, the text returned 
12643: will be a custom name for the role (if defined in the course's 
12644: environment).  If no custom name is defined the default is returned.
12645:    
12646: =item *
12647: 
12648: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12649: All arguments are optional. Returns a hash of a roles, either for
12650: co-author/assistant author roles for a user's Construction Space
12651: (default), or if $context is 'userroles', roles for the user himself,
12652: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12653: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12654: For each key, value is set to colon-separated start and end times for
12655: the role.  If no username and domain are specified, will default to
12656: current user/domain. Types, roles, and roledoms are references to arrays
12657: of role statuses (active, future or previous), roles 
12658: (e.g., cc,in, st etc.) and domains of the roles which can be used
12659: to restrict the list of roles reported. If no array ref is 
12660: provided for types, will default to return only active roles.
12661: 
12662: =item *
12663: 
12664: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12665: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12666: 
12667: Additional optional arguments are: $type (if role checking is to be restricted 
12668: to certain user status types -- previous (expired roles), active (currently
12669: available roles) or future (roles available in the future), and
12670: $hideprivileged -- if true will not report course roles for users who
12671: have active Domain Coordinator role in course's domain or in additional
12672: domains (specified in 'Domains to check for privileged users' in course
12673: environment -- set via:  Course Settings -> Classlists and staff listing).
12674: 
12675: =item *
12676: 
12677: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12678: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12679: $possdomains and $possroles are optional array refs -- to domains to check and
12680: roles to check.  If $possdomains is not specified, a dump will be done of the
12681: users' roles.db to check for a dc or su role in any domain. This can be
12682: time consuming if &privileged is called repeatedly (e.g., when displaying a
12683: classlist), so in such cases, supplying a $possdomains array is preferred, as
12684: this then allows &privileged_by_domain() to be used, which caches the identity
12685: of privileged users, eliminating the need for repeated calls to &dump().
12686: 
12687: =item *
12688: 
12689: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12690: where the outer hash keys are domains specified in the $possdomains array ref,
12691: next inner hash keys are privileged roles specified in the $roles array ref,
12692: and the innermost hash contains key = value pairs for username:domain = end:start
12693: for active or future "privileged" users with that role in that domain. To avoid
12694: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12695: innerhash are cached using priv_$role and $dom as the identifiers.
12696: 
12697: =back
12698: 
12699: =head2 User Modification
12700: 
12701: =over 4
12702: 
12703: =item *
12704: 
12705: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12706: user for the level given by URL.  Optional start and end dates (leave empty
12707: string or zero for "no date")
12708: 
12709: =item *
12710: 
12711: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12712: change a users, password, possible return values are: ok,
12713: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12714: refused
12715: 
12716: =item *
12717: 
12718: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12719: 
12720: =item *
12721: 
12722: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12723:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12724: 
12725: will update user information (firstname,middlename,lastname,generation,
12726: permanentemail), and if forceid is true, student/employee ID also.
12727: A user's institutional affiliation(s) can also be updated.
12728: User information fields will not be overwritten with empty entries 
12729: unless the field is included in the $candelete array reference.
12730: This array is included when a single user is modified via "Manage Users",
12731: or when Autoupdate.pl is run by cron in a domain.
12732: 
12733: =item *
12734: 
12735: modifystudent
12736: 
12737: modify a student's enrollment and identification information.
12738: The course id is resolved based on the current user's environment.  
12739: This means the invoking user must be a course coordinator or otherwise
12740: associated with a course.
12741: 
12742: This call is essentially a wrapper for lonnet::modifyuser and
12743: lonnet::modify_student_enrollment
12744: 
12745: Inputs: 
12746: 
12747: =over 4
12748: 
12749: =item B<$udom> Student's loncapa domain
12750: 
12751: =item B<$uname> Student's loncapa login name
12752: 
12753: =item B<$uid> Student/Employee ID
12754: 
12755: =item B<$umode> Student's authentication mode
12756: 
12757: =item B<$upass> Student's password
12758: 
12759: =item B<$first> Student's first name
12760: 
12761: =item B<$middle> Student's middle name
12762: 
12763: =item B<$last> Student's last name
12764: 
12765: =item B<$gene> Student's generation
12766: 
12767: =item B<$usec> Student's section in course
12768: 
12769: =item B<$end> Unix time of the roles expiration
12770: 
12771: =item B<$start> Unix time of the roles start date
12772: 
12773: =item B<$forceid> If defined, allow $uid to be changed
12774: 
12775: =item B<$desiredhome> server to use as home server for student
12776: 
12777: =item B<$email> Student's permanent e-mail address
12778: 
12779: =item B<$type> Type of enrollment (auto or manual)
12780: 
12781: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12782: 
12783: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12784: 
12785: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12786: 
12787: =item B<$context> role change context (shown in User Management Logs display in a course)
12788: 
12789: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12790: 
12791: =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.
12792: 
12793: =back
12794: 
12795: =item *
12796: 
12797: modify_student_enrollment
12798: 
12799: Change a student's enrollment status in a class.  The environment variable
12800: 'role.request.course' must be defined for this function to proceed.
12801: 
12802: Inputs:
12803: 
12804: =over 4
12805: 
12806: =item $udom, student's domain
12807: 
12808: =item $uname, student's name
12809: 
12810: =item $uid, student's user id
12811: 
12812: =item $first, student's first name
12813: 
12814: =item $middle
12815: 
12816: =item $last
12817: 
12818: =item $gene
12819: 
12820: =item $usec
12821: 
12822: =item $end
12823: 
12824: =item $start
12825: 
12826: =item $type
12827: 
12828: =item $locktype
12829: 
12830: =item $cid
12831: 
12832: =item $selfenroll
12833: 
12834: =item $context
12835: 
12836: =item $credits, number of credits student will earn from this class
12837: 
12838: =back
12839: 
12840: 
12841: =item *
12842: 
12843: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12844: custom role; give a custom role to a user for the level given by URL.  Specify
12845: name and domain of role author, and role name
12846: 
12847: =item *
12848: 
12849: revokerole($udom,$uname,$url,$role) : revoke a role for url
12850: 
12851: =item *
12852: 
12853: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12854: 
12855: =back
12856: 
12857: =head2 Course Infomation
12858: 
12859: =over 4
12860: 
12861: =item *
12862: 
12863: coursedescription($courseid,$options) : returns a hash of information about the
12864: specified course id, including all environment settings for the
12865: course, the description of the course will be in the hash under the
12866: key 'description'
12867: 
12868: $options is an optional parameter that if supplied is a hash reference that controls
12869: what how this function works.  It has the following key/values:
12870: 
12871: =over 4
12872: 
12873: =item freshen_cache
12874: 
12875: If defined, and the environment cache for the course is valid, it is 
12876: returned in the returned hash.
12877: 
12878: =item one_time
12879: 
12880: If defined, the last cache time is set to _now_
12881: 
12882: =item user
12883: 
12884: If defined, the supplied username is used instead of the current user.
12885: 
12886: 
12887: =back
12888: 
12889: =item *
12890: 
12891: resdata($name,$domain,$type,@which) : request for current parameter
12892: setting for a specific $type, where $type is either 'course' or 'user',
12893: @what should be a list of parameters to ask about. This routine caches
12894: answers for 10 minutes.
12895: 
12896: =item *
12897: 
12898: get_courseresdata($courseid, $domain) : dump the entire course resource
12899: data base, returning a hash that is keyed by the resource name and has
12900: values that are the resource value.  I believe that the timestamps and
12901: versions are also returned.
12902: 
12903: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12904: supplemental content area. This routine caches the number of files for 
12905: 10 minutes.
12906: 
12907: =back
12908: 
12909: =head2 Course Modification
12910: 
12911: =over 4
12912: 
12913: =item *
12914: 
12915: writecoursepref($courseid,%prefs) : write preferences (environment
12916: database) for a course
12917: 
12918: =item *
12919: 
12920: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12921: 
12922: =item *
12923: 
12924: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12925: 
12926: =item *
12927: 
12928: is_course($courseid), is_course($cdom, $cnum)
12929: 
12930: Accepts either a combined $courseid (in the form of domain_courseid) or the
12931: two component version $cdom, $cnum. It checks if the specified course exists.
12932: 
12933: Returns:
12934:     undef if the course doesn't exist, otherwise
12935:     in scalar context the combined courseid.
12936:     in list context the two components of the course identifier, domain and 
12937:     courseid.    
12938: 
12939: =back
12940: 
12941: =head2 Resource Subroutines
12942: 
12943: =over 4
12944: 
12945: =item *
12946: 
12947: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12948: 
12949: =item *
12950: 
12951: repcopy($filename) : subscribes to the requested file, and attempts to
12952: replicate from the owning library server, Might return
12953: 'unavailable', 'not_found', 'forbidden', 'ok', or
12954: 'bad_request', also attempts to grab the metadata for the
12955: resource. Expects the local filesystem pathname
12956: (/home/httpd/html/res/....)
12957: 
12958: =back
12959: 
12960: =head2 Resource Information
12961: 
12962: =over 4
12963: 
12964: =item *
12965: 
12966: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12967: and returns the value of a variety of different possible values,
12968: $varname should be a request string, and the other parameters can be
12969: used to specify who and what one is asking about. Ordinarily, $cid 
12970: does not need to be specified, as it is retrived from 
12971: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12972: within lonuserstate::loadmap() when initializing a course, before
12973: $env{'request.course.id'} has been set, so it needs to be provided
12974: in that one case.
12975: 
12976: Possible values for $varname are environment.lastname (or other item
12977: from the envirnment hash), user.name (or someother aspect about the
12978: user), resource.0.maxtries (or some other part and parameter of a
12979: resource)
12980: 
12981: =item *
12982: 
12983: directcondval($number) : get current value of a condition; reads from a state
12984: string
12985: 
12986: =item *
12987: 
12988: condval($condidx) : value of condition index based on state
12989: 
12990: =item *
12991: 
12992: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12993: resource's metadata, $what should be either a specific key, or either
12994: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12995: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12996: 
12997: this function automatically caches all requests
12998: 
12999: =item *
13000: 
13001: metadata_query($query,$custom,$customshow) : make a metadata query against the
13002: network of library servers; returns file handle of where SQL and regex results
13003: will be stored for query
13004: 
13005: =item *
13006: 
13007: symbread($filename) : return symbolic list entry (filename argument optional);
13008: returns the data handle
13009: 
13010: =item *
13011: 
13012: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13013: and is a possible symb for the URL in $thisfn, and if is an encrypted
13014: resource that the user accessed using /enc/ returns a 1 on success, 0
13015: on failure, user must be in a course, as it assumes the existence of
13016: the course initial hash, and uses $env('request.course.id'}.  The third
13017: arg is an optional reference to a scalar.  If this arg is passed in the 
13018: call to symbverify, it will be set to 1 if the symb has been set to be 
13019: encrypted; otherwise it will be null.  
13020: 
13021: =item *
13022: 
13023: symbclean($symb) : removes versions numbers from a symb, returns the
13024: cleaned symb
13025: 
13026: =item *
13027: 
13028: is_on_map($uri) : checks if the $uri is somewhere on the current
13029: course map, user must be in a course for it to work.
13030: 
13031: =item *
13032: 
13033: numval($salt) : return random seed value (addend for rndseed)
13034: 
13035: =item *
13036: 
13037: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13038: a random seed, all arguments are optional, if they aren't sent it uses the
13039: environment to derive them. Note: if symb isn't sent and it can't get one
13040: from &symbread it will use the current time as its return value
13041: 
13042: =item *
13043: 
13044: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13045: unfakeable, receipt
13046: 
13047: =item *
13048: 
13049: receipt() : API to ireceipt working off of env values; given out to users
13050: 
13051: =item *
13052: 
13053: countacc($url) : count the number of accesses to a given URL
13054: 
13055: =item *
13056: 
13057: 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
13058: 
13059: =item *
13060: 
13061: 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)
13062: 
13063: =item *
13064: 
13065: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13066: 
13067: =item *
13068: 
13069: devalidate($symb) : devalidate temporary spreadsheet calculations,
13070: forcing spreadsheet to reevaluate the resource scores next time.
13071: 
13072: =item * 
13073: 
13074: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13075: when viewing in course context.
13076: 
13077:  input: six args -- filename (decluttered), course number, course domain,
13078:                     url, symb (if registered) and group (if this is a 
13079:                     group item -- e.g., bulletin board, group page etc.).
13080: 
13081:  output: array of five scalars --
13082:          $cfile -- url for file editing if editable on current server
13083:          $home -- homeserver of resource (i.e., for author if published,
13084:                                           or course if uploaded.).
13085:          $switchserver --  1 if server switch will be needed.
13086:          $forceedit -- 1 if icon/link should be to go to edit mode 
13087:          $forceview -- 1 if icon/link should be to go to view mode
13088: 
13089: =item *
13090: 
13091: is_course_upload($file,$cnum,$cdom)
13092: 
13093: Used in course context to determine if current file was uploaded to 
13094: the course (i.e., would be found in /userfiles/docs on the course's 
13095: homeserver.
13096: 
13097:   input: 3 args -- filename (decluttered), course number and course domain.
13098:   output: boolean -- 1 if file was uploaded.
13099: 
13100: =back
13101: 
13102: =head2 Storing/Retreiving Data
13103: 
13104: =over 4
13105: 
13106: =item *
13107: 
13108: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13109: for this url; hashref needs to be given and should be a \%hashname; the
13110: remaining args aren't required and if they aren't passed or are '' they will
13111: be derived from the env
13112: 
13113: =item *
13114: 
13115: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13116: uses critical subroutine
13117: 
13118: =item *
13119: 
13120: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13121: all args are optional
13122: 
13123: =item *
13124: 
13125: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13126: dumps the complete (or key matching regexp) namespace into a hash
13127: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13128: normally &store()ed into
13129: 
13130: $range should be either an integer '100' (give me the first 100
13131:                                            matching records)
13132:               or be  two integers sperated by a - with no spaces
13133:                  '30-50' (give me the 30th through the 50th matching
13134:                           records)
13135: 
13136: 
13137: =item *
13138: 
13139: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13140: replaces a &store() version of data with a replacement set of data
13141: for a particular resource in a namespace passed in the $storehash hash 
13142: reference
13143: 
13144: =item *
13145: 
13146: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13147: works very similar to store/cstore, but all data is stored in a
13148: temporary location and can be reset using tmpreset, $storehash should
13149: be a hash reference, returns nothing on success
13150: 
13151: =item *
13152: 
13153: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13154: similar to restore, but all data is stored in a temporary location and
13155: can be reset using tmpreset. Returns a hash of values on success,
13156: error string otherwise.
13157: 
13158: =item *
13159: 
13160: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13161: deltes all keys for $symb form the temporary storage hash.
13162: 
13163: =item *
13164: 
13165: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13166: reference filled in from namesp ($udom and $uname are optional)
13167: 
13168: =item *
13169: 
13170: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13171: namesp ($udom and $uname are optional)
13172: 
13173: =item *
13174: 
13175: dump($namespace,$udom,$uname,$regexp,$range) : 
13176: dumps the complete (or key matching regexp) namespace into a hash
13177: ($udom, $uname, $regexp, $range are optional)
13178: 
13179: $range should be either an integer '100' (give me the first 100
13180:                                            matching records)
13181:               or be  two integers sperated by a - with no spaces
13182:                  '30-50' (give me the 30th through the 50th matching
13183:                           records)
13184: =item *
13185: 
13186: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13187: $store can be a scalar, an array reference, or if the amount to be 
13188: incremented is > 1, a hash reference.
13189: 
13190: ($udom and $uname are optional)
13191: 
13192: =item *
13193: 
13194: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13195: ($udom and $uname are optional)
13196: 
13197: =item *
13198: 
13199: cput($namespace,$storehash,$udom,$uname) : critical put
13200: ($udom and $uname are optional)
13201: 
13202: =item *
13203: 
13204: newput($namespace,$storehash,$udom,$uname) :
13205: 
13206: Attempts to store the items in the $storehash, but only if they don't
13207: currently exist, if this succeeds you can be certain that you have 
13208: successfully created a new key value pair in the $namespace db.
13209: 
13210: 
13211: Args:
13212:  $namespace: name of database to store values to
13213:  $storehash: hashref to store to the db
13214:  $udom: (optional) domain of user containing the db
13215:  $uname: (optional) name of user caontaining the db
13216: 
13217: Returns:
13218:  'ok' -> succeeded in storing all keys of $storehash
13219:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13220:                         least <key> already existed in the db (other
13221:                         requested keys may also already exist)
13222:  'error: <msg>' -> unable to tie the DB or other error occurred
13223:  'con_lost' -> unable to contact request server
13224:  'refused' -> action was not allowed by remote machine
13225: 
13226: 
13227: =item *
13228: 
13229: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13230: reference filled in from namesp (encrypts the return communication)
13231: ($udom and $uname are optional)
13232: 
13233: =item *
13234: 
13235: log($udom,$name,$home,$message) : write to permanent log for user; use
13236: critical subroutine
13237: 
13238: =item *
13239: 
13240: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13241: array reference filled in from namespace found in domain level on either
13242: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13243: 
13244: =item *
13245: 
13246: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13247: domain level either on specified domain server ($uhome) or primary domain 
13248: server ($udom and $uhome are optional)
13249: 
13250: =item * 
13251: 
13252: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13253: for: authentication, language, quotas, timezone, date locale, and portal URL in
13254: the target domain.
13255: 
13256: May also include additional key => value pairs for the following groups:
13257: 
13258: =over
13259: 
13260: =item
13261: disk quotas (MB allocated by default to portfolios and authoring spaces).
13262: 
13263: =over
13264: 
13265: =item defaultquota, authorquota
13266: 
13267: =back
13268: 
13269: =item
13270: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13271: portfolio for users).
13272: 
13273: =over
13274: 
13275: =item
13276: aboutme, blog, webdav, portfolio
13277: 
13278: =back
13279: 
13280: =item
13281: requestcourses: ability to request courses, and how requests are processed.
13282: 
13283: =over
13284: 
13285: =item
13286: official, unofficial, community
13287: 
13288: =back
13289: 
13290: =item
13291: inststatus: types of institutional affiliation, and order in which they are displayed.
13292: 
13293: =over
13294: 
13295: =item
13296: inststatustypes, inststatusorder
13297: 
13298: =back
13299: 
13300: =item
13301: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13302: for course's uploaded content.
13303: 
13304: =over
13305: 
13306: =item
13307: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13308: 
13309: =back
13310: 
13311: =item
13312: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13313: on your servers.
13314: 
13315: =over
13316: 
13317: =item 
13318: remotesessions, hostedsessions
13319: 
13320: =back
13321: 
13322: =back
13323: 
13324: In cases where a domain coordinator has never used the "Set Domain Configuration"
13325: utility to create a configuration.db file on a domain's primary library server 
13326: only the following domain defaults: auth_def, auth_arg_def, lang_def
13327: -- corresponding values are authentication type (internal, krb4, krb5,
13328: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13329: will be available. Values are retrieved from cache (if current), unless the
13330: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13331: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13332: 
13333: Typical usage:
13334: 
13335: %domdefaults = &get_domain_defaults($target_domain);
13336: 
13337: =back
13338: 
13339: =head2 Network Status Functions
13340: 
13341: =over 4
13342: 
13343: =item *
13344: 
13345: dirlist() : return directory list based on URI (first arg).
13346: 
13347: Inputs: 1 required, 5 optional.
13348: 
13349: =over
13350: 
13351: =item 
13352: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13353: 
13354: =item
13355: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13356: 
13357: =item
13358: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13359: 
13360: =item
13361: $getpropath - boolean: 1 if prepend path using &propath(). 
13362: 
13363: =item
13364: $getuserdir - boolean: 1 if prepend path for "userfiles".
13365: 
13366: =item 
13367: $alternateRoot - path to prepend in place of path from $uri.
13368: 
13369: =back
13370: 
13371: Returns: Array of up to two items.
13372: 
13373: =over
13374: 
13375: a reference to an array of files/subdirectories
13376: 
13377: =over
13378: 
13379: Each element in the array of files/subdirectories is a & separated list of
13380: item name and the result of running stat on the item.  If dirlist was requested
13381: for a file instead of a directory, the item name will be ''. For a directory 
13382: listing, if the item is a metadata file, the element will end &N&M 
13383: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13384: default copyright set (1).  
13385: 
13386: =back
13387: 
13388: a scalar containing error condition (if encountered).
13389: 
13390: =over
13391: 
13392: =item 
13393: no_host (no homeserver identified for $username:$domain).
13394: 
13395: =item 
13396: no_such_host (server contacted for listing not identified as valid host).
13397: 
13398: =item 
13399: con_lost (connection to remote server failed).
13400: 
13401: =item 
13402: refused (invalid $username:$domain received on lond side).
13403: 
13404: =item 
13405: no_such_dir (directory at specified path on lond side does not exist). 
13406: 
13407: =item 
13408: empty (directory at specified path on lond side is empty).
13409: 
13410: =over
13411: 
13412: This is currently not encountered because the &ls3, &ls2, 
13413: &ls (_handler) routines on the lond side do not filter out
13414: . and .. from a directory listing. 
13415: 
13416: =back
13417: 
13418: =back
13419: 
13420: =back
13421: 
13422: =item *
13423: 
13424: spareserver() : find server with least workload from spare.tab
13425: 
13426: 
13427: =item *
13428: 
13429: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13430: if there is no corresponding loncapa host.
13431: 
13432: =back
13433: 
13434: 
13435: =head2 Apache Request
13436: 
13437: =over 4
13438: 
13439: =item *
13440: 
13441: ssi($url,%hash) : server side include, does a complete request cycle on url to
13442: localhost, posts hash
13443: 
13444: =back
13445: 
13446: =head2 Data to String to Data
13447: 
13448: =over 4
13449: 
13450: =item *
13451: 
13452: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13453: and '&' separators, supports elements that are arrayrefs and hashrefs
13454: 
13455: =item *
13456: 
13457: hashref2str($hashref) : convert a hashref into a string complete with
13458: escaping and '=' and '&' separators, supports elements that are
13459: arrayrefs and hashrefs
13460: 
13461: =item *
13462: 
13463: arrayref2str($arrayref) : convert an arrayref into a string complete
13464: with escaping and '&' separators, supports elements that are arrayrefs
13465: and hashrefs
13466: 
13467: =item *
13468: 
13469: str2hash($string) : convert string to hash using unescaping and
13470: splitting on '=' and '&', supports elements that are arrayrefs and
13471: hashrefs
13472: 
13473: =item *
13474: 
13475: str2array($string) : convert string to hash using unescaping and
13476: splitting on '&', supports elements that are arrayrefs and hashrefs
13477: 
13478: =back
13479: 
13480: =head2 Logging Routines
13481: 
13482: 
13483: These routines allow one to make log messages in the lonnet.log and
13484: lonnet.perm logfiles.
13485: 
13486: =over 4
13487: 
13488: =item *
13489: 
13490: logtouch() : make sure the logfile, lonnet.log, exists
13491: 
13492: =item *
13493: 
13494: logthis() : append message to the normal lonnet.log file, it gets
13495: preiodically rolled over and deleted.
13496: 
13497: =item *
13498: 
13499: logperm() : append a permanent message to lonnet.perm.log, this log
13500: file never gets deleted by any automated portion of the system, only
13501: messages of critical importance should go in here.
13502: 
13503: 
13504: =back
13505: 
13506: =head2 General File Helper Routines
13507: 
13508: =over 4
13509: 
13510: =item *
13511: 
13512: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13513: (a) files in /uploaded
13514:   (i) If a local copy of the file exists - 
13515:       compares modification date of local copy with last-modified date for 
13516:       definitive version stored on home server for course. If local copy is 
13517:       stale, requests a new version from the home server and stores it. 
13518:       If the original has been removed from the home server, then local copy 
13519:       is unlinked.
13520:   (ii) If local copy does not exist -
13521:       requests the file from the home server and stores it. 
13522:   
13523:   If $caller is 'uploadrep':  
13524:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13525:     for request for files originally uploaded via DOCS. 
13526:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13527:   
13528:   Otherwise:
13529:      This indicates a call from the content generation phase of the request.
13530:      -  returns the entire contents of the file or -1.
13531:      
13532: (b) files in /res
13533:    - returns the entire contents of a file or -1; 
13534:    it properly subscribes to and replicates the file if neccessary.
13535: 
13536: 
13537: =item *
13538: 
13539: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13540:                   reference
13541: 
13542: returns either a stat() list of data about the file or an empty list
13543: if the file doesn't exist or couldn't find out about it (connection
13544: problems or user unknown)
13545: 
13546: =item *
13547: 
13548: filelocation($dir,$file) : returns file system location of a file
13549: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13550: directory that relative $file lookups are to looked in ($dir of /a/dir
13551: and a file of ../bob will become /a/bob)
13552: 
13553: =item *
13554: 
13555: hreflocation($dir,$file) : returns file system location or a URL; same as
13556: filelocation except for hrefs
13557: 
13558: =item *
13559: 
13560: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13561: 
13562: =back
13563: 
13564: =head2 Usererfile file routines (/uploaded*)
13565: 
13566: =over 4
13567: 
13568: =item *
13569: 
13570: userfileupload(): main rotine for putting a file in a user or course's
13571:                   filespace, arguments are,
13572: 
13573:  formname - required - this is the name of the element in $env where the
13574:            filename, and the contents of the file to create/modifed exist
13575:            the filename is in $env{'form.'.$formname.'.filename'} and the
13576:            contents of the file is located in $env{'form.'.$formname}
13577:  context - if coursedoc, store the file in the course of the active role
13578:              of the current user; 
13579:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13580:            if 'canceloverwrite': delete file in tmp/overwrites directory
13581:  subdir - required - subdirectory to put the file in under ../userfiles/
13582:          if undefined, it will be placed in "unknown"
13583: 
13584:  (This routine calls clean_filename() to remove any dangerous
13585:  characters from the filename, and then calls finuserfileupload() to
13586:  complete the transaction)
13587: 
13588:  returns either the url of the uploaded file (/uploaded/....) if successful
13589:  and /adm/notfound.html if unsuccessful
13590: 
13591: =item *
13592: 
13593: clean_filename(): routine for cleaing a filename up for storage in
13594:                  userfile space, argument is:
13595: 
13596:  filename - proposed filename
13597: 
13598: returns: the new clean filename
13599: 
13600: =item *
13601: 
13602: finishuserfileupload(): routine that creates and sends the file to
13603: userspace, probably shouldn't be called directly
13604: 
13605:   docuname: username or courseid of destination for the file
13606:   docudom: domain of user/course of destination for the file
13607:   formname: same as for userfileupload()
13608:   fname: filename (including subdirectories) for the file
13609:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13610:   allfiles: reference to hash used to store objects found by parser
13611:   codebase: reference to hash used for codebases of java objects found by parser
13612:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13613:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13614:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13615:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13616:   context: if 'overwrite', will move the uploaded file from its temporary location to
13617:             userfiles to facilitate overwriting a previously uploaded file with same name.
13618:   mimetype: reference to scalar to accommodate mime type determined
13619:             from File::MMagic if $parser = parse.
13620: 
13621:  returns either the url of the uploaded file (/uploaded/....) if successful
13622:  and /adm/notfound.html if unsuccessful (or an error message if context 
13623:  was 'overwrite').
13624:  
13625: 
13626: =item *
13627: 
13628: renameuserfile(): renames an existing userfile to a new name
13629: 
13630:   Args:
13631:    docuname: username or courseid of destination for the file
13632:    docudom: domain of user/course of destination for the file
13633:    old: current file name (including any subdirs under userfiles)
13634:    new: desired file name (including any subdirs under userfiles)
13635: 
13636: =item *
13637: 
13638: mkdiruserfile(): creates a directory is a userfiles dir
13639: 
13640:   Args:
13641:    docuname: username or courseid of destination for the file
13642:    docudom: domain of user/course of destination for the file
13643:    dir: dir to create (including any subdirs under userfiles)
13644: 
13645: =item *
13646: 
13647: removeuserfile(): removes a file that exists in userfiles
13648: 
13649:   Args:
13650:    docuname: username or courseid of destination for the file
13651:    docudom: domain of user/course of destination for the file
13652:    fname: filname to delete (including any subdirs under userfiles)
13653: 
13654: =item *
13655: 
13656: removeuploadedurl(): convience function for removeuserfile()
13657: 
13658:   Args:
13659:    url:  a full /uploaded/... url to delete
13660: 
13661: =item * 
13662: 
13663: get_portfile_permissions():
13664:   Args:
13665:     domain: domain of user or course contain the portfolio files
13666:     user: name of user or num of course contain the portfolio files
13667:   Returns:
13668:     hashref of a dump of the proper file_permissions.db
13669:    
13670: 
13671: =item * 
13672: 
13673: get_access_controls():
13674: 
13675: Args:
13676:   current_permissions: the hash ref returned from get_portfile_permissions()
13677:   group: (optional) the group you want the files associated with
13678:   file: (optional) the file you want access info on
13679: 
13680: Returns:
13681:     a hash (keys are file names) of hashes containing
13682:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13683:         values are XML containing access control settings (see below) 
13684: 
13685: Internal notes:
13686: 
13687:  access controls are stored in file_permissions.db as key=value pairs.
13688:     key -> path to file/file_name\0uniqueID:scope_end_start
13689:         where scope -> public,guest,course,group,domains or users.
13690:               end -> UNIX time for end of access (0 -> no end date)
13691:               start -> UNIX time for start of access
13692: 
13693:     value -> XML description of access control
13694:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13695:             <start></start>
13696:             <end></end>
13697: 
13698:             <password></password>  for scope type = guest
13699: 
13700:             <domain></domain>     for scope type = course or group
13701:             <number></number>
13702:             <roles id="">
13703:              <role></role>
13704:              <access></access>
13705:              <section></section>
13706:              <group></group>
13707:             </roles>
13708: 
13709:             <dom></dom>         for scope type = domains
13710: 
13711:             <users>             for scope type = users
13712:              <user>
13713:               <uname></uname>
13714:               <udom></udom>
13715:              </user>
13716:             </users>
13717:            </scope> 
13718:               
13719:  Access data is also aggregated for each file in an additional key=value pair:
13720:  key -> path to file/file_name\0accesscontrol 
13721:  value -> reference to hash
13722:           hash contains key = value pairs
13723:           where key = uniqueID:scope_end_start
13724:                 value = UNIX time record was last updated
13725: 
13726:           Used to improve speed of look-ups of access controls for each file.  
13727:  
13728:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13729: 
13730: =item *
13731: 
13732: modify_access_controls():
13733: 
13734: Modifies access controls for a portfolio file
13735: Args
13736: 1. file name
13737: 2. reference to hash of required changes,
13738: 3. domain
13739: 4. username
13740:   where domain,username are the domain of the portfolio owner 
13741:   (either a user or a course) 
13742: 
13743: Returns:
13744: 1. result of additions or updates ('ok' or 'error', with error message). 
13745: 2. result of deletions ('ok' or 'error', with error message).
13746: 3. reference to hash of any new or updated access controls.
13747: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13748:    key = integer (inbound ID)
13749:    value = uniqueID
13750: 
13751: =item *
13752: 
13753: get_timebased_id():
13754: 
13755: Attempts to get a unique timestamp-based suffix for use with items added to a 
13756: course via the Course Editor (e.g., folders, composite pages, 
13757: group bulletin boards).
13758: 
13759: Args: (first three required; six others optional)
13760: 
13761: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13762:    docssequence, or name of group
13763: 
13764: 2. keyid (alphanumeric): name of temporary locking key in hash,
13765:    e.g., num, boardids
13766: 
13767: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13768:    file will be named nohist_namespace.db
13769: 
13770: 4. cdom: domain of course; default is current course domain from %env
13771: 
13772: 5. cnum: course number; default is current course number from %env
13773: 
13774: 6. idtype: set to concat if an additional digit is to be appended to the 
13775:    unix timestamp to form the suffix, if the plain timestamp is already
13776:    in use.  Default is to not do this, but simply increment the unix 
13777:    timestamp by 1 until a unique key is obtained.
13778: 
13779: 7. who: holder of locking key; defaults to user:domain for user.
13780: 
13781: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13782:    retrying); default is 3.
13783: 
13784: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13785: 
13786: Returns:
13787: 
13788: 1. suffix obtained (numeric)
13789: 
13790: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13791: 
13792: 3. error: contains (localized) error message if an error occurred.
13793: 
13794: 
13795: =back
13796: 
13797: =head2 HTTP Helper Routines
13798: 
13799: =over 4
13800: 
13801: =item *
13802: 
13803: escape() : unpack non-word characters into CGI-compatible hex codes
13804: 
13805: =item *
13806: 
13807: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13808: 
13809: =back
13810: 
13811: =head1 PRIVATE SUBROUTINES
13812: 
13813: =head2 Underlying communication routines (Shouldn't call)
13814: 
13815: =over 4
13816: 
13817: =item *
13818: 
13819: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13820: 
13821: =item *
13822: 
13823: reply() : uses subreply to send a message to remote machine, logs all failures
13824: 
13825: =item *
13826: 
13827: critical() : passes a critical message to another server; if cannot
13828: get through then place message in connection buffer directory and
13829: returns con_delayed, if incapable of saving message, returns
13830: con_failed
13831: 
13832: =item *
13833: 
13834: reconlonc() : tries to reconnect lonc client processes.
13835: 
13836: =back
13837: 
13838: =head2 Resource Access Logging
13839: 
13840: =over 4
13841: 
13842: =item *
13843: 
13844: flushcourselogs() : flush (save) buffer logs and access logs
13845: 
13846: =item *
13847: 
13848: courselog($what) : save message for course in hash
13849: 
13850: =item *
13851: 
13852: courseacclog($what) : save message for course using &courselog().  Perform
13853: special processing for specific resource types (problems, exams, quizzes, etc).
13854: 
13855: =item *
13856: 
13857: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13858: as a PerlChildExitHandler
13859: 
13860: =back
13861: 
13862: =head2 Other
13863: 
13864: =over 4
13865: 
13866: =item *
13867: 
13868: symblist($mapname,%newhash) : update symbolic storage links
13869: 
13870: =back
13871: 
13872: =cut
13873: 

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