File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1392: download - view: text, annotated - select for diffs
Wed Dec 5 03:29:11 2018 UTC (5 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Avoid repeated redirects back and forth between balancer and target node
  in corner case.
  - Remove file on balancer with record of node in use when browser lacks
    cookie for the active session on (balanced) node, when log-in page on
    that node is set to redirect.
  - If removal fails, remove the user's session file on the node itself.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1392 2018/12/05 03:29:11 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 HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # 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_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $protocol = $protocol{$lonhost};
  315:                     $protocol = 'http' if ($protocol ne 'https');
  316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  317:                     my $request=new HTTP::Request('GET',$url);
  318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  319:                     unless ($response->is_error()) {
  320:                         my $content = $response->content;
  321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  322:                             $loncaparev = $1;
  323:                         }
  324:                     }
  325:                 } else {
  326:                     $loncaparev = $loncaparevs{$lonhost};
  327:                 }
  328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  329:                 $loncaparev = $1;
  330:             }
  331:         }
  332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  333:     }
  334: }
  335: 
  336: sub get_server_homeID {
  337:     my ($hostname,$ignore_cache,$caller) = @_;
  338:     unless ($ignore_cache) {
  339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  340:         if (defined($cached)) {
  341:             return $serverhomeID;
  342:         }
  343:     }
  344:     my $cachetime = 12*3600;
  345:     my $serverhomeID;
  346:     if ($caller eq 'loncron') { 
  347:         my @machine_ids = &machine_ids($hostname);
  348:         foreach my $id (@machine_ids) {
  349:             my $response = &reply('serverhomeID',$id);
  350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  351:                 $serverhomeID = $response;
  352:                 last;
  353:             }
  354:         }
  355:         if ($serverhomeID eq '') {
  356:             $serverhomeID = $machine_ids[-1];
  357:         }
  358:     } else {
  359:         $serverhomeID = $serverhomeIDs{$hostname};
  360:     }
  361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  362: }
  363: 
  364: sub get_remote_globals {
  365:     my ($lonhost,$whathash,$ignore_cache) = @_;
  366:     my ($result,%returnhash,%whatneeded);
  367:     if (ref($whathash) eq 'HASH') {
  368:         foreach my $what (sort(keys(%{$whathash}))) {
  369:             my $hashid = $lonhost.'-'.$what;
  370:             my ($response,$cached);
  371:             unless ($ignore_cache) {
  372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  373:             }
  374:             if (defined($cached)) {
  375:                 $returnhash{$what} = $response;
  376:             } else {
  377:                 $whatneeded{$what} = 1;
  378:             }
  379:         }
  380:         if (keys(%whatneeded) == 0) {
  381:             $result = 'ok';
  382:         } else {
  383:             my $requested = &freeze_escape(\%whatneeded);
  384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  386:                 ($rep eq 'unknown_cmd')) {
  387:                 $result = $rep;
  388:             } else {
  389:                 $result = 'ok';
  390:                 my @pairs=split(/\&/,$rep);
  391:                 foreach my $item (@pairs) {
  392:                     my ($key,$value)=split(/=/,$item,2);
  393:                     my $what = &unescape($key);
  394:                     my $hashid = $lonhost.'-'.$what;
  395:                     $returnhash{$what}=&thaw_unescape($value);
  396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  397:                 }
  398:             }
  399:         }
  400:     }
  401:     return ($result,\%returnhash);
  402: }
  403: 
  404: sub remote_devalidate_cache {
  405:     my ($lonhost,$cachekeys) = @_;
  406:     my $items;
  407:     return unless (ref($cachekeys) eq 'ARRAY');
  408:     my $cachestr = join('&',@{$cachekeys});
  409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  410:     return $response;
  411: }
  412: 
  413: # -------------------------------------------------- Non-critical communication
  414: sub subreply {
  415:     my ($cmd,$server)=@_;
  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  417:     #
  418:     #  With loncnew process trimming, there's a timing hole between lonc server
  419:     #  process exit and the master server picking up the listen on the AF_UNIX
  420:     #  socket.  In that time interval, a lock file will exist:
  421: 
  422:     my $lockfile=$peerfile.".lock";
  423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  424: 	sleep(0.1);
  425:     }
  426:     # At this point, either a loncnew parent is listening or an old lonc
  427:     # or loncnew child is listening so we can connect or everything's dead.
  428:     #
  429:     #   We'll give the connection a few tries before abandoning it.  If
  430:     #   connection is not possible, we'll con_lost back to the client.
  431:     #   
  432:     my $client;
  433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  435: 				      Type    => SOCK_STREAM,
  436: 				      Timeout => 10);
  437: 	if ($client) {
  438: 	    last;		# Connected!
  439: 	} else {
  440: 	    &create_connection(&hostname($server),$server);
  441: 	}
  442:         sleep(0.1);	# Try again later if failed connection.
  443:     }
  444:     my $answer;
  445:     if ($client) {
  446: 	print $client "sethost:$server:$cmd\n";
  447: 	$answer=<$client>;
  448: 	if (!$answer) { $answer="con_lost"; }
  449: 	chomp($answer);
  450:     } else {
  451: 	$answer = 'con_lost';	# Failed connection.
  452:     }
  453:     return $answer;
  454: }
  455: 
  456: sub reply {
  457:     my ($cmd,$server)=@_;
  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  459:     my $answer=subreply($cmd,$server);
  460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  461:        &logthis("<font color=\"blue\">WARNING:".
  462:                 " $cmd to $server returned $answer</font>");
  463:     }
  464:     return $answer;
  465: }
  466: 
  467: # ----------------------------------------------------------- Send USR1 to lonc
  468: 
  469: sub reconlonc {
  470:     my ($lonid) = @_;
  471:     if ($lonid) {
  472:         my $hostname = &hostname($lonid);
  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  474: 	if ($hostname && -e $peerfile) {
  475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  477: 					     Type    => SOCK_STREAM,
  478: 					     Timeout => 10);
  479: 	    if ($client) {
  480: 		print $client ("reset_retries\n");
  481: 		my $answer=<$client>;
  482: 		#reset just this one.
  483: 	    }
  484: 	}
  485: 	return;
  486:     }
  487: 
  488:     &logthis("Trying to reconnect lonc");
  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  490:     if (open(my $fh,"<",$loncfile)) {
  491: 	my $loncpid=<$fh>;
  492:         chomp($loncpid);
  493:         if (kill 0 => $loncpid) {
  494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  495:             kill USR1 => $loncpid;
  496:             sleep 1;
  497:         } else {
  498: 	    &logthis(
  499:                "<font color=\"blue\">WARNING:".
  500:                " lonc at pid $loncpid not responding, giving up</font>");
  501:         }
  502:     } else {
  503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  504:     }
  505: }
  506: 
  507: # ------------------------------------------------------ Critical communication
  508: 
  509: sub critical {
  510:     my ($cmd,$server)=@_;
  511:     unless (&hostname($server)) {
  512:         &logthis("<font color=\"blue\">WARNING:".
  513:                " Critical message to unknown server ($server)</font>");
  514:         return 'no_such_host';
  515:     }
  516:     my $answer=reply($cmd,$server);
  517:     if ($answer eq 'con_lost') {
  518: 	&reconlonc($server);
  519: 	my $answer=reply($cmd,$server);
  520:         if ($answer eq 'con_lost') {
  521:             my $now=time;
  522:             my $middlename=$cmd;
  523:             $middlename=substr($middlename,0,16);
  524:             $middlename=~s/\W//g;
  525:             my $dfilename=
  526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  527:             $dumpcount++;
  528:             {
  529: 		my $dfh;
  530: 		if (open($dfh,">",$dfilename)) {
  531: 		    print $dfh "$cmd\n"; 
  532: 		    close($dfh);
  533: 		}
  534:             }
  535:             sleep 1;
  536:             my $wcmd='';
  537:             {
  538: 		my $dfh;
  539: 		if (open($dfh,"<",$dfilename)) {
  540: 		    $wcmd=<$dfh>; 
  541: 		    close($dfh);
  542: 		}
  543:             }
  544:             chomp($wcmd);
  545:             if ($wcmd eq $cmd) {
  546: 		&logthis("<font color=\"blue\">WARNING: ".
  547:                          "Connection buffer $dfilename: $cmd</font>");
  548:                 &logperm("D:$server:$cmd");
  549: 	        return 'con_delayed';
  550:             } else {
  551:                 &logthis("<font color=\"red\">CRITICAL:"
  552:                         ." Critical connection failed: $server $cmd</font>");
  553:                 &logperm("F:$server:$cmd");
  554:                 return 'con_failed';
  555:             }
  556:         }
  557:     }
  558:     return $answer;
  559: }
  560: 
  561: # ------------------------------------------- check if return value is an error
  562: 
  563: sub error {
  564:     my ($result) = @_;
  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  566: 	if ($2 == 2) { return undef; }
  567: 	return $1;
  568:     }
  569:     return undef;
  570: }
  571: 
  572: sub convert_and_load_session_env {
  573:     my ($lonidsdir,$handle)=@_;
  574:     my @profile;
  575:     {
  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  577: 	if (!$opened) {
  578: 	    return 0;
  579: 	}
  580: 	flock($idf,LOCK_SH);
  581: 	@profile=<$idf>;
  582: 	close($idf);
  583:     }
  584:     my %temp_env;
  585:     foreach my $line (@profile) {
  586: 	if ($line !~ m/=/) {
  587: 	    return 0;
  588: 	}
  589: 	chomp($line);
  590: 	my ($envname,$envvalue)=split(/=/,$line,2);
  591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  592:     }
  593:     unlink("$lonidsdir/$handle.id");
  594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  595: 	    0640)) {
  596: 	%disk_env = %temp_env;
  597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  598: 	untie(%disk_env);
  599:     }
  600:     return 1;
  601: }
  602: 
  603: # ------------------------------------------- Transfer profile into environment
  604: my $env_loaded;
  605: sub transfer_profile_to_env {
  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
  607:     if (!$force_transfer && $env_loaded) { return; } 
  608: 
  609:     if (!defined($lonidsdir)) {
  610: 	$lonidsdir = $perlvar{'lonIDsDir'};
  611:     }
  612:     if (!defined($handle)) {
  613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  614:     }
  615: 
  616:     my $convert;
  617:     {
  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  619: 	if (!$opened) {
  620: 	    return;
  621: 	}
  622: 	flock($idf,LOCK_SH);
  623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  624: 		&GDBM_READER(),0640)) {
  625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  626: 	    untie(%disk_env);
  627: 	} else {
  628: 	    $convert = 1;
  629: 	}
  630:     }
  631:     if ($convert) {
  632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  633: 	    &logthis("Failed to load session, or convert session.");
  634: 	}
  635:     }
  636: 
  637:     my %remove;
  638:     while ( my $envname = each(%env) ) {
  639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  640:             if ($time < time-300) {
  641:                 $remove{$key}++;
  642:             }
  643:         }
  644:     }
  645: 
  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  647:     $env_loaded=1;
  648:     foreach my $expired_key (keys(%remove)) {
  649:         &delenv($expired_key);
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------- Check for valid session 
  654: sub check_for_valid_session {
  655:     my ($r,$name,$userhashref,$domref) = @_;
  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  658:     if ($name eq 'lonDAV') {
  659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  660:     } else {
  661:         $lonidsdir=$r->dir_config('lonIDsDir');
  662:         if ($name eq '') {
  663:             $name = 'lonID';
  664:         }
  665:     }
  666:     if ($name eq 'lonID') {
  667:         $secure = 'lonSID';
  668:         $linkname = 'lonLinkID';
  669:         $pubname = 'lonPubID';
  670:         if (exists($cookies{$secure})) {
  671:             $lonid=$cookies{$secure};
  672:         } elsif (exists($cookies{$name})) {
  673:             $lonid=$cookies{$name};
  674:         } elsif (exists($cookies{$linkname})) {
  675:             $lonid=$cookies{$linkname};
  676:         } elsif (exists($cookies{$pubname})) {
  677:             $lonid=$cookies{$pubname};
  678:         }
  679:     } else {
  680:         $lonid=$cookies{$name};
  681:     }
  682:     return undef if (!$lonid);
  683: 
  684:     my $handle=&LONCAPA::clean_handle($lonid->value);
  685:     if (-l "$lonidsdir/$handle.id") {
  686:         my $link = readlink("$lonidsdir/$handle.id");
  687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  688:             $handle = $1;
  689:         }
  690:     }
  691:     if (!-e "$lonidsdir/$handle.id") {
  692:         if ((ref($domref)) && ($name eq 'lonID') && 
  693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  696:                 $$domref = $possudom;
  697:             }
  698:         }
  699:         return undef;
  700:     }
  701: 
  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  703:     return undef if (!$opened);
  704: 
  705:     flock($idf,LOCK_SH);
  706:     my %disk_env;
  707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  708: 	    &GDBM_READER(),0640)) {
  709: 	return undef;	
  710:     }
  711: 
  712:     if (!defined($disk_env{'user.name'})
  713: 	|| !defined($disk_env{'user.domain'})) {
  714: 	return undef;
  715:     }
  716: 
  717:     if (ref($userhashref) eq 'HASH') {
  718:         $userhashref->{'name'} = $disk_env{'user.name'};
  719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  721:         if ($userhashref->{'lti'}) {
  722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  724:         }
  725:     }
  726: 
  727:     return $handle;
  728: }
  729: 
  730: sub timed_flock {
  731:     my ($file,$lock_type) = @_;
  732:     my $failed=0;
  733:     eval {
  734: 	local $SIG{__DIE__}='DEFAULT';
  735: 	local $SIG{ALRM}=sub {
  736: 	    $failed=1;
  737: 	    die("failed lock");
  738: 	};
  739: 	alarm(13);
  740: 	flock($file,$lock_type);
  741: 	alarm(0);
  742:     };
  743:     if ($failed) {
  744: 	return undef;
  745:     } else {
  746: 	return 1;
  747:     }
  748: }
  749: 
  750: sub get_sessionfile_vars {
  751:     my ($handle,$lonidsdir,$storearr) = @_;
  752:     my %returnhash;
  753:     unless (ref($storearr) eq 'ARRAY') {
  754:         return %returnhash;
  755:     }
  756:     if (-l "$lonidsdir/$handle.id") {
  757:         my $link = readlink("$lonidsdir/$handle.id");
  758:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  759:             $handle = $1;
  760:         }
  761:     }
  762:     if ((-e "$lonidsdir/$handle.id") &&
  763:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  764:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  765:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  766:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  767:                 flock($idf,LOCK_SH);
  768:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  769:                         &GDBM_READER(),0640)) {
  770:                     foreach my $item (@{$storearr}) {
  771:                         $returnhash{$item} = $disk_env{$item};
  772:                     }
  773:                     untie(%disk_env);
  774:                 }
  775:             }
  776:         }
  777:     }
  778:     return %returnhash;
  779: }
  780: 
  781: # ---------------------------------------------------------- Append Environment
  782: 
  783: sub appenv {
  784:     my ($newenv,$roles) = @_;
  785:     if (ref($newenv) eq 'HASH') {
  786:         foreach my $key (keys(%{$newenv})) {
  787:             my $refused = 0;
  788: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  789:                 $refused = 1;
  790:                 if (ref($roles) eq 'ARRAY') {
  791:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  792:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  793:                         $refused = 0;
  794:                     }
  795:                 }
  796:             }
  797:             if ($refused) {
  798:                 &logthis("<font color=\"blue\">WARNING: ".
  799:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  800:                          .'</font>');
  801: 	        delete($newenv->{$key});
  802:             } else {
  803:                 $env{$key}=$newenv->{$key};
  804:             }
  805:         }
  806:         my $lonids = $perlvar{'lonIDsDir'};
  807:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  808:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  809:             if ($opened
  810: 	        && &timed_flock($env_file,LOCK_EX)
  811: 	        &&
  812: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  813: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  814: 	        while (my ($key,$value) = each(%{$newenv})) {
  815: 	            $disk_env{$key} = $value;
  816: 	        }
  817: 	        untie(%disk_env);
  818:             }
  819:         }
  820:     }
  821:     return 'ok';
  822: }
  823: # ----------------------------------------------------- Delete from Environment
  824: 
  825: sub delenv {
  826:     my ($delthis,$regexp,$roles) = @_;
  827:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  828:         my $refused = 1;
  829:         if (ref($roles) eq 'ARRAY') {
  830:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  831:             if (grep(/^\Q$role\E$/,@{$roles})) {
  832:                 $refused = 0;
  833:             }
  834:         }
  835:         if ($refused) {
  836:             &logthis("<font color=\"blue\">WARNING: ".
  837:                      "Attempt to delete from environment ".$delthis);
  838:             return 'error';
  839:         }
  840:     }
  841:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  842:     if ($opened
  843: 	&& &timed_flock($env_file,LOCK_EX)
  844: 	&&
  845: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  846: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  847: 	foreach my $key (keys(%disk_env)) {
  848: 	    if ($regexp) {
  849:                 if ($key=~/^$delthis/) {
  850:                     delete($env{$key});
  851:                     delete($disk_env{$key});
  852:                 } 
  853:             } else {
  854:                 if ($key=~/^\Q$delthis\E/) {
  855: 		    delete($env{$key});
  856: 		    delete($disk_env{$key});
  857: 	        }
  858:             }
  859: 	}
  860: 	untie(%disk_env);
  861:     }
  862:     return 'ok';
  863: }
  864: 
  865: sub get_env_multiple {
  866:     my ($name) = @_;
  867:     my @values;
  868:     if (defined($env{$name})) {
  869:         # exists is it an array
  870:         if (ref($env{$name})) {
  871:             @values=@{ $env{$name} };
  872:         } else {
  873:             $values[0]=$env{$name};
  874:         }
  875:     }
  876:     return(@values);
  877: }
  878: 
  879: # ------------------------------------------------------------------- Locking
  880: 
  881: sub set_lock {
  882:     my ($text)=@_;
  883:     $locknum++;
  884:     my $id=$$.'-'.$locknum;
  885:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  886:              'session.lock.'.$id => $text});
  887:     return $id;
  888: }
  889: 
  890: sub get_locks {
  891:     my $num=0;
  892:     my %texts=();
  893:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  894:        if ($lock=~/\w/) {
  895:           $num++;
  896:           $texts{$lock}=$env{'session.lock.'.$lock};
  897:        }
  898:    }
  899:    return ($num,%texts);
  900: }
  901: 
  902: sub remove_lock {
  903:     my ($id)=@_;
  904:     my $newlocks='';
  905:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  906:        if (($lock=~/\w/) && ($lock ne $id)) {
  907:           $newlocks.=','.$lock;
  908:        }
  909:     }
  910:     &appenv({'session.locks' => $newlocks});
  911:     &delenv('session.lock.'.$id);
  912: }
  913: 
  914: sub remove_all_locks {
  915:     my $activelocks=$env{'session.locks'};
  916:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  917:        if ($lock=~/\w/) {
  918:           &remove_lock($lock);
  919:        }
  920:     }
  921: }
  922: 
  923: 
  924: # ------------------------------------------ Find out current server userload
  925: sub userload {
  926:     my $numusers=0;
  927:     {
  928: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  929: 	my $filename;
  930: 	my $curtime=time;
  931: 	while ($filename=readdir(LONIDS)) {
  932: 	    next if ($filename eq '.' || $filename eq '..');
  933: 	    next if ($filename =~ /publicuser_\d+\.id/);
  934:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  935: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  936: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  937: 	}
  938: 	closedir(LONIDS);
  939:     }
  940:     my $userloadpercent=0;
  941:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  942:     if ($maxuserload) {
  943: 	$userloadpercent=100*$numusers/$maxuserload;
  944:     }
  945:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  946:     return $userloadpercent;
  947: }
  948: 
  949: # ------------------------------ Find server with least workload from spare.tab
  950: 
  951: sub spareserver {
  952:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  953:     my $spare_server;
  954:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  955:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  956:                                                      :  $userloadpercent;
  957:     my ($uint_dom,$remotesessions);
  958:     if (($udom ne '') && (&domain($udom) ne '')) {
  959:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  960:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  961:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  962:         $remotesessions = $udomdefaults{'remotesessions'};
  963:     }
  964:     my $spareshash = &this_host_spares($udom);
  965:     if (ref($spareshash) eq 'HASH') {
  966:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  967:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  968:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  969:                                              $try_server));
  970: 	        ($spare_server, $lowest_load) =
  971: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  972:             }
  973:         }
  974: 
  975:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  976: 
  977:         if (!$found_server) {
  978:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  979: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  980:                     next unless (&spare_can_host($udom,$uint_dom,
  981:                                                  $remotesessions,$try_server));
  982: 	            ($spare_server, $lowest_load) =
  983: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  984:                 }
  985: 	    }
  986:         }
  987:     }
  988: 
  989:     if (!$want_server_name) {
  990:         my $protocol = 'http';
  991:         if ($protocol{$spare_server} eq 'https') {
  992:             $protocol = $protocol{$spare_server};
  993:         }
  994:         if (defined($spare_server)) {
  995:             my $hostname = &hostname($spare_server);
  996:             if (defined($hostname)) {
  997: 	        $spare_server = $protocol.'://'.$hostname;
  998:             }
  999:         }
 1000:     }
 1001:     return $spare_server;
 1002: }
 1003: 
 1004: sub compare_server_load {
 1005:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1006: 
 1007:     if ($required) {
 1008:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1009:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1010:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1011:         if (($major eq '' && $minor eq '') ||
 1012:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1013:             return ($spare_server,$lowest_load);
 1014:         }
 1015:     }
 1016: 
 1017:     my $loadans     = &reply('load',    $try_server);
 1018:     my $userloadans = &reply('userload',$try_server);
 1019: 
 1020:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1021: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1022:     }
 1023: 
 1024:     my $load;
 1025:     if ($loadans =~ /\d/) {
 1026: 	if ($userloadans =~ /\d/) {
 1027: 	    #both are numbers, pick the bigger one
 1028: 	    $load = ($loadans > $userloadans) ? $loadans 
 1029: 		                              : $userloadans;
 1030: 	} else {
 1031: 	    $load = $loadans;
 1032: 	}
 1033:     } else {
 1034: 	$load = $userloadans;
 1035:     }
 1036: 
 1037:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1038: 	$spare_server = $try_server;
 1039: 	$lowest_load  = $load;
 1040:     }
 1041:     return ($spare_server,$lowest_load);
 1042: }
 1043: 
 1044: # --------------------------- ask offload servers if user already has a session
 1045: sub find_existing_session {
 1046:     my ($udom,$uname) = @_;
 1047:     my $spareshash = &this_host_spares($udom);
 1048:     if (ref($spareshash) eq 'HASH') {
 1049:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1050:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1051:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1052:             }
 1053:         }
 1054:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1055:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1056:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1057:             }
 1058:         }
 1059:     }
 1060:     return;
 1061: }
 1062: 
 1063: # check if user's browser sent load balancer cookie and server still has session
 1064: # and is not overloaded.
 1065: sub check_for_balancer_cookie {
 1066:     my ($r,$update_mtime) = @_;
 1067:     my ($otherserver,$cookie);
 1068:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1069:     if (exists($cookies{'balanceID'})) {
 1070:         my $balid = $cookies{'balanceID'};
 1071:         $cookie=&LONCAPA::clean_handle($balid->value);
 1072:         my $balancedir=$r->dir_config('lonBalanceDir');
 1073:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1074:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1075:                 my ($possudom,$possuname) = ($1,$2);
 1076:                 my $has_session = 0;
 1077:                 if ((&domain($possudom) ne '') &&
 1078:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1079:                     my $try_server;
 1080:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1081:                     if ($opened) {
 1082:                         flock($idf,LOCK_SH);
 1083:                         while (my $line = <$idf>) {
 1084:                             chomp($line);
 1085:                             if (&hostname($line) ne '') {
 1086:                                 $try_server = $line;
 1087:                                 last;
 1088:                             }
 1089:                         }
 1090:                         close($idf);
 1091:                         if (($try_server) &&
 1092:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1093:                             my $lowest_load = 30000;
 1094:                             ($otherserver,$lowest_load) =
 1095:                                 &compare_server_load($try_server,undef,$lowest_load);
 1096:                             if ($otherserver ne '' && $lowest_load < 100) {
 1097:                                 $has_session = 1;
 1098:                             } else {
 1099:                                 undef($otherserver);
 1100:                             }
 1101:                         }
 1102:                     }
 1103:                 }
 1104:                 if ($has_session) {
 1105:                     if ($update_mtime) {
 1106:                         my $atime = my $mtime = time;
 1107:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1108:                     }
 1109:                 } else {
 1110:                     unlink("$balancedir/$cookie.id");
 1111:                 }
 1112:             }
 1113:         }
 1114:     }
 1115:     return ($otherserver,$cookie);
 1116: }
 1117: 
 1118: sub delbalcookie {
 1119:     my ($cookie,$balancer) =@_;
 1120:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1121:         my ($udom,$uname) = ($1,$2);
 1122:         my $uprimary_id = &domain($udom,'primary');
 1123:         my $uintdom = &internet_dom($uprimary_id);
 1124:         my $intdom = &internet_dom($balancer);
 1125:         my $serverhomedom = &host_domain($balancer);
 1126:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1127:             return &reply("delbalcookie:$cookie",$balancer);
 1128:         }
 1129:     }
 1130: }
 1131: 
 1132: # -------------------------------- ask if server already has a session for user
 1133: sub has_user_session {
 1134:     my ($lonid,$udom,$uname) = @_;
 1135:     my $result = &reply(join(':','userhassession',
 1136: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1137:     return 1 if ($result eq 'ok');
 1138: 
 1139:     return 0;
 1140: }
 1141: 
 1142: # --------- determine least loaded server in a user's domain which allows login
 1143: 
 1144: sub choose_server {
 1145:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1146:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1147:     my %servers = &get_servers($udom);
 1148:     my $lowest_load = 30000;
 1149:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1150:     if ($skiploadbal) {
 1151:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1152:         unless (defined($cached)) {
 1153:             my $cachetime = 60*60*24;
 1154:             my %domconfig =
 1155:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1156:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1157:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1158:                                            $cachetime);
 1159:             }
 1160:         }
 1161:     }
 1162:     foreach my $lonhost (keys(%servers)) {
 1163:         if ($skiploadbal) {
 1164:             if (ref($balancers) eq 'HASH') {
 1165:                 next if (exists($balancers->{$lonhost}));
 1166:             }
 1167:         }
 1168:         my $loginvia;
 1169:         if ($checkloginvia) {
 1170:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1171:             if ($loginvia) {
 1172:                 my ($server,$path) = split(/:/,$loginvia);
 1173:                 ($login_host, $lowest_load) =
 1174:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1175:                 if ($login_host eq $server) {
 1176:                     $portal_path = $path;
 1177:                     $isredirect = 1;
 1178:                 }
 1179:             } else {
 1180:                 ($login_host, $lowest_load) =
 1181:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1182:                 if ($login_host eq $lonhost) {
 1183:                     $portal_path = '';
 1184:                     $isredirect = ''; 
 1185:                 }
 1186:             }
 1187:         } else {
 1188:             ($login_host, $lowest_load) =
 1189:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1190:         }
 1191:     }
 1192:     if ($login_host ne '') {
 1193:         $hostname = &hostname($login_host);
 1194:     }
 1195:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1196: }
 1197: 
 1198: # --------------------------------------------- Try to change a user's password
 1199: 
 1200: sub changepass {
 1201:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1202:     $currentpass = &escape($currentpass);
 1203:     $newpass     = &escape($newpass);
 1204:     my $lonhost = $perlvar{'lonHostID'};
 1205:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1206: 		       $server);
 1207:     if (! $answer) {
 1208: 	&logthis("No reply on password change request to $server ".
 1209: 		 "by $uname in domain $udom.");
 1210:     } elsif ($answer =~ "^ok") {
 1211:         &logthis("$uname in $udom successfully changed their password ".
 1212: 		 "on $server.");
 1213:     } elsif ($answer =~ "^pwchange_failure") {
 1214: 	&logthis("$uname in $udom was unable to change their password ".
 1215: 		 "on $server.  The action was blocked by either lcpasswd ".
 1216: 		 "or pwchange");
 1217:     } elsif ($answer =~ "^non_authorized") {
 1218:         &logthis("$uname in $udom did not get their password correct when ".
 1219: 		 "attempting to change it on $server.");
 1220:     } elsif ($answer =~ "^auth_mode_error") {
 1221:         &logthis("$uname in $udom attempted to change their password despite ".
 1222: 		 "not being locally or internally authenticated on $server.");
 1223:     } elsif ($answer =~ "^unknown_user") {
 1224:         &logthis("$uname in $udom attempted to change their password ".
 1225: 		 "on $server but were unable to because $server is not ".
 1226: 		 "their home server.");
 1227:     } elsif ($answer =~ "^refused") {
 1228: 	&logthis("$server refused to change $uname in $udom password because ".
 1229: 		 "it was sent an unencrypted request to change the password.");
 1230:     } elsif ($answer =~ "invalid_client") {
 1231:         &logthis("$server refused to change $uname in $udom password because ".
 1232:                  "it was a reset by e-mail originating from an invalid server.");
 1233:     }
 1234:     return $answer;
 1235: }
 1236: 
 1237: # ----------------------- Try to determine user's current authentication scheme
 1238: 
 1239: sub queryauthenticate {
 1240:     my ($uname,$udom)=@_;
 1241:     my $uhome=&homeserver($uname,$udom);
 1242:     if (!$uhome) {
 1243: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1244: 	return 'no_host';
 1245:     }
 1246:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1247:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1248: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1249:     }
 1250:     return $answer;
 1251: }
 1252: 
 1253: # --------- Try to authenticate user from domain's lib servers (first this one)
 1254: 
 1255: sub authenticate {
 1256:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1257:     $upass=&escape($upass);
 1258:     $uname= &LONCAPA::clean_username($uname);
 1259:     my $uhome=&homeserver($uname,$udom,1);
 1260:     my $newhome;
 1261:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1262: # Maybe the machine was offline and only re-appeared again recently?
 1263:         &reconlonc();
 1264: # One more
 1265: 	$uhome=&homeserver($uname,$udom,1);
 1266:         if (($uhome eq 'no_host') && $checkdefauth) {
 1267:             if (defined(&domain($udom,'primary'))) {
 1268:                 $newhome=&domain($udom,'primary');
 1269:             }
 1270:             if ($newhome ne '') {
 1271:                 $uhome = $newhome;
 1272:             }
 1273:         }
 1274: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1275: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1276: 	    return 'no_host';
 1277:         }
 1278:     }
 1279:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1280:     if ($answer eq 'authorized') {
 1281:         if ($newhome) {
 1282:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1283:             return 'no_account_on_host'; 
 1284:         } else {
 1285:             &logthis("User $uname at $udom authorized by $uhome");
 1286:             return $uhome;
 1287:         }
 1288:     }
 1289:     if ($answer eq 'non_authorized') {
 1290: 	&logthis("User $uname at $udom rejected by $uhome");
 1291: 	return 'no_host'; 
 1292:     }
 1293:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1294:     return 'no_host';
 1295: }
 1296: 
 1297: sub can_host_session {
 1298:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1299:     my $canhost = 1;
 1300:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1301:     if (ref($remotesessions) eq 'HASH') {
 1302:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1303:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1304:                 $canhost = 0;
 1305:             } else {
 1306:                 $canhost = 1;
 1307:             }
 1308:         }
 1309:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1310:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1311:                 $canhost = 1;
 1312:             } else {
 1313:                 $canhost = 0;
 1314:             }
 1315:         }
 1316:         if ($canhost) {
 1317:             if ($remotesessions->{'version'} ne '') {
 1318:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1319:                 if ($reqmajor ne '' && $reqminor ne '') {
 1320:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1321:                         my $major = $1;
 1322:                         my $minor = $2;
 1323:                         if (($major < $reqmajor ) ||
 1324:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1325:                             $canhost = 0;
 1326:                         }
 1327:                     } else {
 1328:                         $canhost = 0;
 1329:                     }
 1330:                 }
 1331:             }
 1332:         }
 1333:     }
 1334:     if ($canhost) {
 1335:         if (ref($hostedsessions) eq 'HASH') {
 1336:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1337:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1338:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1339:                 if (($uint_dom ne '') && 
 1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1341:                     $canhost = 0;
 1342:                 } else {
 1343:                     $canhost = 1;
 1344:                 }
 1345:             }
 1346:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1347:                 if (($uint_dom ne '') && 
 1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1349:                     $canhost = 1;
 1350:                 } else {
 1351:                     $canhost = 0;
 1352:                 }
 1353:             }
 1354:         }
 1355:     }
 1356:     return $canhost;
 1357: }
 1358: 
 1359: sub spare_can_host {
 1360:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1361:     my $canhost=1;
 1362:     my $try_server_hostname = &hostname($try_server);
 1363:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1364:     my $serverhomedom = &host_domain($serverhomeID);
 1365:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1366:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1367:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1368:             $canhost = 0;
 1369:         }
 1370:     }
 1371:     if (($canhost) && ($uint_dom)) {
 1372:         my @intdoms;
 1373:         my $internet_names = &get_internet_names($try_server);
 1374:         if (ref($internet_names) eq 'ARRAY') {
 1375:             @intdoms = @{$internet_names};
 1376:         }
 1377:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1378:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1379:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1380:                                          $remotesessions,
 1381:                                          $defdomdefaults{'hostedsessions'});
 1382:         }
 1383:     }
 1384:     return $canhost;
 1385: }
 1386: 
 1387: sub this_host_spares {
 1388:     my ($dom) = @_;
 1389:     my ($dom_in_use,$lonhost_in_use,$result);
 1390:     my @hosts = &current_machine_ids();
 1391:     foreach my $lonhost (@hosts) {
 1392:         if (&host_domain($lonhost) eq $dom) {
 1393:             $dom_in_use = $dom;
 1394:             $lonhost_in_use = $lonhost;
 1395:             last;
 1396:         }
 1397:     }
 1398:     if ($dom_in_use ne '') {
 1399:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1400:     }
 1401:     if (ref($result) ne 'HASH') {
 1402:         $lonhost_in_use = $perlvar{'lonHostID'};
 1403:         $dom_in_use = &host_domain($lonhost_in_use);
 1404:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1405:         if (ref($result) ne 'HASH') {
 1406:             $result = \%spareid;
 1407:         }
 1408:     }
 1409:     return $result;
 1410: }
 1411: 
 1412: sub spares_for_offload  {
 1413:     my ($dom_in_use,$lonhost_in_use) = @_;
 1414:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1415:     if (defined($cached)) {
 1416:         return $result;
 1417:     } else {
 1418:         my $cachetime = 60*60*24;
 1419:         my %domconfig =
 1420:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1421:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1422:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1423:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1424:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1425:                 }
 1426:             }
 1427:         }
 1428:     }
 1429:     return;
 1430: }
 1431: 
 1432: sub get_lonbalancer_config {
 1433:     my ($servers) = @_;
 1434:     my ($currbalancer,$currtargets);
 1435:     if (ref($servers) eq 'HASH') {
 1436:         foreach my $server (keys(%{$servers})) {
 1437:             my %what = (
 1438:                          spareid => 1,
 1439:                          perlvar => 1,
 1440:                        );
 1441:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1442:             if ($result eq 'ok') {
 1443:                 if (ref($returnhash) eq 'HASH') {
 1444:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1445:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1446:                             $currbalancer = $server;
 1447:                             $currtargets = {};
 1448:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1449:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1450:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1451:                                 }
 1452:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1453:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1454:                                 }
 1455:                             }
 1456:                             last;
 1457:                         }
 1458:                     }
 1459:                 }
 1460:             }
 1461:         }
 1462:     }
 1463:     return ($currbalancer,$currtargets);
 1464: }
 1465: 
 1466: sub check_loadbalancing {
 1467:     my ($uname,$udom,$caller) = @_;
 1468:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1469:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1470:     my $lonhost = $perlvar{'lonHostID'};
 1471:     my @hosts = &current_machine_ids();
 1472:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1473:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1474:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1475:     my $serverhomedom = &host_domain($lonhost);
 1476:     my $domneedscache;
 1477:     my $cachetime = 60*60*24;
 1478: 
 1479:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1480:         $dom_in_use = $udom;
 1481:         $homeintdom = 1;
 1482:     } else {
 1483:         $dom_in_use = $serverhomedom;
 1484:     }
 1485:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1486:     unless (defined($cached)) {
 1487:         my %domconfig =
 1488:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1489:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1490:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1491:         } else {
 1492:             $domneedscache = $dom_in_use;
 1493:         }
 1494:     }
 1495:     if (ref($result) eq 'HASH') {
 1496:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1497:             &check_balancer_result($result,@hosts);
 1498:         if ($is_balancer) {
 1499:             if (ref($currrules) eq 'HASH') {
 1500:                 if ($homeintdom) {
 1501:                     if ($uname ne '') {
 1502:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1503:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1504:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1505:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1506:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1507:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1508:                             }
 1509:                         }
 1510:                         if ($rule_in_effect eq '') {
 1511:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1512:                             if ($userenv{'inststatus'} ne '') {
 1513:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1514:                                 my ($othertitle,$usertypes,$types) =
 1515:                                     &Apache::loncommon::sorted_inst_types($udom);
 1516:                                 if (ref($types) eq 'ARRAY') {
 1517:                                     foreach my $type (@{$types}) {
 1518:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1519:                                             if (exists($currrules->{$type})) {
 1520:                                                 $rule_in_effect = $currrules->{$type};
 1521:                                             }
 1522:                                         }
 1523:                                     }
 1524:                                 }
 1525:                             } else {
 1526:                                 if (exists($currrules->{'default'})) {
 1527:                                     $rule_in_effect = $currrules->{'default'};
 1528:                                 }
 1529:                             }
 1530:                         }
 1531:                     } else {
 1532:                         if (exists($currrules->{'default'})) {
 1533:                             $rule_in_effect = $currrules->{'default'};
 1534:                         }
 1535:                     }
 1536:                 } else {
 1537:                     if ($currrules->{'_LC_external'} ne '') {
 1538:                         $rule_in_effect = $currrules->{'_LC_external'};
 1539:                     }
 1540:                 }
 1541:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1542:                                                        $uname,$udom);
 1543:             }
 1544:         }
 1545:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1546:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1547:         unless (defined($cached)) {
 1548:             my %domconfig =
 1549:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1550:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1551:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1552:             } else {
 1553:                 $domneedscache = $serverhomedom;
 1554:             }
 1555:         }
 1556:         if (ref($result) eq 'HASH') {
 1557:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1558:                 &check_balancer_result($result,@hosts);
 1559:             if ($is_balancer) {
 1560:                 if (ref($currrules) eq 'HASH') {
 1561:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1562:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1563:                     }
 1564:                 }
 1565:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1566:                                                        $uname,$udom);
 1567:             }
 1568:         } else {
 1569:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1570:                 $is_balancer = 1;
 1571:                 $offloadto = &this_host_spares($dom_in_use);
 1572:             }
 1573:             unless (defined($cached)) {
 1574:                 $domneedscache = $serverhomedom;
 1575:             }
 1576:         }
 1577:     } else {
 1578:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1579:             $is_balancer = 1;
 1580:             $offloadto = &this_host_spares($dom_in_use);
 1581:         }
 1582:         unless (defined($cached)) {
 1583:             $domneedscache = $serverhomedom;
 1584:         }
 1585:     }
 1586:     if ($domneedscache) {
 1587:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1588:     }
 1589:     if ($is_balancer) {
 1590:         my $lowest_load = 30000;
 1591:         if (ref($offloadto) eq 'HASH') {
 1592:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1593:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1594:                     ($otherserver,$lowest_load) =
 1595:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1596:                 }
 1597:             }
 1598:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1599: 
 1600:             if (!$found_server) {
 1601:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1602:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1603:                         ($otherserver,$lowest_load) =
 1604:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1605:                     }
 1606:                 }
 1607:             }
 1608:         } elsif (ref($offloadto) eq 'ARRAY') {
 1609:             if (@{$offloadto} == 1) {
 1610:                 $otherserver = $offloadto->[0];
 1611:             } elsif (@{$offloadto} > 1) {
 1612:                 foreach my $try_server (@{$offloadto}) {
 1613:                     ($otherserver,$lowest_load) =
 1614:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1615:                 }
 1616:             }
 1617:         }
 1618:         unless ($caller eq 'login') {
 1619:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1620:                 $is_balancer = 0;
 1621:                 if ($uname ne '' && $udom ne '') {
 1622:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1623:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1624:                                  'user.loadbalcheck.time' => time});
 1625:                     }
 1626:                 }
 1627:             }
 1628:         }
 1629:         unless ($homeintdom) {
 1630:             undef($setcookie);
 1631:         }
 1632:     }
 1633:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1634: }
 1635: 
 1636: sub check_balancer_result {
 1637:     my ($result,@hosts) = @_;
 1638:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1639:     if (ref($result) eq 'HASH') {
 1640:         if ($result->{'lonhost'} ne '') {
 1641:             my $currbalancer = $result->{'lonhost'};
 1642:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1643:                 $is_balancer = 1;
 1644:                 $currtargets = $result->{'targets'};
 1645:                 $currrules = $result->{'rules'};
 1646:                 $dom_balancers = $currbalancer;
 1647:             }
 1648:             $dom_balancers = $currbalancer;
 1649:         } else {
 1650:             if (keys(%{$result})) {
 1651:                 foreach my $key (keys(%{$result})) {
 1652:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1653:                         (ref($result->{$key}) eq 'HASH')) {
 1654:                         $is_balancer = 1;
 1655:                         $currrules = $result->{$key}{'rules'};
 1656:                         $currtargets = $result->{$key}{'targets'};
 1657:                         $setcookie = $result->{$key}{'cookie'};
 1658:                         last;
 1659:                     }
 1660:                 }
 1661:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1662:             }
 1663:         }
 1664:     }
 1665:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1666: }
 1667: 
 1668: sub get_loadbalancer_targets {
 1669:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1670:     my $offloadto;
 1671:     if ($rule_in_effect eq 'none') {
 1672:         return [$perlvar{'lonHostID'}];
 1673:     } elsif ($rule_in_effect eq '') {
 1674:         $offloadto = $currtargets;
 1675:     } else {
 1676:         if ($rule_in_effect eq 'homeserver') {
 1677:             my $homeserver = &homeserver($uname,$udom);
 1678:             if ($homeserver ne 'no_host') {
 1679:                 $offloadto = [$homeserver];
 1680:             }
 1681:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1682:             my %domconfig =
 1683:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1684:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1685:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1686:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1687:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1688:                     }
 1689:                 }
 1690:             } else {
 1691:                 my %servers = &internet_dom_servers($udom);
 1692:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1693:                 if (&hostname($remotebalancer) ne '') {
 1694:                     $offloadto = [$remotebalancer];
 1695:                 }
 1696:             }
 1697:         } elsif (&hostname($rule_in_effect) ne '') {
 1698:             $offloadto = [$rule_in_effect];
 1699:         }
 1700:     }
 1701:     return $offloadto;
 1702: }
 1703: 
 1704: sub internet_dom_servers {
 1705:     my ($dom) = @_;
 1706:     my (%uniqservers,%servers);
 1707:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1708:     my @machinedoms = &machine_domains($primaryserver);
 1709:     foreach my $mdom (@machinedoms) {
 1710:         my %currservers = %servers;
 1711:         my %server = &get_servers($mdom);
 1712:         %servers = (%currservers,%server);
 1713:     }
 1714:     my %by_hostname;
 1715:     foreach my $id (keys(%servers)) {
 1716:         push(@{$by_hostname{$servers{$id}}},$id);
 1717:     }
 1718:     foreach my $hostname (sort(keys(%by_hostname))) {
 1719:         if (@{$by_hostname{$hostname}} > 1) {
 1720:             my $match = 0;
 1721:             foreach my $id (@{$by_hostname{$hostname}}) {
 1722:                 if (&host_domain($id) eq $dom) {
 1723:                     $uniqservers{$id} = $hostname;
 1724:                     $match = 1;
 1725:                 }
 1726:             }
 1727:             unless ($match) {
 1728:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1729:             }
 1730:         } else {
 1731:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1732:         }
 1733:     }
 1734:     return %uniqservers;
 1735: }
 1736: 
 1737: sub trusted_domains {
 1738:     my ($cmdtype,$calldom) = @_;
 1739:     my ($trusted,$untrusted);
 1740:     if (&domain($calldom) eq '') {
 1741:         return ($trusted,$untrusted);
 1742:     }
 1743:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1744:         return ($trusted,$untrusted);
 1745:     }
 1746:     my $callprimary = &domain($calldom,'primary');
 1747:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1748:     if ($intcalldom eq '') {
 1749:         return ($trusted,$untrusted);
 1750:     }
 1751: 
 1752:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1753:     unless (defined($cached)) {
 1754:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1755:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1756:         $trustconfig = $domconfig{'trust'};
 1757:     }
 1758:     if (ref($trustconfig)) {
 1759:         my (%possexc,%possinc,@allexc,@allinc); 
 1760:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1761:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1762:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1763:             }
 1764:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1765:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1766:             }
 1767:         }
 1768:         if (keys(%possexc)) {
 1769:             if (keys(%possinc)) {
 1770:                 foreach my $key (sort(keys(%possexc))) {
 1771:                     next if ($key eq $intcalldom);
 1772:                     unless ($possinc{$key}) {
 1773:                         push(@allexc,$key);
 1774:                     }
 1775:                 }
 1776:             } else {
 1777:                 @allexc = sort(keys(%possexc));
 1778:             }
 1779:         }
 1780:         if (keys(%possinc)) {
 1781:             $possinc{$intcalldom} = 1;
 1782:             @allinc = sort(keys(%possinc));
 1783:         }
 1784:         if ((@allexc > 0) || (@allinc > 0)) {
 1785:             my %doms_by_intdom;
 1786:             my %allintdoms = &all_host_intdom();
 1787:             my %alldoms = &all_host_domain();
 1788:             foreach my $key (%allintdoms) {
 1789:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1790:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1791:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1792:                     }
 1793:                 } else {
 1794:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1795:                 }
 1796:             }
 1797:             foreach my $exc (@allexc) {
 1798:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1799:                     $untrusted = $doms_by_intdom{$exc};
 1800:                 }
 1801:             }
 1802:             foreach my $inc (@allinc) {
 1803:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1804:                     $trusted = $doms_by_intdom{$inc};
 1805:                 }
 1806:             }
 1807:         }
 1808:     }
 1809:     return ($trusted,$untrusted);
 1810: }
 1811: 
 1812: sub will_trust {
 1813:     my ($cmdtype,$domain,$possdom) = @_;
 1814:     return 1 if ($domain eq $possdom);
 1815:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1816:     my $willtrust; 
 1817:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1818:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1819:             $willtrust = 1;
 1820:         }
 1821:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1822:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1823:             $willtrust = 1;
 1824:         }
 1825:     } else {
 1826:         $willtrust = 1;
 1827:     }
 1828:     return $willtrust;
 1829: }
 1830: 
 1831: # ---------------------- Find the homebase for a user from domain's lib servers
 1832: 
 1833: my %homecache;
 1834: sub homeserver {
 1835:     my ($uname,$udom,$ignoreBadCache)=@_;
 1836:     my $index="$uname:$udom";
 1837: 
 1838:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1839: 
 1840:     my %servers = &get_servers($udom,'library');
 1841:     foreach my $tryserver (keys(%servers)) {
 1842:         next if ($ignoreBadCache ne 'true' && 
 1843: 		 exists($badServerCache{$tryserver}));
 1844: 
 1845: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1846: 	if ($answer eq 'found') {
 1847: 	    delete($badServerCache{$tryserver}); 
 1848: 	    return $homecache{$index}=$tryserver;
 1849: 	} elsif ($answer eq 'no_host') {
 1850: 	    $badServerCache{$tryserver}=1;
 1851: 	}
 1852:     }    
 1853:     return 'no_host';
 1854: }
 1855: 
 1856: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1857: 
 1858: sub idget {
 1859:     my ($udom,$idsref,$namespace)=@_;
 1860:     my %returnhash=();
 1861:     my @ids=(); 
 1862:     if (ref($idsref) eq 'ARRAY') {
 1863:         @ids = @{$idsref};
 1864:     } else {
 1865:         return %returnhash; 
 1866:     }
 1867:     if ($namespace eq '') {
 1868:         $namespace = 'ids';
 1869:     }
 1870:     
 1871:     my %servers = &get_servers($udom,'library');
 1872:     foreach my $tryserver (keys(%servers)) {
 1873: 	my $idlist=join('&', map { &escape($_); } @ids);
 1874: 	if ($namespace eq 'ids') {
 1875: 	    $idlist=~tr/A-Z/a-z/;
 1876: 	}
 1877: 	my $reply;
 1878: 	if ($namespace eq 'ids') {
 1879: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1880: 	} else {
 1881: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1882: 	}
 1883: 	my @answer=();
 1884: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1885: 	    @answer=split(/\&/,$reply);
 1886: 	}                    ;
 1887: 	my $i;
 1888: 	for ($i=0;$i<=$#ids;$i++) {
 1889: 	    if ($answer[$i]) {
 1890: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1891: 	    }
 1892: 	}
 1893:     }
 1894:     return %returnhash;
 1895: }
 1896: 
 1897: # ------------------------------------- Find the IDs behind a list of usernames
 1898: 
 1899: sub idrget {
 1900:     my ($udom,@unames)=@_;
 1901:     my %returnhash=();
 1902:     foreach my $uname (@unames) {
 1903:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1904:     }
 1905:     return %returnhash;
 1906: }
 1907: 
 1908: # Store away a list of names and associated student/employee IDs or clicker IDs
 1909: 
 1910: sub idput {
 1911:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1912:     my %servers=();
 1913:     my %ids=();
 1914:     my %byid = ();
 1915:     if (ref($idsref) eq 'HASH') {
 1916:         %ids=%{$idsref};
 1917:     }
 1918:     if ($namespace eq '') {
 1919:         $namespace = 'ids'; 
 1920:     }
 1921:     foreach my $uname (keys(%ids)) {
 1922: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1923:         if ($uhom eq '') {
 1924:             $uhom=&homeserver($uname,$udom);
 1925:         }
 1926:         if ($uhom ne 'no_host') {
 1927:             my $esc_unam=&escape($uname);
 1928:             if ($namespace eq 'ids') {
 1929:                 my $id=&escape($ids{$uname});
 1930:                 $id=~tr/A-Z/a-z/;
 1931:                 my $esc_unam=&escape($uname);
 1932:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1933:             } else {
 1934:                 my @currids = split(/,/,$ids{$uname});
 1935:                 foreach my $id (@currids) {
 1936:                     $byid{$uhom}{$id} .= $uname.',';
 1937:                 }
 1938:             }
 1939:         }
 1940:     }
 1941:     if ($namespace eq 'clickers') {
 1942:         foreach my $server (keys(%byid)) {
 1943:             if (ref($byid{$server}) eq 'HASH') {
 1944:                 foreach my $id (keys(%{$byid{$server}})) {
 1945:                     $byid{$server} =~ s/,$//;
 1946:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1947:                 }
 1948:             }
 1949:         }
 1950:     }
 1951:     foreach my $server (keys(%servers)) {
 1952:         $servers{$server} =~ s/\&$//;
 1953:         if ($namespace eq 'ids') {     
 1954:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1955:         } else {
 1956:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1957:         }
 1958:     }
 1959: }
 1960: 
 1961: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1962: 
 1963: sub iddel {
 1964:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1965:     my %result=();
 1966:     my %ids=();
 1967:     my %byid = ();
 1968:     if (ref($idshashref) eq 'HASH') {
 1969:         %ids=%{$idshashref};
 1970:     } else {
 1971:         return %result;
 1972:     }
 1973:     if ($namespace eq '') {
 1974:         $namespace = 'ids';
 1975:     }
 1976:     my %servers=();
 1977:     while (my ($id,$unamestr) = each(%ids)) {
 1978:         if ($namespace eq 'ids') {
 1979:             my $uhom = $uhome;
 1980:             if ($uhom eq '') { 
 1981:                 $uhom=&homeserver($unamestr,$udom);
 1982:             }
 1983:             if ($uhom ne 'no_host') {
 1984:                 $servers{$uhom}.='&'.&escape($id);
 1985:             }
 1986:          } else {
 1987:             my @curritems = split(/,/,$ids{$id});
 1988:             foreach my $uname (@curritems) {
 1989:                 my $uhom = $uhome;
 1990:                 if ($uhom eq '') {
 1991:                     $uhom=&homeserver($uname,$udom);
 1992:                 }
 1993:                 if ($uhom ne 'no_host') { 
 1994:                     $byid{$uhom}{$id} .= $uname.',';
 1995:                 }
 1996:             }
 1997:         }
 1998:     }
 1999:     if ($namespace eq 'clickers') {
 2000:         foreach my $server (keys(%byid)) {
 2001:             if (ref($byid{$server}) eq 'HASH') {
 2002:                 foreach my $id (keys(%{$byid{$server}})) {
 2003:                     $byid{$server}{$id} =~ s/,$//;
 2004:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2005:                 }
 2006:             }
 2007:         }
 2008:     }
 2009:     foreach my $server (keys(%servers)) {
 2010:         $servers{$server} =~ s/\&$//;
 2011:         if ($namespace eq 'ids') {
 2012:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2013:         } elsif ($namespace eq 'clickers') {
 2014:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2015:         }
 2016:     }
 2017:     return %result;
 2018: }
 2019: 
 2020: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2021: 
 2022: sub updateclickers {
 2023:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2024:     my %clickers;
 2025:     if (ref($idshashref) eq 'HASH') {
 2026:         %clickers=%{$idshashref};
 2027:     } else {
 2028:         return;
 2029:     }
 2030:     my $items='';
 2031:     foreach my $item (keys(%clickers)) {
 2032:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2033:     }
 2034:     $items=~s/\&$//;
 2035:     my $request = "updateclickers:$udom:$action:$items";
 2036:     if ($critical) {
 2037:         return &critical($request,$uhome);
 2038:     } else {
 2039:         return &reply($request,$uhome);
 2040:     }
 2041: }
 2042: 
 2043: # ------------------------------dump from db file owned by domainconfig user
 2044: sub dump_dom {
 2045:     my ($namespace, $udom, $regexp) = @_;
 2046: 
 2047:     $udom ||= $env{'user.domain'};
 2048: 
 2049:     return () unless $udom;
 2050: 
 2051:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2052: }
 2053: 
 2054: # ------------------------------------------ get items from domain db files   
 2055: 
 2056: sub get_dom {
 2057:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2058:     return if ($udom eq 'public');
 2059:     my $items='';
 2060:     foreach my $item (@$storearr) {
 2061:         $items.=&escape($item).'&';
 2062:     }
 2063:     $items=~s/\&$//;
 2064:     if (!$udom) {
 2065:         $udom=$env{'user.domain'};
 2066:         return if ($udom eq 'public');
 2067:         if (defined(&domain($udom,'primary'))) {
 2068:             $uhome=&domain($udom,'primary');
 2069:         } else {
 2070:             undef($uhome);
 2071:         }
 2072:     } else {
 2073:         if (!$uhome) {
 2074:             if (defined(&domain($udom,'primary'))) {
 2075:                 $uhome=&domain($udom,'primary');
 2076:             }
 2077:         }
 2078:     }
 2079:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2080:         my $rep;
 2081:         if ($namespace =~ /^enc/) {
 2082:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2083:         } else {
 2084:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2085:         }
 2086:         my %returnhash;
 2087:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2088:             return %returnhash;
 2089:         }
 2090:         my @pairs=split(/\&/,$rep);
 2091:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2092:             return @pairs;
 2093:         }
 2094:         my $i=0;
 2095:         foreach my $item (@$storearr) {
 2096:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2097:             $i++;
 2098:         }
 2099:         return %returnhash;
 2100:     } else {
 2101:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2102:     }
 2103: }
 2104: 
 2105: # -------------------------------------------- put items in domain db files 
 2106: 
 2107: sub put_dom {
 2108:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2109:     if (!$udom) {
 2110:         $udom=$env{'user.domain'};
 2111:         if (defined(&domain($udom,'primary'))) {
 2112:             $uhome=&domain($udom,'primary');
 2113:         } else {
 2114:             undef($uhome);
 2115:         }
 2116:     } else {
 2117:         if (!$uhome) {
 2118:             if (defined(&domain($udom,'primary'))) {
 2119:                 $uhome=&domain($udom,'primary');
 2120:             }
 2121:         }
 2122:     } 
 2123:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2124:         my $items='';
 2125:         foreach my $item (keys(%$storehash)) {
 2126:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2127:         }
 2128:         $items=~s/\&$//;
 2129:         if ($namespace =~ /^enc/) {
 2130:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2131:         } else {
 2132:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2133:         }
 2134:     } else {
 2135:         &logthis("put_dom failed - no homeserver and/or domain");
 2136:     }
 2137: }
 2138: 
 2139: # --------------------- newput for items in db file owned by domainconfig user
 2140: sub newput_dom {
 2141:     my ($namespace,$storehash,$udom) = @_;
 2142:     my $result;
 2143:     if (!$udom) {
 2144:         $udom=$env{'user.domain'};
 2145:     }
 2146:     if ($udom) {
 2147:         my $uname = &get_domainconfiguser($udom);
 2148:         $result = &newput($namespace,$storehash,$udom,$uname);
 2149:     }
 2150:     return $result;
 2151: }
 2152: 
 2153: # --------------------- delete for items in db file owned by domainconfig user
 2154: sub del_dom {
 2155:     my ($namespace,$storearr,$udom)=@_;
 2156:     if (ref($storearr) eq 'ARRAY') {
 2157:         if (!$udom) {
 2158:             $udom=$env{'user.domain'};
 2159:         }
 2160:         if ($udom) {
 2161:             my $uname = &get_domainconfiguser($udom); 
 2162:             return &del($namespace,$storearr,$udom,$uname);
 2163:         }
 2164:     }
 2165: }
 2166: 
 2167: # ----------------------------------construct domainconfig user for a domain 
 2168: sub get_domainconfiguser {
 2169:     my ($udom) = @_;
 2170:     return $udom.'-domainconfig';
 2171: }
 2172: 
 2173: sub retrieve_inst_usertypes {
 2174:     my ($udom) = @_;
 2175:     my (%returnhash,@order);
 2176:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2177:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2178:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2179:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2180:     } else {
 2181:         if (defined(&domain($udom,'primary'))) {
 2182:             my $uhome=&domain($udom,'primary');
 2183:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2184:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2185:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2186:                 return (\%returnhash,\@order);
 2187:             }
 2188:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2189:             my @pairs=split(/\&/,$hashitems);
 2190:             foreach my $item (@pairs) {
 2191:                 my ($key,$value)=split(/=/,$item,2);
 2192:                 $key = &unescape($key);
 2193:                 next if ($key =~ /^error: 2 /);
 2194:                 $returnhash{$key}=&thaw_unescape($value);
 2195:             }
 2196:             my @esc_order = split(/\&/,$orderitems);
 2197:             foreach my $item (@esc_order) {
 2198:                 push(@order,&unescape($item));
 2199:             }
 2200:         } else {
 2201:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2202:         }
 2203:         return (\%returnhash,\@order);
 2204:     }
 2205: }
 2206: 
 2207: sub is_domainimage {
 2208:     my ($url) = @_;
 2209:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2210:         if (&domain($1) ne '') {
 2211:             return '1';
 2212:         }
 2213:     }
 2214:     return;
 2215: }
 2216: 
 2217: sub inst_directory_query {
 2218:     my ($srch) = @_;
 2219:     my $udom = $srch->{'srchdomain'};
 2220:     my %results;
 2221:     my $homeserver = &domain($udom,'primary');
 2222:     my $outcome;
 2223:     if ($homeserver ne '') {
 2224:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2225:             if ($srch->{'srchby'} eq 'email') {
 2226:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2227:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2228:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2229:                     (($major == 2) && ($minor < 12))) {
 2230:                     return;
 2231:                 }
 2232:             }
 2233:         }
 2234: 	my $queryid=&reply("querysend:instdirsearch:".
 2235: 			   &escape($srch->{'srchby'}).':'.
 2236: 			   &escape($srch->{'srchterm'}).':'.
 2237: 			   &escape($srch->{'srchtype'}),$homeserver);
 2238: 	my $host=&hostname($homeserver);
 2239: 	if ($queryid !~/^\Q$host\E\_/) {
 2240: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2241: 	    return;
 2242: 	}
 2243: 	my $response = &get_query_reply($queryid);
 2244: 	my $maxtries = 5;
 2245: 	my $tries = 1;
 2246: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2247: 	    $response = &get_query_reply($queryid);
 2248: 	    $tries ++;
 2249: 	}
 2250: 
 2251:         if (!&error($response) && $response ne 'refused') {
 2252:             if ($response eq 'unavailable') {
 2253:                 $outcome = $response;
 2254:             } else {
 2255:                 $outcome = 'ok';
 2256:                 my @matches = split(/\n/,$response);
 2257:                 foreach my $match (@matches) {
 2258:                     my ($key,$value) = split(/=/,$match);
 2259:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2260:                 }
 2261:             }
 2262:         }
 2263:     }
 2264:     return ($outcome,%results);
 2265: }
 2266: 
 2267: sub usersearch {
 2268:     my ($srch) = @_;
 2269:     my $dom = $srch->{'srchdomain'};
 2270:     my %results;
 2271:     my %libserv = &all_library();
 2272:     my $query = 'usersearch';
 2273:     foreach my $tryserver (keys(%libserv)) {
 2274:         if (&host_domain($tryserver) eq $dom) {
 2275:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2276:                 if ($srch->{'srchby'} eq 'email') {
 2277:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2278:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2279:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2280:                              (($major == 2) && ($minor < 12)));
 2281:                 }
 2282:             }
 2283:             my $host=&hostname($tryserver);
 2284:             my $queryid=
 2285:                 &reply("querysend:".&escape($query).':'.
 2286:                        &escape($srch->{'srchby'}).':'.
 2287:                        &escape($srch->{'srchtype'}).':'.
 2288:                        &escape($srch->{'srchterm'}),$tryserver);
 2289:             if ($queryid !~/^\Q$host\E\_/) {
 2290:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2291:                 next;
 2292:             }
 2293:             my $reply = &get_query_reply($queryid);
 2294:             my $maxtries = 1;
 2295:             my $tries = 1;
 2296:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2297:                 $reply = &get_query_reply($queryid);
 2298:                 $tries ++;
 2299:             }
 2300:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2301:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2302:             } else {
 2303:                 my @matches;
 2304:                 if ($reply =~ /\n/) {
 2305:                     @matches = split(/\n/,$reply);
 2306:                 } else {
 2307:                     @matches = split(/\&/,$reply);
 2308:                 }
 2309:                 foreach my $match (@matches) {
 2310:                     my ($uname,$udom,%userhash);
 2311:                     foreach my $entry (split(/:/,$match)) {
 2312:                         my ($key,$value) =
 2313:                             map {&unescape($_);} split(/=/,$entry);
 2314:                         $userhash{$key} = $value;
 2315:                         if ($key eq 'username') {
 2316:                             $uname = $value;
 2317:                         } elsif ($key eq 'domain') {
 2318:                             $udom = $value;
 2319:                         }
 2320:                     }
 2321:                     $results{$uname.':'.$udom} = \%userhash;
 2322:                 }
 2323:             }
 2324:         }
 2325:     }
 2326:     return %results;
 2327: }
 2328: 
 2329: sub get_instuser {
 2330:     my ($udom,$uname,$id) = @_;
 2331:     my $homeserver = &domain($udom,'primary');
 2332:     my ($outcome,%results);
 2333:     if ($homeserver ne '') {
 2334:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2335:                            &escape($id).':'.&escape($udom),$homeserver);
 2336:         my $host=&hostname($homeserver);
 2337:         if ($queryid !~/^\Q$host\E\_/) {
 2338:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2339:             return;
 2340:         }
 2341:         my $response = &get_query_reply($queryid);
 2342:         my $maxtries = 5;
 2343:         my $tries = 1;
 2344:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2345:             $response = &get_query_reply($queryid);
 2346:             $tries ++;
 2347:         }
 2348:         if (!&error($response) && $response ne 'refused') {
 2349:             if ($response eq 'unavailable') {
 2350:                 $outcome = $response;
 2351:             } else {
 2352:                 $outcome = 'ok';
 2353:                 my @matches = split(/\n/,$response);
 2354:                 foreach my $match (@matches) {
 2355:                     my ($key,$value) = split(/=/,$match);
 2356:                     $results{&unescape($key)} = &thaw_unescape($value);
 2357:                 }
 2358:             }
 2359:         }
 2360:     }
 2361:     my %userinfo;
 2362:     if (ref($results{$uname}) eq 'HASH') {
 2363:         %userinfo = %{$results{$uname}};
 2364:     } 
 2365:     return ($outcome,%userinfo);
 2366: }
 2367: 
 2368: sub get_multiple_instusers {
 2369:     my ($udom,$users,$caller) = @_;
 2370:     my ($outcome,$results);
 2371:     if (ref($users) eq 'HASH') {
 2372:         my $count = keys(%{$users}); 
 2373:         my $requested = &freeze_escape($users);
 2374:         my $homeserver = &domain($udom,'primary');
 2375:         if ($homeserver ne '') {
 2376:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2377:             my $host=&hostname($homeserver);
 2378:             if ($queryid !~/^\Q$host\E\_/) {
 2379:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2380:                          ' for host: '.$homeserver.'in domain '.$udom);
 2381:                 return ($outcome,$results);
 2382:             }
 2383:             my $response = &get_query_reply($queryid);
 2384:             my $maxtries = 5;
 2385:             if ($count > 100) {
 2386:                 $maxtries = 1+int($count/20);
 2387:             }
 2388:             my $tries = 1;
 2389:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2390:                 $response = &get_query_reply($queryid);
 2391:                 $tries ++;
 2392:             }
 2393:             if ($response eq '') {
 2394:                 $results = {};
 2395:                 foreach my $key (keys(%{$users})) {
 2396:                     my ($uname,$id);
 2397:                     if ($caller eq 'id') {
 2398:                         $id = $key;
 2399:                     } else {
 2400:                         $uname = $key;
 2401:                     }
 2402:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2403:                     $outcome = $resp;
 2404:                     if ($resp eq 'ok') {
 2405:                         %{$results} = (%{$results}, %info);
 2406:                     } else {
 2407:                         last;
 2408:                     }
 2409:                 }
 2410:             } elsif(!&error($response) && ($response ne 'refused')) {
 2411:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2412:                     $outcome = $response;
 2413:                 } else {
 2414:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2415:                     if ($outcome eq 'ok') {
 2416:                         $results = &thaw_unescape($userdata); 
 2417:                     }
 2418:                 }
 2419:             }
 2420:         }
 2421:     }
 2422:     return ($outcome,$results);
 2423: }
 2424: 
 2425: sub inst_rulecheck {
 2426:     my ($udom,$uname,$id,$item,$rules) = @_;
 2427:     my %returnhash;
 2428:     if ($udom ne '') {
 2429:         if (ref($rules) eq 'ARRAY') {
 2430:             @{$rules} = map {&escape($_);} (@{$rules});
 2431:             my $rulestr = join(':',@{$rules});
 2432:             my $homeserver=&domain($udom,'primary');
 2433:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2434:                 my $response;
 2435:                 if ($item eq 'username') {                
 2436:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2437:                                               ':'.&escape($uname).':'.$rulestr,
 2438:                                               $homeserver));
 2439:                 } elsif ($item eq 'id') {
 2440:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2441:                                               ':'.&escape($id).':'.$rulestr,
 2442:                                               $homeserver));
 2443:                 } elsif ($item eq 'selfcreate') {
 2444:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2445:                                                &escape($udom).':'.&escape($uname).
 2446:                                               ':'.$rulestr,$homeserver));
 2447:                 }
 2448:                 if ($response ne 'refused') {
 2449:                     my @pairs=split(/\&/,$response);
 2450:                     foreach my $item (@pairs) {
 2451:                         my ($key,$value)=split(/=/,$item,2);
 2452:                         $key = &unescape($key);
 2453:                         next if ($key =~ /^error: 2 /);
 2454:                         $returnhash{$key}=&thaw_unescape($value);
 2455:                     }
 2456:                 }
 2457:             }
 2458:         }
 2459:     }
 2460:     return %returnhash;
 2461: }
 2462: 
 2463: sub inst_userrules {
 2464:     my ($udom,$check) = @_;
 2465:     my (%ruleshash,@ruleorder);
 2466:     if ($udom ne '') {
 2467:         my $homeserver=&domain($udom,'primary');
 2468:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2469:             my $response;
 2470:             if ($check eq 'id') {
 2471:                 $response=&reply('instidrules:'.&escape($udom),
 2472:                                  $homeserver);
 2473:             } elsif ($check eq 'email') {
 2474:                 $response=&reply('instemailrules:'.&escape($udom),
 2475:                                  $homeserver);
 2476:             } else {
 2477:                 $response=&reply('instuserrules:'.&escape($udom),
 2478:                                  $homeserver);
 2479:             }
 2480:             if (($response ne 'refused') && ($response ne 'error') && 
 2481:                 ($response ne 'unknown_cmd') && 
 2482:                 ($response ne 'no_such_host')) {
 2483:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2484:                 my @pairs=split(/\&/,$hashitems);
 2485:                 foreach my $item (@pairs) {
 2486:                     my ($key,$value)=split(/=/,$item,2);
 2487:                     $key = &unescape($key);
 2488:                     next if ($key =~ /^error: 2 /);
 2489:                     $ruleshash{$key}=&thaw_unescape($value);
 2490:                 }
 2491:                 my @esc_order = split(/\&/,$orderitems);
 2492:                 foreach my $item (@esc_order) {
 2493:                     push(@ruleorder,&unescape($item));
 2494:                 }
 2495:             }
 2496:         }
 2497:     }
 2498:     return (\%ruleshash,\@ruleorder);
 2499: }
 2500: 
 2501: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2502: 
 2503: sub get_domain_defaults {
 2504:     my ($domain,$ignore_cache) = @_;
 2505:     return if (($domain eq '') || ($domain eq 'public'));
 2506:     my $cachetime = 60*60*24;
 2507:     unless ($ignore_cache) {
 2508:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2509:         if (defined($cached)) {
 2510:             if (ref($result) eq 'HASH') {
 2511:                 return %{$result};
 2512:             }
 2513:         }
 2514:     }
 2515:     my %domdefaults;
 2516:     my %domconfig =
 2517:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2518:                                   'requestcourses','inststatus',
 2519:                                   'coursedefaults','usersessions',
 2520:                                   'requestauthor','selfenrollment',
 2521:                                   'coursecategories','ssl','autoenroll',
 2522:                                   'trust','helpsettings'],$domain);
 2523:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2524:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2525:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2526:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2527:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2528:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2529:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2530:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2531:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2532:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2533:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2534:     } else {
 2535:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2536:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2537:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2538:     }
 2539:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2540:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2542:         } else {
 2543:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2544:         }
 2545:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2546:         foreach my $item (@usertools) {
 2547:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2548:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2549:             }
 2550:         }
 2551:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2552:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2553:         }
 2554:     }
 2555:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2556:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2557:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2558:         }
 2559:     }
 2560:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2561:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2562:     }
 2563:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2564:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2565:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2566:         }
 2567:     }
 2568:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2569:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2570:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2571:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2572:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2573:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2574:         }
 2575:         foreach my $type (@coursetypes) {
 2576:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2577:                 unless ($type eq 'community') {
 2578:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2579:                 }
 2580:             }
 2581:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2582:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2583:             }
 2584:             if ($domdefaults{'postsubmit'} eq 'on') {
 2585:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2586:                     $domdefaults{$type.'postsubtimeout'} = 
 2587:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2588:                 }
 2589:             }
 2590:         }
 2591:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2592:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2593:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2594:                 if (@clonecodes) {
 2595:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2596:                 }
 2597:             }
 2598:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2599:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2600:         }
 2601:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2602:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2603:         } 
 2604:     }
 2605:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2606:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2607:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2608:         }
 2609:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2610:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2611:         }
 2612:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2613:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2614:         }
 2615:     }
 2616:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2617:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2618:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2619:                             'approval','limit');
 2620:             foreach my $type (@coursetypes) {
 2621:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2622:                     my @mgrdc = ();
 2623:                     foreach my $item (@settings) {
 2624:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2625:                             push(@mgrdc,$item);
 2626:                         }
 2627:                     }
 2628:                     if (@mgrdc) {
 2629:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2630:                     }
 2631:                 }
 2632:             }
 2633:         }
 2634:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2635:             foreach my $type (@coursetypes) {
 2636:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2637:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2638:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2639:                     }
 2640:                 }
 2641:             }
 2642:         }
 2643:     }
 2644:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2645:         $domdefaults{'catauth'} = 'std';
 2646:         $domdefaults{'catunauth'} = 'std';
 2647:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2648:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2649:         }
 2650:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2651:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2652:         }
 2653:     }
 2654:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2655:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2656:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2657:         }
 2658:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2659:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2660:         }
 2661:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2662:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2663:         }
 2664:     }
 2665:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2666:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2667:         foreach my $prefix (@prefixes) {
 2668:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2669:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2670:             }
 2671:         }
 2672:     }
 2673:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2674:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2675:     }
 2676:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2677:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2678:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2679:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2680:         }
 2681:     }
 2682:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2683:     return %domdefaults;
 2684: }
 2685: 
 2686: sub course_portal_url {
 2687:     my ($cnum,$cdom) = @_;
 2688:     my $chome = &homeserver($cnum,$cdom);
 2689:     my $hostname = &hostname($chome);
 2690:     my $protocol = $protocol{$chome};
 2691:     $protocol = 'http' if ($protocol ne 'https');
 2692:     my %domdefaults = &get_domain_defaults($cdom);
 2693:     my $firsturl;
 2694:     if ($domdefaults{'portal_def'}) {
 2695:         $firsturl = $domdefaults{'portal_def'};
 2696:     } else {
 2697:         $firsturl = $protocol.'://'.$hostname;
 2698:     }
 2699:     return $firsturl;
 2700: }
 2701: 
 2702: # --------------------------------------------------- Assign a key to a student
 2703: 
 2704: sub assign_access_key {
 2705: #
 2706: # a valid key looks like uname:udom#comments
 2707: # comments are being appended
 2708: #
 2709:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2710:     $kdom=
 2711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2712:     $knum=
 2713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2714:     $cdom=
 2715:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2716:     $cnum=
 2717:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2718:     $udom=$env{'user.name'} unless (defined($udom));
 2719:     $uname=$env{'user.domain'} unless (defined($uname));
 2720:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2721:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2722:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2723:                                                   # assigned to this person
 2724:                                                   # - this should not happen,
 2725:                                                   # unless something went wrong
 2726:                                                   # the first time around
 2727: # ready to assign
 2728:         $logentry=$1.'; '.$logentry;
 2729:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2730:                                                  $kdom,$knum) eq 'ok') {
 2731: # key now belongs to user
 2732: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2733:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2734:                 &appenv({'environment.'.$envkey => $ckey});
 2735:                 return 'ok';
 2736:             } else {
 2737:                 return 
 2738:   'error: Count not permanently assign key, will need to be re-entered later.';
 2739: 	    }
 2740:         } else {
 2741:             return 'error: Could not assign key, try again later.';
 2742:         }
 2743:     } elsif (!$existing{$ckey}) {
 2744: # the key does not exist
 2745: 	return 'error: The key does not exist';
 2746:     } else {
 2747: # the key is somebody else's
 2748: 	return 'error: The key is already in use';
 2749:     }
 2750: }
 2751: 
 2752: # ------------------------------------------ put an additional comment on a key
 2753: 
 2754: sub comment_access_key {
 2755: #
 2756: # a valid key looks like uname:udom#comments
 2757: # comments are being appended
 2758: #
 2759:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2760:     $cdom=
 2761:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2762:     $cnum=
 2763:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2764:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2765:     if ($existing{$ckey}) {
 2766:         $existing{$ckey}.='; '.$logentry;
 2767: # ready to assign
 2768:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2769:                                                  $cdom,$cnum) eq 'ok') {
 2770: 	    return 'ok';
 2771:         } else {
 2772: 	    return 'error: Count not store comment.';
 2773:         }
 2774:     } else {
 2775: # the key does not exist
 2776: 	return 'error: The key does not exist';
 2777:     }
 2778: }
 2779: 
 2780: # ------------------------------------------------------ Generate a set of keys
 2781: 
 2782: sub generate_access_keys {
 2783:     my ($number,$cdom,$cnum,$logentry)=@_;
 2784:     $cdom=
 2785:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2786:     $cnum=
 2787:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2788:     unless (&allowed('mky',$cdom)) { return 0; }
 2789:     unless (($cdom) && ($cnum)) { return 0; }
 2790:     if ($number>10000) { return 0; }
 2791:     sleep(2); # make sure don't get same seed twice
 2792:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2793:     my $total=0;
 2794:     for (my $i=1;$i<=$number;$i++) {
 2795:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2796:                   sprintf("%lx",int(100000*rand)).'-'.
 2797:                   sprintf("%lx",int(100000*rand));
 2798:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2799:        $newkey=~s/0/h/g; # and also 0 and O
 2800:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2801:        if ($existing{$newkey}) {
 2802:            $i--;
 2803:        } else {
 2804: 	  if (&put('accesskeys',
 2805:               { $newkey => '# generated '.localtime().
 2806:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2807:                            '; '.$logentry },
 2808: 		   $cdom,$cnum) eq 'ok') {
 2809:               $total++;
 2810: 	  }
 2811:        }
 2812:     }
 2813:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2814:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2815:     return $total;
 2816: }
 2817: 
 2818: # ------------------------------------------------------- Validate an accesskey
 2819: 
 2820: sub validate_access_key {
 2821:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2822:     $cdom=
 2823:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2824:     $cnum=
 2825:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2826:     $udom=$env{'user.domain'} unless (defined($udom));
 2827:     $uname=$env{'user.name'} unless (defined($uname));
 2828:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2829:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2830: }
 2831: 
 2832: # ------------------------------------- Find the section of student in a course
 2833: sub devalidate_getsection_cache {
 2834:     my ($udom,$unam,$courseid)=@_;
 2835:     my $hashid="$udom:$unam:$courseid";
 2836:     &devalidate_cache_new('getsection',$hashid);
 2837: }
 2838: 
 2839: sub courseid_to_courseurl {
 2840:     my ($courseid) = @_;
 2841:     #already url style courseid
 2842:     return $courseid if ($courseid =~ m{^/});
 2843: 
 2844:     if (exists($env{'course.'.$courseid.'.num'})) {
 2845: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2846: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2847: 	return "/$cdom/$cnum";
 2848:     }
 2849: 
 2850:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2851:     if (exists($courseinfo{'num'})) {
 2852: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2853:     }
 2854: 
 2855:     return undef;
 2856: }
 2857: 
 2858: sub getsection {
 2859:     my ($udom,$unam,$courseid)=@_;
 2860:     my $cachetime=1800;
 2861: 
 2862:     my $hashid="$udom:$unam:$courseid";
 2863:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2864:     if (defined($cached)) { return $result; }
 2865: 
 2866:     my %Pending; 
 2867:     my %Expired;
 2868:     #
 2869:     # Each role can either have not started yet (pending), be active, 
 2870:     #    or have expired.
 2871:     #
 2872:     # If there is an active role, we are done.
 2873:     #
 2874:     # If there is more than one role which has not started yet, 
 2875:     #     choose the one which will start sooner
 2876:     # If there is one role which has not started yet, return it.
 2877:     #
 2878:     # If there is more than one expired role, choose the one which ended last.
 2879:     # If there is a role which has expired, return it.
 2880:     #
 2881:     $courseid = &courseid_to_courseurl($courseid);
 2882:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2883:     foreach my $key (keys(%roleshash)) {
 2884:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2885:         my $section=$1;
 2886:         if ($key eq $courseid.'_st') { $section=''; }
 2887:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2888:         my $now=time;
 2889:         if (defined($end) && $end && ($now > $end)) {
 2890:             $Expired{$end}=$section;
 2891:             next;
 2892:         }
 2893:         if (defined($start) && $start && ($now < $start)) {
 2894:             $Pending{$start}=$section;
 2895:             next;
 2896:         }
 2897:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2898:     }
 2899:     #
 2900:     # Presumedly there will be few matching roles from the above
 2901:     # loop and the sorting time will be negligible.
 2902:     if (scalar(keys(%Pending))) {
 2903:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2904:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2905:     } 
 2906:     if (scalar(keys(%Expired))) {
 2907:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2908:         my $time = pop(@sorted);
 2909:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2910:     }
 2911:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2912: }
 2913: 
 2914: sub save_cache {
 2915:     &purge_remembered();
 2916:     #&Apache::loncommon::validate_page();
 2917:     undef(%env);
 2918:     undef($env_loaded);
 2919: }
 2920: 
 2921: my $to_remember=-1;
 2922: my %remembered;
 2923: my %accessed;
 2924: my $kicks=0;
 2925: my $hits=0;
 2926: sub make_key {
 2927:     my ($name,$id) = @_;
 2928:     if (length($id) > 65 
 2929: 	&& length(&escape($id)) > 200) {
 2930: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2931:     }
 2932:     return &escape($name.':'.$id);
 2933: }
 2934: 
 2935: sub devalidate_cache_new {
 2936:     my ($name,$id,$debug) = @_;
 2937:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2938:     my $remembered_id=$name.':'.$id;
 2939:     $id=&make_key($name,$id);
 2940:     $memcache->delete($id);
 2941:     delete($remembered{$remembered_id});
 2942:     delete($accessed{$remembered_id});
 2943: }
 2944: 
 2945: sub is_cached_new {
 2946:     my ($name,$id,$debug) = @_;
 2947:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2948:     if (exists($remembered{$remembered_id})) {
 2949: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2950: 	$accessed{$remembered_id}=[&gettimeofday()];
 2951: 	$hits++;
 2952: 	return ($remembered{$remembered_id},1);
 2953:     }
 2954:     $id=&make_key($name,$id);
 2955:     my $value = $memcache->get($id);
 2956:     if (!(defined($value))) {
 2957: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2958: 	return (undef,undef);
 2959:     }
 2960:     if ($value eq '__undef__') {
 2961: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2962: 	$value=undef;
 2963:     }
 2964:     &make_room($remembered_id,$value,$debug);
 2965:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2966:     return ($value,1);
 2967: }
 2968: 
 2969: sub do_cache_new {
 2970:     my ($name,$id,$value,$time,$debug) = @_;
 2971:     my $remembered_id=$name.':'.$id;
 2972:     $id=&make_key($name,$id);
 2973:     my $setvalue=$value;
 2974:     if (!defined($setvalue)) {
 2975: 	$setvalue='__undef__';
 2976:     }
 2977:     if (!defined($time) ) {
 2978: 	$time=600;
 2979:     }
 2980:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2981:     my $result = $memcache->set($id,$setvalue,$time);
 2982:     if (! $result) {
 2983: 	&logthis("caching of id -> $id  failed");
 2984: 	$memcache->disconnect_all();
 2985:     }
 2986:     # need to make a copy of $value
 2987:     &make_room($remembered_id,$value,$debug);
 2988:     return $value;
 2989: }
 2990: 
 2991: sub make_room {
 2992:     my ($remembered_id,$value,$debug)=@_;
 2993: 
 2994:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2995:                                     : $value;
 2996:     if ($to_remember<0) { return; }
 2997:     $accessed{$remembered_id}=[&gettimeofday()];
 2998:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2999:     my $to_kick;
 3000:     my $max_time=0;
 3001:     foreach my $other (keys(%accessed)) {
 3002: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3003: 	    $to_kick=$other;
 3004: 	    $max_time=&tv_interval($accessed{$other});
 3005: 	}
 3006:     }
 3007:     delete($remembered{$to_kick});
 3008:     delete($accessed{$to_kick});
 3009:     $kicks++;
 3010:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3011:     return;
 3012: }
 3013: 
 3014: sub purge_remembered {
 3015:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3016:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3017:     undef(%remembered);
 3018:     undef(%accessed);
 3019: }
 3020: # ------------------------------------- Read an entry from a user's environment
 3021: 
 3022: sub userenvironment {
 3023:     my ($udom,$unam,@what)=@_;
 3024:     my $items;
 3025:     foreach my $item (@what) {
 3026:         $items.=&escape($item).'&';
 3027:     }
 3028:     $items=~s/\&$//;
 3029:     my %returnhash=();
 3030:     my $uhome = &homeserver($unam,$udom);
 3031:     unless ($uhome eq 'no_host') {
 3032:         my @answer=split(/\&/, 
 3033:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3034:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3035:             return %returnhash;
 3036:         }
 3037:         my $i;
 3038:         for ($i=0;$i<=$#what;$i++) {
 3039: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3040:         }
 3041:     }
 3042:     return %returnhash;
 3043: }
 3044: 
 3045: # ---------------------------------------------------------- Get a studentphoto
 3046: sub studentphoto {
 3047:     my ($udom,$unam,$ext) = @_;
 3048:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3049:     if (defined($env{'request.course.id'})) {
 3050:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3051:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3052:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3053:             } else {
 3054:                 my ($result,$perm_reqd)=
 3055: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3056:                 if ($result eq 'ok') {
 3057:                     if (!($perm_reqd eq 'yes')) {
 3058:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3059:                     }
 3060:                 }
 3061:             }
 3062:         }
 3063:     } else {
 3064:         my ($result,$perm_reqd) = 
 3065: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3066:         if ($result eq 'ok') {
 3067:             if (!($perm_reqd eq 'yes')) {
 3068:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3069:             }
 3070:         }
 3071:     }
 3072:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3073: }
 3074: 
 3075: sub retrievestudentphoto {
 3076:     my ($udom,$unam,$ext,$type) = @_;
 3077:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3078:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3079:     if ($ret eq 'ok') {
 3080:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3081:         if ($type eq 'thumbnail') {
 3082:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3083:         }
 3084:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3085:         return $tokenurl;
 3086:     } else {
 3087:         if ($type eq 'thumbnail') {
 3088:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3089:         } else { 
 3090:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3091:         }
 3092:     }
 3093: }
 3094: 
 3095: # -------------------------------------------------------------------- New chat
 3096: 
 3097: sub chatsend {
 3098:     my ($newentry,$anon,$group)=@_;
 3099:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3100:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3101:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3102:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3103: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3104: 		   &escape($newentry)).':'.$group,$chome);
 3105: }
 3106: 
 3107: # ------------------------------------------ Find current version of a resource
 3108: 
 3109: sub getversion {
 3110:     my $fname=&clutter(shift);
 3111:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3112:     return &currentversion(&filelocation('',$fname));
 3113: }
 3114: 
 3115: sub currentversion {
 3116:     my $fname=shift;
 3117:     my $author=$fname;
 3118:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3119:     my ($udom,$uname)=split(/\//,$author);
 3120:     my $home=&homeserver($uname,$udom);
 3121:     if ($home eq 'no_host') { 
 3122:         return -1; 
 3123:     }
 3124:     my $answer=&reply("currentversion:$fname",$home);
 3125:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3126: 	return -1;
 3127:     }
 3128:     return $answer;
 3129: }
 3130: 
 3131: #
 3132: # Return special version number of resource if set by override, empty otherwise
 3133: #
 3134: sub usedversion {
 3135:     my $fname=shift;
 3136:     unless ($fname) { $fname=$env{'request.uri'}; }
 3137:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3138:     if ($urlversion) { return $urlversion; }
 3139:     return '';
 3140: }
 3141: 
 3142: # ----------------------------- Subscribe to a resource, return URL if possible
 3143: 
 3144: sub subscribe {
 3145:     my $fname=shift;
 3146:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3147:     $fname=~s/[\n\r]//g;
 3148:     my $author=$fname;
 3149:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3150:     my ($udom,$uname)=split(/\//,$author);
 3151:     my $home=homeserver($uname,$udom);
 3152:     if ($home eq 'no_host') {
 3153:         return 'not_found';
 3154:     }
 3155:     my $answer=reply("sub:$fname",$home);
 3156:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3157: 	$answer.=' by '.$home;
 3158:     }
 3159:     return $answer;
 3160: }
 3161:     
 3162: # -------------------------------------------------------------- Replicate file
 3163: 
 3164: sub repcopy {
 3165:     my $filename=shift;
 3166:     $filename=~s/\/+/\//g;
 3167:     my $londocroot = $perlvar{'lonDocRoot'};
 3168:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3169:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3170:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3171: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3172: 	return &repcopy_userfile($filename);
 3173:     }
 3174:     $filename=~s/[\n\r]//g;
 3175:     my $transname="$filename.in.transfer";
 3176: # FIXME: this should flock
 3177:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3178:     my $remoteurl=subscribe($filename);
 3179:     if ($remoteurl =~ /^con_lost by/) {
 3180: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3181:            return 'unavailable';
 3182:     } elsif ($remoteurl eq 'not_found') {
 3183: 	   #&logthis("Subscribe returned not_found: $filename");
 3184: 	   return 'not_found';
 3185:     } elsif ($remoteurl =~ /^rejected by/) {
 3186: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3187:            return 'forbidden';
 3188:     } elsif ($remoteurl eq 'directory') {
 3189:            return 'ok';
 3190:     } else {
 3191:         my $author=$filename;
 3192:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3193:         my ($udom,$uname)=split(/\//,$author);
 3194:         my $home=homeserver($uname,$udom);
 3195:         unless ($home eq $perlvar{'lonHostID'}) {
 3196:            my @parts=split(/\//,$filename);
 3197:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3198:            if ($path ne "$londocroot/res") {
 3199:                &logthis("Malconfiguration for replication: $filename");
 3200: 	       return 'bad_request';
 3201:            }
 3202:            my $count;
 3203:            for ($count=5;$count<$#parts;$count++) {
 3204:                $path.="/$parts[$count]";
 3205:                if ((-e $path)!=1) {
 3206: 		   mkdir($path,0777);
 3207:                }
 3208:            }
 3209:            my $request=new HTTP::Request('GET',"$remoteurl");
 3210:            my $response;
 3211:            if ($remoteurl =~ m{/raw/}) {
 3212:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3213:            } else {
 3214:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3215:            }
 3216:            if ($response->is_error()) {
 3217: 	       unlink($transname);
 3218:                my $message=$response->status_line;
 3219:                &logthis("<font color=\"blue\">WARNING:"
 3220:                        ." LWP get: $message: $filename</font>");
 3221:                return 'unavailable';
 3222:            } else {
 3223: 	       if ($remoteurl!~/\.meta$/) {
 3224:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3225:                   my $mresponse;
 3226:                   if ($remoteurl =~ m{/raw/}) {
 3227:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3228:                   } else {
 3229:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3230:                   }
 3231:                   if ($mresponse->is_error()) {
 3232: 		      unlink($filename.'.meta');
 3233:                       &logthis(
 3234:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3235:                   }
 3236: 	       }
 3237:                rename($transname,$filename);
 3238:                return 'ok';
 3239:            }
 3240:        }
 3241:     }
 3242: }
 3243: 
 3244: # ------------------------------------------------ Get server side include body
 3245: sub ssi_body {
 3246:     my ($filelink,%form)=@_;
 3247:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3248:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3249:     }
 3250:     my $output='';
 3251:     my $response;
 3252:     if ($filelink=~/^https?\:/) {
 3253:        ($output,$response)=&externalssi($filelink);
 3254:     } else {
 3255:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3256:        $filelink .= 'inhibitmenu=yes';
 3257:        ($output,$response)=&ssi($filelink,%form);
 3258:     }
 3259:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3260:     $output=~s/^.*?\<body[^\>]*\>//si;
 3261:     $output=~s/\<\/body\s*\>.*?$//si;
 3262:     if (wantarray) {
 3263:         return ($output, $response);
 3264:     } else {
 3265:         return $output;
 3266:     }
 3267: }
 3268: 
 3269: # --------------------------------------------------------- Server Side Include
 3270: 
 3271: sub absolute_url {
 3272:     my ($host_name) = @_;
 3273:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3274:     if ($host_name eq '') {
 3275: 	$host_name = $ENV{'SERVER_NAME'};
 3276:     }
 3277:     return $protocol.$host_name;
 3278: }
 3279: 
 3280: #
 3281: #   Server side include.
 3282: # Parameters:
 3283: #  fn     Possibly encrypted resource name/id.
 3284: #  form   Hash that describes how the rendering should be done
 3285: #         and other things.
 3286: # Returns:
 3287: #   Scalar context: The content of the response.
 3288: #   Array context:  2 element list of the content and the full response object.
 3289: #     
 3290: sub ssi {
 3291: 
 3292:     my ($fn,%form)=@_;
 3293:     my $request;
 3294: 
 3295:     $form{'no_update_last_known'}=1;
 3296:     &Apache::lonenc::check_encrypt(\$fn);
 3297:     if (%form) {
 3298:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3299:       $request->content(join('&',map { 
 3300:             my $name = escape($_);
 3301:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3302:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3303:             : &escape($form{$_}) );    
 3304:         } keys(%form)));
 3305:     } else {
 3306:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3307:     }
 3308: 
 3309:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3310:     my $lonhost = $perlvar{'lonHostID'};
 3311:     my $islocal;
 3312:     if (($env{'request.course.id'}) &&
 3313:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3314:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3315:         ($form{'grade_symb'} ne '') &&
 3316:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3317:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3318:         $islocal = 1;
 3319:     }
 3320:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3321:                                                 '','','',$islocal);
 3322: 
 3323:     if (wantarray) {
 3324: 	return ($response->content, $response);
 3325:     } else {
 3326: 	return $response->content;
 3327:     }
 3328: }
 3329: 
 3330: sub externalssi {
 3331:     my ($url)=@_;
 3332:     my $request=new HTTP::Request('GET',$url);
 3333:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3334:     if (wantarray) {
 3335:         return ($response->content, $response);
 3336:     } else {
 3337:         return $response->content;
 3338:     }
 3339: }
 3340: 
 3341: 
 3342: # If the local copy of a replicated resource is outdated, trigger a  
 3343: # connection from the homeserver to flush the delayed queue. If no update 
 3344: # happens, remove local copies of outdated resource (and corresponding
 3345: # metadata file).
 3346: 
 3347: sub remove_stale_resfile {
 3348:     my ($url) = @_;
 3349:     my $removed;
 3350:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3351:         my $audom = $1;
 3352:         my $auname = $2;
 3353:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3354:             my $homeserver = &homeserver($auname,$audom);
 3355:             unless (($homeserver eq 'no_host') ||
 3356:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3357:                 my $fname = &filelocation('',$url);
 3358:                 if (-e $fname) {
 3359:                     my $protocol = $protocol{$homeserver};
 3360:                     $protocol = 'http' if ($protocol ne 'https');
 3361:                     my $hostname = &hostname($homeserver);
 3362:                     if ($hostname) {
 3363:                         my $uri = &declutter($url);
 3364:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3365:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3366:                         if ($response->is_success()) {
 3367:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3368:                             my $locmodtime = (stat($fname))[9];
 3369:                             if ($locmodtime < $remmodtime) {
 3370:                                 my $stale;
 3371:                                 my $answer = &reply('pong',$homeserver);
 3372:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3373:                                     sleep(0.2);
 3374:                                     $locmodtime = (stat($fname))[9];
 3375:                                     if ($locmodtime < $remmodtime) {
 3376:                                         my $posstransfer = $fname.'.in.transfer';
 3377:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3378:                                             $removed = 1;
 3379:                                         } else {
 3380:                                             $stale = 1;
 3381:                                         }
 3382:                                     } else {
 3383:                                         $removed = 1;
 3384:                                     }
 3385:                                 } else {
 3386:                                     $stale = 1;
 3387:                                 }
 3388:                                 if ($stale) {
 3389:                                     unlink($fname);
 3390:                                     if ($uri!~/\.meta$/) {
 3391:                                         unlink($fname.'.meta');
 3392:                                     }
 3393:                                     &reply("unsub:$fname",$homeserver);
 3394:                                     $removed = 1;
 3395:                                 }
 3396:                             }
 3397:                         }
 3398:                     }
 3399:                 }
 3400:             }
 3401:         }
 3402:     }
 3403:     return $removed;
 3404: }
 3405: 
 3406: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3407: 
 3408: sub allowuploaded {
 3409:     my ($srcurl,$url)=@_;
 3410:     $url=&clutter(&declutter($url));
 3411:     my $dir=$url;
 3412:     $dir=~s/\/[^\/]+$//;
 3413:     my %httpref=();
 3414:     my $httpurl=&hreflocation('',$url);
 3415:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3416:     &Apache::lonnet::appenv(\%httpref);
 3417: }
 3418: 
 3419: #
 3420: # Determine if the current user should be able to edit a particular resource,
 3421: # when viewing in course context.
 3422: # (a) When viewing resource used to determine if "Edit" item is included in 
 3423: #     Functions.
 3424: # (b) When displaying folder contents in course editor, used to determine if
 3425: #     "Edit" link will be displayed alongside resource.
 3426: #
 3427: #  input: six args -- filename (decluttered), course number, course domain,
 3428: #                   url, symb (if registered) and group (if this is a group
 3429: #                   item -- e.g., bulletin board, group page etc.).
 3430: #  output: array of five scalars -- 
 3431: #          $cfile -- url for file editing if editable on current server
 3432: #          $home -- homeserver of resource (i.e., for author if published,
 3433: #                                           or course if uploaded.).
 3434: #          $switchserver --  1 if server switch will be needed.
 3435: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3436: #          $forceview -- 1 if icon/link should be to go to view mode
 3437: #
 3438: 
 3439: sub can_edit_resource {
 3440:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3441:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3442: #
 3443: # For aboutme pages user can only edit his/her own.
 3444: #
 3445:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3446:         my ($sdom,$sname) = ($1,$2);
 3447:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3448:             $home = $env{'user.home'};
 3449:             $cfile = $resurl;
 3450:             if ($env{'form.forceedit'}) {
 3451:                 $forceview = 1;
 3452:             } else {
 3453:                 $forceedit = 1;
 3454:             }
 3455:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3456:         } else {
 3457:             return;
 3458:         }
 3459:     }
 3460: 
 3461:     if ($env{'request.course.id'}) {
 3462:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3463:         if ($group ne '') {
 3464: # if this is a group homepage or group bulletin board, check group privs
 3465:             my $allowed = 0;
 3466:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3467:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3468:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3469:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3470:                     $allowed = 1;
 3471:                 }
 3472:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3473:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3474:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3475:                     $allowed = 1;
 3476:                 }
 3477:             }
 3478:             if ($allowed) {
 3479:                 $home=&homeserver($cnum,$cdom);
 3480:                 if ($env{'form.forceedit'}) {
 3481:                     $forceview = 1;
 3482:                 } else {
 3483:                     $forceedit = 1;
 3484:                 }
 3485:                 $cfile = $resurl;
 3486:             } else {
 3487:                 return;
 3488:             }
 3489:         } else {
 3490:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3491:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3492:                     return;
 3493:                 }
 3494:             } elsif (!$crsedit) {
 3495: #
 3496: # No edit allowed where CC has switched to student role.
 3497: #
 3498:                 return;
 3499:             }
 3500:         }
 3501:     }
 3502: 
 3503:     if ($file ne '') {
 3504:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3505:             if (&is_course_upload($file,$cnum,$cdom)) {
 3506:                 $uploaded = 1;
 3507:                 $incourse = 1;
 3508:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3509:                     $cfile = &hreflocation('',$file);
 3510:                     if ($env{'form.forceedit'}) {
 3511:                         $forceview = 1;
 3512:                     } else {
 3513:                         $forceedit = 1;
 3514:                     }
 3515:                 }
 3516:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3517:                 $incourse = 1;
 3518:                 if ($env{'form.forceedit'}) {
 3519:                     $forceview = 1;
 3520:                 } else {
 3521:                     $forceedit = 1;
 3522:                 }
 3523:                 $cfile = $resurl;
 3524:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3525:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3526:                     $incourse = 1;
 3527:                     if ($env{'form.forceedit'}) {
 3528:                         $forceview = 1;
 3529:                     } else {
 3530:                         $forceedit = 1;
 3531:                     }
 3532:                     $cfile = $resurl;
 3533:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3534:                     $incourse = 1;
 3535:                     $cfile = $resurl.'/smpedit';
 3536:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3537:                     $incourse = 1;
 3538:                     if ($env{'form.forceedit'}) {
 3539:                         $forceview = 1;
 3540:                     } else {
 3541:                         $forceedit = 1;
 3542:                     }
 3543:                     $cfile = $resurl;
 3544:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3545:                     $incourse = 1;
 3546:                     if ($env{'form.forceedit'}) {
 3547:                         $forceview = 1;
 3548:                     } else {
 3549:                         $forceedit = 1;
 3550:                     }
 3551:                     $cfile = $resurl;
 3552:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3553:                     $incourse = 1;
 3554:                     if ($env{'form.forceedit'}) {
 3555:                         $forceview = 1;
 3556:                     } else {
 3557:                         $forceedit = 1;
 3558:                     }
 3559:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3560:                 }
 3561:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3562:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3563:                 if (&is_on_map($template)) { 
 3564:                     $incourse = 1;
 3565:                     $forceview = 1;
 3566:                     $cfile = $template;
 3567:                 }
 3568:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3569:                     $incourse = 1;
 3570:                     if ($env{'form.forceedit'}) {
 3571:                         $forceview = 1;
 3572:                     } else {
 3573:                         $forceedit = 1;
 3574:                     }
 3575:                     $cfile = $resurl;
 3576:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3577:                 $incourse = 1;
 3578:                 if ($env{'form.forceedit'}) {
 3579:                     $forceview = 1;
 3580:                 } else {
 3581:                     $forceedit = 1;
 3582:                 }
 3583:                 $cfile = $resurl;
 3584:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3585:                 $incourse = 1;
 3586:                 $forceview = 1;
 3587:                 if ($symb) {
 3588:                     my ($map,$id,$res)=&decode_symb($symb);
 3589:                     $env{'request.symb'} = $symb;
 3590:                     $cfile = &clutter($res);
 3591:                 } else {
 3592:                     $cfile = $env{'form.suppurl'};
 3593:                     my $escfile = &unescape($cfile);
 3594:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3595:                         $cfile = '/adm/wrapper'.$escfile;
 3596:                     } else {
 3597:                         $escfile =~ s{^http://}{};
 3598:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3599:                     }
 3600:                 }
 3601:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3602:                 if ($env{'form.forceedit'}) {
 3603:                     $forceview = 1;
 3604:                 } else {
 3605:                     $forceedit = 1;
 3606:                 }
 3607:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3608:             }
 3609:         }
 3610:         if ($uploaded || $incourse) {
 3611:             $home=&homeserver($cnum,$cdom);
 3612:         } elsif ($file !~ m{/$}) {
 3613:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3614:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3615:             # Check that the user has permission to edit this resource
 3616:             my $setpriv = 1;
 3617:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3618:             if (defined($cfudom)) {
 3619:                 $home=&homeserver($cfuname,$cfudom);
 3620:                 $cfile=$file;
 3621:             }
 3622:         }
 3623:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3624:             (($home ne '') && ($home ne 'no_host'))) {
 3625:             my @ids=&current_machine_ids();
 3626:             unless (grep(/^\Q$home\E$/,@ids)) {
 3627:                 $switchserver=1;
 3628:             }
 3629:         }
 3630:     }
 3631:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3632: }
 3633: 
 3634: sub is_course_upload {
 3635:     my ($file,$cnum,$cdom) = @_;
 3636:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3637:     $uploadpath =~ s{^\/}{};
 3638:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3639:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3640:         return 1;
 3641:     }
 3642:     return;
 3643: }
 3644: 
 3645: sub in_course {
 3646:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3647:     if ($hideprivileged) {
 3648:         my $skipuser;
 3649:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3650:         my @possdoms = ($cdom);  
 3651:         if ($coursehash{'checkforpriv'}) { 
 3652:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3653:         }
 3654:         if (&privileged($uname,$udom,\@possdoms)) {
 3655:             $skipuser = 1;
 3656:             if ($coursehash{'nothideprivileged'}) {
 3657:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3658:                     my $user;
 3659:                     if ($item =~ /:/) {
 3660:                         $user = $item;
 3661:                     } else {
 3662:                         $user = join(':',split(/[\@]/,$item));
 3663:                     }
 3664:                     if ($user eq $uname.':'.$udom) {
 3665:                         undef($skipuser);
 3666:                         last;
 3667:                     }
 3668:                 }
 3669:             }
 3670:             if ($skipuser) {
 3671:                 return 0;
 3672:             }
 3673:         }
 3674:     }
 3675:     $type ||= 'any';
 3676:     if (!defined($cdom) || !defined($cnum)) {
 3677:         my $cid  = $env{'request.course.id'};
 3678:         $cdom = $env{'course.'.$cid.'.domain'};
 3679:         $cnum = $env{'course.'.$cid.'.num'};
 3680:     }
 3681:     my $typesref;
 3682:     if (($type eq 'any') || ($type eq 'all')) {
 3683:         $typesref = ['active','previous','future'];
 3684:     } elsif ($type eq 'previous' || $type eq 'future') {
 3685:         $typesref = [$type];
 3686:     }
 3687:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3688:                               $typesref,undef,[$cdom]);
 3689:     my ($tmp) = keys(%roles);
 3690:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3691:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3692:     if (@course_roles > 0) {
 3693:         return 1;
 3694:     }
 3695:     return 0;
 3696: }
 3697: 
 3698: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3699: # input: action, courseID, current domain, intended
 3700: #        path to file, source of file, instruction to parse file for objects,
 3701: #        ref to hash for embedded objects,
 3702: #        ref to hash for codebase of java objects.
 3703: #        reference to scalar to accommodate mime type determined
 3704: #          from File::MMagic if $parser = parse.
 3705: #
 3706: # output: url to file (if action was uploaddoc), 
 3707: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3708: #
 3709: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3710: # course.
 3711: #
 3712: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3713: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3714: #          course's home server.
 3715: #
 3716: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3717: #          be copied from $source (current location) to 
 3718: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3719: #         and will then be copied to
 3720: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3721: #         course's home server.
 3722: #
 3723: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3724: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3725: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3726: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3727: #         in course's home server.
 3728: #
 3729: 
 3730: sub process_coursefile {
 3731:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3732:         $mimetype)=@_;
 3733:     my $fetchresult;
 3734:     my $home=&homeserver($docuname,$docudom);
 3735:     if ($action eq 'propagate') {
 3736:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3737: 			     $home);
 3738:     } else {
 3739:         my $fpath = '';
 3740:         my $fname = $file;
 3741:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3742:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3743:         my $filepath = &build_filepath($fpath);
 3744:         if ($action eq 'copy') {
 3745:             if ($source eq '') {
 3746:                 $fetchresult = 'no source file';
 3747:                 return $fetchresult;
 3748:             } else {
 3749:                 my $destination = $filepath.'/'.$fname;
 3750:                 rename($source,$destination);
 3751:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3752:                                  $home);
 3753:             }
 3754:         } elsif ($action eq 'uploaddoc') {
 3755:             open(my $fh,'>',$filepath.'/'.$fname);
 3756:             print $fh $env{'form.'.$source};
 3757:             close($fh);
 3758:             if ($parser eq 'parse') {
 3759:                 my $mm = new File::MMagic;
 3760:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3761:                 if ($type eq 'text/html') {
 3762:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3763:                     unless ($parse_result eq 'ok') {
 3764:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3765:                     }
 3766:                 }
 3767:                 if (ref($mimetype)) {
 3768:                     $$mimetype = $type;
 3769:                 } 
 3770:             }
 3771:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3772:                                  $home);
 3773:             if ($fetchresult eq 'ok') {
 3774:                 return '/uploaded/'.$fpath.'/'.$fname;
 3775:             } else {
 3776:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3777:                         ' to host '.$home.': '.$fetchresult);
 3778:                 return '/adm/notfound.html';
 3779:             }
 3780:         }
 3781:     }
 3782:     unless ( $fetchresult eq 'ok') {
 3783:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3784:              ' to host '.$home.': '.$fetchresult);
 3785:     }
 3786:     return $fetchresult;
 3787: }
 3788: 
 3789: sub build_filepath {
 3790:     my ($fpath) = @_;
 3791:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3792:     unless ($fpath eq '') {
 3793:         my @parts=split('/',$fpath);
 3794:         foreach my $part (@parts) {
 3795:             $filepath.= '/'.$part;
 3796:             if ((-e $filepath)!=1) {
 3797:                 mkdir($filepath,0777);
 3798:             }
 3799:         }
 3800:     }
 3801:     return $filepath;
 3802: }
 3803: 
 3804: sub store_edited_file {
 3805:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3806:     my $file = $primary_url;
 3807:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3808:     my $fpath = '';
 3809:     my $fname = $file;
 3810:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3811:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3812:     my $filepath = &build_filepath($fpath);
 3813:     open(my $fh,'>',$filepath.'/'.$fname);
 3814:     print $fh $content;
 3815:     close($fh);
 3816:     my $home=&homeserver($docuname,$docudom);
 3817:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3818: 			  $home);
 3819:     if ($$fetchresult eq 'ok') {
 3820:         return '/uploaded/'.$fpath.'/'.$fname;
 3821:     } else {
 3822:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3823: 		 ' to host '.$home.': '.$$fetchresult);
 3824:         return '/adm/notfound.html';
 3825:     }
 3826: }
 3827: 
 3828: sub clean_filename {
 3829:     my ($fname,$args)=@_;
 3830: # Replace Windows backslashes by forward slashes
 3831:     $fname=~s/\\/\//g;
 3832:     if (!$args->{'keep_path'}) {
 3833:         # Get rid of everything but the actual filename
 3834: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3835:     }
 3836: # Replace spaces by underscores
 3837:     $fname=~s/\s+/\_/g;
 3838: # Replace all other weird characters by nothing
 3839:     $fname=~s{[^/\w\.\-]}{}g;
 3840: # Replace all .\d. sequences with _\d. so they no longer look like version
 3841: # numbers
 3842:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3843:     return $fname;
 3844: }
 3845: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3846: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3847: # image with the same aspect ratio as the original, but with dimensions which do 
 3848: # not exceed $resizewidth and $resizeheight.
 3849:  
 3850: sub resizeImage {
 3851:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3852:     my $ima = Image::Magick->new;
 3853:     my $resized;
 3854:     if (-e $img_path) {
 3855:         $ima->Read($img_path);
 3856:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3857:             my $width = $ima->Get('width');
 3858:             my $height = $ima->Get('height');
 3859:             if ($width > $resizewidth) {
 3860: 	        my $factor = $width/$resizewidth;
 3861:                 my $newheight = $height/$factor;
 3862:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3863:                 $resized = 1;
 3864:             }
 3865:         }
 3866:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3867:             my $width = $ima->Get('width');
 3868:             my $height = $ima->Get('height');
 3869:             if ($height > $resizeheight) {
 3870:                 my $factor = $height/$resizeheight;
 3871:                 my $newwidth = $width/$factor;
 3872:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3873:                 $resized = 1;
 3874:             }
 3875:         }
 3876:         if ($resized) {
 3877:             $ima->Write($img_path);
 3878:         }
 3879:     }
 3880:     return;
 3881: }
 3882: 
 3883: # --------------- Take an uploaded file and put it into the userfiles directory
 3884: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3885: #                    the desired filename is in $env{"form.$formname.filename"}
 3886: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3887: #                                    canceloverwrite, or ''. 
 3888: #                   if 'coursedoc': upload to the current course
 3889: #                   if 'existingfile': write file to tmp/overwrites directory 
 3890: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3891: #                   $context is passed as argument to &finishuserfileupload
 3892: #        $subdir - directory in userfile to store the file into
 3893: #        $parser - instruction to parse file for objects ($parser = parse)    
 3894: #        $allfiles - reference to hash for embedded objects
 3895: #        $codebase - reference to hash for codebase of java objects
 3896: #        $desuname - username for permanent storage of uploaded file
 3897: #        $dsetudom - domain for permanaent storage of uploaded file
 3898: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3899: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3900: #        $resizewidth - width (pixels) to which to resize uploaded image
 3901: #        $resizeheight - height (pixels) to which to resize uploaded image
 3902: #        $mimetype - reference to scalar to accommodate mime type determined
 3903: #                    from File::MMagic.
 3904: # 
 3905: # output: url of file in userspace, or error: <message> 
 3906: #             or /adm/notfound.html if failure to upload occurse
 3907: 
 3908: sub userfileupload {
 3909:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3910:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3911:     if (!defined($subdir)) { $subdir='unknown'; }
 3912:     my $fname=$env{'form.'.$formname.'.filename'};
 3913:     $fname=&clean_filename($fname);
 3914:     # See if there is anything left
 3915:     unless ($fname) { return 'error: no uploaded file'; }
 3916:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3917:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3918:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3919:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3920:         my $now = time;
 3921:         my $filepath;
 3922:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3923:              $filepath = 'tmp/helprequests/'.$now;
 3924:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3925:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3926:                          '_'.$env{'user.domain'}.'/pending';
 3927:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3928:             my ($docuname,$docudom);
 3929:             if ($destudom =~ /^$match_domain$/) {
 3930:                 $docudom = $destudom;
 3931:             } else {
 3932:                 $docudom = $env{'user.domain'};
 3933:             }
 3934:             if ($destuname =~ /^$match_username$/) {
 3935:                 $docuname = $destuname;
 3936:             } else {
 3937:                 $docuname = $env{'user.name'};
 3938:             }
 3939:             if (exists($env{'form.group'})) {
 3940:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3941:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3942:             }
 3943:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3944:             if ($context eq 'canceloverwrite') {
 3945:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3946:                 if (-e  $tempfile) {
 3947:                     my @info = stat($tempfile);
 3948:                     if ($info[9] eq $env{'form.timestamp'}) {
 3949:                         unlink($tempfile);
 3950:                     }
 3951:                 }
 3952:                 return;
 3953:             }
 3954:         }
 3955:         # Create the directory if not present
 3956:         my @parts=split(/\//,$filepath);
 3957:         my $fullpath = $perlvar{'lonDaemons'};
 3958:         for (my $i=0;$i<@parts;$i++) {
 3959:             $fullpath .= '/'.$parts[$i];
 3960:             if ((-e $fullpath)!=1) {
 3961:                 mkdir($fullpath,0777);
 3962:             }
 3963:         }
 3964:         open(my $fh,'>',$fullpath.'/'.$fname);
 3965:         print $fh $env{'form.'.$formname};
 3966:         close($fh);
 3967:         if ($context eq 'existingfile') {
 3968:             my @info = stat($fullpath.'/'.$fname);
 3969:             return ($fullpath.'/'.$fname,$info[9]);
 3970:         } else {
 3971:             return $fullpath.'/'.$fname;
 3972:         }
 3973:     }
 3974:     if ($subdir eq 'scantron') {
 3975:         $fname = 'scantron_orig_'.$fname;
 3976:     } else {
 3977:         $fname="$subdir/$fname";
 3978:     }
 3979:     if ($context eq 'coursedoc') {
 3980: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3981: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3982:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3983:             return &finishuserfileupload($docuname,$docudom,
 3984: 					 $formname,$fname,$parser,$allfiles,
 3985: 					 $codebase,$thumbwidth,$thumbheight,
 3986:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3987:         } else {
 3988:             if ($env{'form.folder'}) {
 3989:                 $fname=$env{'form.folder'}.'/'.$fname;
 3990:             }
 3991:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3992: 				       $fname,$formname,$parser,
 3993: 				       $allfiles,$codebase,$mimetype);
 3994:         }
 3995:     } elsif (defined($destuname)) {
 3996:         my $docuname=$destuname;
 3997:         my $docudom=$destudom;
 3998: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3999: 				     $parser,$allfiles,$codebase,
 4000:                                      $thumbwidth,$thumbheight,
 4001:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4002:     } else {
 4003:         my $docuname=$env{'user.name'};
 4004:         my $docudom=$env{'user.domain'};
 4005:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4006:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4007:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4008:         }
 4009: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4010: 				     $parser,$allfiles,$codebase,
 4011:                                      $thumbwidth,$thumbheight,
 4012:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4013:     }
 4014: }
 4015: 
 4016: sub finishuserfileupload {
 4017:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4018:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4019:     my $path=$docudom.'/'.$docuname.'/';
 4020:     my $filepath=$perlvar{'lonDocRoot'};
 4021:   
 4022:     my ($fnamepath,$file,$fetchthumb);
 4023:     $file=$fname;
 4024:     if ($fname=~m|/|) {
 4025:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4026: 	$path.=$fnamepath.'/';
 4027:     }
 4028:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4029:     my $count;
 4030:     for ($count=4;$count<=$#parts;$count++) {
 4031:         $filepath.="/$parts[$count]";
 4032:         if ((-e $filepath)!=1) {
 4033: 	    mkdir($filepath,0777);
 4034:         }
 4035:     }
 4036: 
 4037: # Save the file
 4038:     {
 4039: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4040: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4041: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4042: 	    return '/adm/notfound.html';
 4043: 	}
 4044:         if ($context eq 'overwrite') {
 4045:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4046:             my $target = $filepath.'/'.$file;
 4047:             if (-e $source) {
 4048:                 my @info = stat($source);
 4049:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4050:                     unless (&File::Copy::move($source,$target)) {
 4051:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4052:                         return "Moving from $source failed";
 4053:                     }
 4054:                 } else {
 4055:                     return "Temporary file: $source had unexpected date/time for last modification";
 4056:                 }
 4057:             } else {
 4058:                 return "Temporary file: $source missing";
 4059:             }
 4060:         } elsif (!print FH ($env{'form.'.$formname})) {
 4061: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4062: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4063: 	    return '/adm/notfound.html';
 4064: 	}
 4065: 	close(FH);
 4066:         if ($resizewidth && $resizeheight) {
 4067:             my $mm = new File::MMagic;
 4068:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4069:             if ($mime_type =~ m{^image/}) {
 4070: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4071:             }  
 4072: 	}
 4073:     }
 4074:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4075:         if (ref($mimetype)) {
 4076:             if ($$mimetype eq '') {
 4077:                 my $mm = new File::MMagic;
 4078:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4079:                 $$mimetype = $type;
 4080:             }
 4081:         }
 4082:     }
 4083:     if ($parser eq 'parse') {
 4084:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4085:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4086:                                                        $allfiles,$codebase);
 4087:             unless ($parse_result eq 'ok') {
 4088:                 &logthis('Failed to parse '.$filepath.$file.
 4089: 	   	         ' for embedded media: '.$parse_result); 
 4090:             }
 4091:         }
 4092:     }
 4093:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4094:         my $input = $filepath.'/'.$file;
 4095:         my $output = $filepath.'/'.'tn-'.$file;
 4096:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4097:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4098:         system({$args[0]} @args);
 4099:         if (-e $filepath.'/'.'tn-'.$file) {
 4100:             $fetchthumb  = 1; 
 4101:         }
 4102:     }
 4103:  
 4104: # Notify homeserver to grep it
 4105: #
 4106:     my $docuhome=&homeserver($docuname,$docudom);	
 4107:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4108:     if ($fetchresult eq 'ok') {
 4109:         if ($fetchthumb) {
 4110:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4111:             if ($thumbresult ne 'ok') {
 4112:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4113:                          $docuhome.': '.$thumbresult);
 4114:             }
 4115:         }
 4116: #
 4117: # Return the URL to it
 4118:         return '/uploaded/'.$path.$file;
 4119:     } else {
 4120:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4121: 		 ': '.$fetchresult);
 4122:         return '/adm/notfound.html';
 4123:     }
 4124: }
 4125: 
 4126: sub extract_embedded_items {
 4127:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4128:     my @state = ();
 4129:     my (%lastids,%related,%shockwave,%flashvars);
 4130:     my %javafiles = (
 4131:                       codebase => '',
 4132:                       code => '',
 4133:                       archive => ''
 4134:                     );
 4135:     my %mediafiles = (
 4136:                       src => '',
 4137:                       movie => '',
 4138:                      );
 4139:     my $p;
 4140:     if ($content) {
 4141:         $p = HTML::LCParser->new($content);
 4142:     } else {
 4143:         $p = HTML::LCParser->new($fullpath);
 4144:     }
 4145:     while (my $t=$p->get_token()) {
 4146: 	if ($t->[0] eq 'S') {
 4147: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4148: 	    push(@state, $tagname);
 4149:             if (lc($tagname) eq 'allow') {
 4150:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4151:             }
 4152: 	    if (lc($tagname) eq 'img') {
 4153: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4154: 	    }
 4155: 	    if (lc($tagname) eq 'a') {
 4156:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4157:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4158:                 }
 4159: 	    }
 4160:             if (lc($tagname) eq 'script') {
 4161:                 my $src;
 4162:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4163:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4164:                 } else {
 4165:                     if ($attr->{'src'} ne '') {
 4166:                         $src = $attr->{'src'};
 4167:                         &add_filetype($allfiles,$src,'src');
 4168:                     }
 4169:                 }
 4170:                 my $text = $p->get_trimmed_text();
 4171:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4172:                     my @swfargs = split(/,/,$1);
 4173:                     foreach my $item (@swfargs) {
 4174:                         $item =~ s/["']//g;
 4175:                         $item =~ s/^\s+//;
 4176:                         $item =~ s/\s+$//;
 4177:                     }
 4178:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4179:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4180:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4181:                         } else {
 4182:                             $related{$swfargs[0]} = [$swfargs[2]];
 4183:                         }
 4184:                     }
 4185:                 }
 4186:             }
 4187:             if (lc($tagname) eq 'link') {
 4188:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4189:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4190:                 }
 4191:             }
 4192: 	    if (lc($tagname) eq 'object' ||
 4193: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4194: 		foreach my $item (keys(%javafiles)) {
 4195: 		    $javafiles{$item} = '';
 4196: 		}
 4197:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4198:                     $lastids{lc($tagname)} = $attr->{'id'};
 4199:                 }
 4200: 	    }
 4201: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4202: 		my $name = lc($attr->{'name'});
 4203: 		foreach my $item (keys(%javafiles)) {
 4204: 		    if ($name eq $item) {
 4205: 			$javafiles{$item} = $attr->{'value'};
 4206: 			last;
 4207: 		    }
 4208: 		}
 4209:                 my $pathfrom;
 4210: 		foreach my $item (keys(%mediafiles)) {
 4211: 		    if ($name eq $item) {
 4212:                         $pathfrom = $attr->{'value'};
 4213:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4214: 			&add_filetype($allfiles,$pathfrom,$name);
 4215: 			last;
 4216: 		    }
 4217: 		}
 4218:                 if ($name eq 'flashvars') {
 4219:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4220:                 }
 4221:                 if ($pathfrom ne '') {
 4222:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4223:                                          $pathfrom);
 4224:                 }
 4225: 	    }
 4226: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4227: 		foreach my $item (keys(%javafiles)) {
 4228: 		    if ($attr->{$item}) {
 4229: 			$javafiles{$item} = $attr->{$item};
 4230: 			last;
 4231: 		    }
 4232: 		}
 4233: 		foreach my $item (keys(%mediafiles)) {
 4234: 		    if ($attr->{$item}) {
 4235: 			&add_filetype($allfiles,$attr->{$item},$item);
 4236: 			last;
 4237: 		    }
 4238: 		}
 4239:                 if (lc($tagname) eq 'embed') {
 4240:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4241:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4242:                                              $attr->{'src'});
 4243:                     }
 4244:                 }
 4245: 	    }
 4246:             if (lc($tagname) eq 'iframe') {
 4247:                 my $src = $attr->{'src'} ;
 4248:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4249:                     &add_filetype($allfiles,$src,'src');
 4250:                 } elsif ($src =~ m{^/}) {
 4251:                     if ($env{'request.course.id'}) {
 4252:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4253:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4254:                         my $url = &hreflocation('',$fullpath);
 4255:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4256:                             my $relpath = $1;
 4257:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4258:                                 &add_filetype($allfiles,$1,'src');
 4259:                             }
 4260:                         }
 4261:                     }
 4262:                 }
 4263:             }
 4264:             if ($t->[4] =~ m{/>$}) {
 4265:                 pop(@state);
 4266:             }
 4267: 	} elsif ($t->[0] eq 'E') {
 4268: 	    my ($tagname) = ($t->[1]);
 4269: 	    if ($javafiles{'codebase'} ne '') {
 4270: 		$javafiles{'codebase'} .= '/';
 4271: 	    }  
 4272: 	    if (lc($tagname) eq 'applet' ||
 4273: 		lc($tagname) eq 'object' ||
 4274: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4275: 		) {
 4276: 		foreach my $item (keys(%javafiles)) {
 4277: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4278: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4279: 			&add_filetype($allfiles,$file,$item);
 4280: 		    }
 4281: 		}
 4282: 	    } 
 4283: 	    pop @state;
 4284: 	}
 4285:     }
 4286:     foreach my $id (sort(keys(%flashvars))) {
 4287:         if ($shockwave{$id} ne '') {
 4288:             my @pairs = split(/\&/,$flashvars{$id});
 4289:             foreach my $pair (@pairs) {
 4290:                 my ($key,$value) = split(/\=/,$pair);
 4291:                 if ($key eq 'thumb') {
 4292:                     &add_filetype($allfiles,$value,$key);
 4293:                 } elsif ($key eq 'content') {
 4294:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4295:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4296:                     if ($ext ne '') {
 4297:                         &add_filetype($allfiles,$path.$value,$ext);
 4298:                     }
 4299:                 }
 4300:             }
 4301:         }
 4302:     }
 4303:     return 'ok';
 4304: }
 4305: 
 4306: sub add_filetype {
 4307:     my ($allfiles,$file,$type)=@_;
 4308:     if (exists($allfiles->{$file})) {
 4309: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4310: 	    push(@{$allfiles->{$file}}, &escape($type));
 4311: 	}
 4312:     } else {
 4313: 	@{$allfiles->{$file}} = (&escape($type));
 4314:     }
 4315: }
 4316: 
 4317: sub embedded_dependency {
 4318:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4319:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4320:         if (($identifier ne '') &&
 4321:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4322:             ($pathfrom ne '')) {
 4323:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4324:             foreach my $dep (@{$related->{$identifier}}) {
 4325:                 &add_filetype($allfiles,$path.$dep,'object');
 4326:             }
 4327:         }
 4328:     }
 4329:     return;
 4330: }
 4331: 
 4332: sub removeuploadedurl {
 4333:     my ($url)=@_;	
 4334:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4335:     return &removeuserfile($uname,$udom,$fname);
 4336: }
 4337: 
 4338: sub removeuserfile {
 4339:     my ($docuname,$docudom,$fname)=@_;
 4340:     my $home=&homeserver($docuname,$docudom);    
 4341:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4342:     if ($result eq 'ok') {	
 4343:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4344:             my $metafile = $fname.'.meta';
 4345:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4346: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4347:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4348:             my $sqlresult = 
 4349:                 &update_portfolio_table($docuname,$docudom,$file,
 4350:                                         'portfolio_metadata',$group,
 4351:                                         'delete');
 4352:         }
 4353:     }
 4354:     return $result;
 4355: }
 4356: 
 4357: sub mkdiruserfile {
 4358:     my ($docuname,$docudom,$dir)=@_;
 4359:     my $home=&homeserver($docuname,$docudom);
 4360:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4361: }
 4362: 
 4363: sub renameuserfile {
 4364:     my ($docuname,$docudom,$old,$new)=@_;
 4365:     my $home=&homeserver($docuname,$docudom);
 4366:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4367:                         &escape("$old").':'.&escape("$new"),$home);
 4368:     if ($result eq 'ok') {
 4369:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4370:             my $oldmeta = $old.'.meta';
 4371:             my $newmeta = $new.'.meta';
 4372:             my $metaresult = 
 4373:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4374: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4375:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4376:             my $sqlresult = 
 4377:                 &update_portfolio_table($docuname,$docudom,$file,
 4378:                                         'portfolio_metadata',$group,
 4379:                                         'delete');
 4380:         }
 4381:     }
 4382:     return $result;
 4383: }
 4384: 
 4385: # ------------------------------------------------------------------------- Log
 4386: 
 4387: sub log {
 4388:     my ($dom,$nam,$hom,$what)=@_;
 4389:     return critical("log:$dom:$nam:$what",$hom);
 4390: }
 4391: 
 4392: # ------------------------------------------------------------------ Course Log
 4393: #
 4394: # This routine flushes several buffers of non-mission-critical nature
 4395: #
 4396: 
 4397: sub flushcourselogs {
 4398:     &logthis('Flushing log buffers');
 4399: #
 4400: # course logs
 4401: # This is a log of all transactions in a course, which can be used
 4402: # for data mining purposes
 4403: #
 4404: # It also collects the courseid database, which lists last transaction
 4405: # times and course titles for all courseids
 4406: #
 4407:     my %courseidbuffer=();
 4408:     foreach my $crsid (keys(%courselogs)) {
 4409:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4410: 		          &escape($courselogs{$crsid}),
 4411: 		          $coursehombuf{$crsid}) eq 'ok') {
 4412: 	    delete $courselogs{$crsid};
 4413:         } else {
 4414:             &logthis('Failed to flush log buffer for '.$crsid);
 4415:             if (length($courselogs{$crsid})>40000) {
 4416:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4417:                         " exceeded maximum size, deleting.</font>");
 4418:                delete $courselogs{$crsid};
 4419:             }
 4420:         }
 4421:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4422:             'description' => $coursedescrbuf{$crsid},
 4423:             'inst_code'    => $courseinstcodebuf{$crsid},
 4424:             'type'        => $coursetypebuf{$crsid},
 4425:             'owner'       => $courseownerbuf{$crsid},
 4426:         };
 4427:     }
 4428: #
 4429: # Write course id database (reverse lookup) to homeserver of courses 
 4430: # Is used in pickcourse
 4431: #
 4432:     foreach my $crs_home (keys(%courseidbuffer)) {
 4433:         my $response = &courseidput(&host_domain($crs_home),
 4434:                                     $courseidbuffer{$crs_home},
 4435:                                     $crs_home,'timeonly');
 4436:     }
 4437: #
 4438: # File accesses
 4439: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4440: #
 4441:     foreach my $entry (keys(%accesshash)) {
 4442:         if ($entry =~ /___count$/) {
 4443:             my ($dom,$name);
 4444:             ($dom,$name,undef)=
 4445: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4446:             if (! defined($dom) || $dom eq '' || 
 4447:                 ! defined($name) || $name eq '') {
 4448:                 my $cid = $env{'request.course.id'};
 4449:                 $dom  = $env{'request.'.$cid.'.domain'};
 4450:                 $name = $env{'request.'.$cid.'.num'};
 4451:             }
 4452:             my $value = $accesshash{$entry};
 4453:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4454:             my %temphash=($url => $value);
 4455:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4456:             if ($result eq 'ok') {
 4457:                 delete $accesshash{$entry};
 4458:             }
 4459:         } else {
 4460:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4461:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4462:             my %temphash=($entry => $accesshash{$entry});
 4463:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4464:                 delete $accesshash{$entry};
 4465:             }
 4466:         }
 4467:     }
 4468: #
 4469: # Roles
 4470: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4471: #
 4472:     foreach my $entry (keys(%userrolehash)) {
 4473:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4474: 	    split(/\:/,$entry);
 4475:         if (&Apache::lonnet::put('nohist_userroles',
 4476:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4477:                 $rudom,$runame) eq 'ok') {
 4478: 	    delete $userrolehash{$entry};
 4479:         }
 4480:     }
 4481: #
 4482: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4483: #
 4484:     my %domrolebuffer = ();
 4485:     foreach my $entry (keys(%domainrolehash)) {
 4486:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4487:         if ($domrolebuffer{$rudom}) {
 4488:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4489:                       '='.&escape($domainrolehash{$entry});
 4490:         } else {
 4491:             $domrolebuffer{$rudom}.=&escape($entry).
 4492:                       '='.&escape($domainrolehash{$entry});
 4493:         }
 4494:         delete $domainrolehash{$entry};
 4495:     }
 4496:     foreach my $dom (keys(%domrolebuffer)) {
 4497: 	my %servers;
 4498: 	if (defined(&domain($dom,'primary'))) {
 4499: 	    my $primary=&domain($dom,'primary');
 4500: 	    my $hostname=&hostname($primary);
 4501: 	    $servers{$primary} = $hostname;
 4502: 	} else { 
 4503: 	    %servers = &get_servers($dom,'library');
 4504: 	}
 4505: 	foreach my $tryserver (keys(%servers)) {
 4506: 	    if (&reply('domroleput:'.$dom.':'.
 4507: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4508: 		last;
 4509: 	    } else {  
 4510: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4511: 	    }
 4512:         }
 4513:     }
 4514:     $dumpcount++;
 4515: }
 4516: 
 4517: sub courselog {
 4518:     my $what=shift;
 4519:     $what=time.':'.$what;
 4520:     unless ($env{'request.course.id'}) { return ''; }
 4521:     $coursedombuf{$env{'request.course.id'}}=
 4522:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4523:     $coursenumbuf{$env{'request.course.id'}}=
 4524:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4525:     $coursehombuf{$env{'request.course.id'}}=
 4526:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4527:     $coursedescrbuf{$env{'request.course.id'}}=
 4528:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4529:     $courseinstcodebuf{$env{'request.course.id'}}=
 4530:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4531:     $courseownerbuf{$env{'request.course.id'}}=
 4532:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4533:     $coursetypebuf{$env{'request.course.id'}}=
 4534:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4535:     if (defined $courselogs{$env{'request.course.id'}}) {
 4536: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4537:     } else {
 4538: 	$courselogs{$env{'request.course.id'}}.=$what;
 4539:     }
 4540:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4541: 	&flushcourselogs();
 4542:     }
 4543: }
 4544: 
 4545: sub courseacclog {
 4546:     my $fnsymb=shift;
 4547:     unless ($env{'request.course.id'}) { return ''; }
 4548:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4549:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4550:         $what.=':POST';
 4551:         # FIXME: Probably ought to escape things....
 4552: 	foreach my $key (keys(%env)) {
 4553:             if ($key=~/^form\.(.*)/) {
 4554:                 my $formitem = $1;
 4555:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4556:                     $what.=':'.$formitem.'='.$env{$key};
 4557:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4558:                     $what.=':'.$formitem.'='.$env{$key};
 4559:                 }
 4560:             }
 4561:         }
 4562:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4563:         # FIXME: We should not be depending on a form parameter that someone
 4564:         # editing lonsearchcat.pm might change in the future.
 4565:         if ($env{'form.phase'} eq 'course_search') {
 4566:             $what.= ':POST';
 4567:             # FIXME: Probably ought to escape things....
 4568:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4569:                                  'crsdiscuss') {
 4570:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4571:             }
 4572:         }
 4573:     }
 4574:     &courselog($what);
 4575: }
 4576: 
 4577: sub countacc {
 4578:     my $url=&declutter(shift);
 4579:     return if (! defined($url) || $url eq '');
 4580:     unless ($env{'request.course.id'}) { return ''; }
 4581: #
 4582: # Mark that this url was used in this course
 4583: #
 4584:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4585: #
 4586: # Increase the access count for this resource in this child process
 4587: #
 4588:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4589:     $accesshash{$key}++;
 4590: }
 4591: 
 4592: sub linklog {
 4593:     my ($from,$to)=@_;
 4594:     $from=&declutter($from);
 4595:     $to=&declutter($to);
 4596:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4597:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4598: }
 4599: 
 4600: sub statslog {
 4601:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4602:     if ($users<2) { return; }
 4603:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4604:             'course'       => $env{'request.course.id'},
 4605:             'sections'     => '"all"',
 4606:             'num_students' => $users,
 4607:             'part'         => $part,
 4608:             'symb'         => $symb,
 4609:             'mean_tries'   => $av_attempts,
 4610:             'deg_of_diff'  => $degdiff});
 4611:     foreach my $key (keys(%dynstore)) {
 4612:         $accesshash{$key}=$dynstore{$key};
 4613:     }
 4614: }
 4615:   
 4616: sub userrolelog {
 4617:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4618:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4619:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4620:        $userrolehash
 4621:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4622:                     =$tend.':'.$tstart;
 4623:     }
 4624:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4625:        $userrolehash
 4626:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4627:                     =$tend.':'.$tstart;
 4628:     }
 4629:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4630:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4631:        $domainrolehash
 4632:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4633:                     = $tend.':'.$tstart;
 4634:     }
 4635: }
 4636: 
 4637: sub courserolelog {
 4638:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4639:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4640:         my $cdom = $1;
 4641:         my $cnum = $2;
 4642:         my $sec = $3;
 4643:         my $namespace = 'rolelog';
 4644:         my %storehash = (
 4645:                            role    => $trole,
 4646:                            start   => $tstart,
 4647:                            end     => $tend,
 4648:                            selfenroll => $selfenroll,
 4649:                            context    => $context,
 4650:                         );
 4651:         if ($trole eq 'gr') {
 4652:             $namespace = 'groupslog';
 4653:             $storehash{'group'} = $sec;
 4654:         } else {
 4655:             $storehash{'section'} = $sec;
 4656:         }
 4657:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4658:                    $domain,$cnum,$cdom);
 4659:         if (($trole ne 'st') || ($sec ne '')) {
 4660:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4661:         }
 4662:     }
 4663:     return;
 4664: }
 4665: 
 4666: sub domainrolelog {
 4667:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4668:     if ($area =~ m{^/($match_domain)/$}) {
 4669:         my $cdom = $1;
 4670:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4671:         my $namespace = 'rolelog';
 4672:         my %storehash = (
 4673:                            role    => $trole,
 4674:                            start   => $tstart,
 4675:                            end     => $tend,
 4676:                            context => $context,
 4677:                         );
 4678:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4679:                    $domain,$domconfiguser,$cdom);
 4680:     }
 4681:     return;
 4682: 
 4683: }
 4684: 
 4685: sub coauthorrolelog {
 4686:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4687:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4688:         my $audom = $1;
 4689:         my $auname = $2;
 4690:         my $namespace = 'rolelog';
 4691:         my %storehash = (
 4692:                            role    => $trole,
 4693:                            start   => $tstart,
 4694:                            end     => $tend,
 4695:                            context => $context,
 4696:                         );
 4697:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4698:                    $domain,$auname,$audom);
 4699:     }
 4700:     return;
 4701: }
 4702: 
 4703: sub get_course_adv_roles {
 4704:     my ($cid,$codes) = @_;
 4705:     $cid=$env{'request.course.id'} unless (defined($cid));
 4706:     my %coursehash=&coursedescription($cid);
 4707:     my $crstype = &Apache::loncommon::course_type($cid);
 4708:     my %nothide=();
 4709:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4710:         if ($user !~ /:/) {
 4711: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4712:         } else {
 4713:             $nothide{$user}=1;
 4714:         }
 4715:     }
 4716:     my @possdoms = ($coursehash{'domain'});
 4717:     if ($coursehash{'checkforpriv'}) {
 4718:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4719:     }
 4720:     my %returnhash=();
 4721:     my %dumphash=
 4722:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4723:     my $now=time;
 4724:     my %privileged;
 4725:     foreach my $entry (keys(%dumphash)) {
 4726: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4727:         if (($tstart) && ($tstart<0)) { next; }
 4728:         if (($tend) && ($tend<$now)) { next; }
 4729:         if (($tstart) && ($now<$tstart)) { next; }
 4730:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4731: 	if ($username eq '' || $domain eq '') { next; }
 4732:         if ((&privileged($username,$domain,\@possdoms)) &&
 4733:             (!$nothide{$username.':'.$domain})) { next; }
 4734: 	if ($role eq 'cr') { next; }
 4735:         if ($codes) {
 4736:             if ($section) { $role .= ':'.$section; }
 4737:             if ($returnhash{$role}) {
 4738:                 $returnhash{$role}.=','.$username.':'.$domain;
 4739:             } else {
 4740:                 $returnhash{$role}=$username.':'.$domain;
 4741:             }
 4742:         } else {
 4743:             my $key=&plaintext($role,$crstype);
 4744:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4745:             if ($returnhash{$key}) {
 4746: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4747:             } else {
 4748:                 $returnhash{$key}=$username.':'.$domain;
 4749:             }
 4750:         }
 4751:     }
 4752:     return %returnhash;
 4753: }
 4754: 
 4755: sub get_my_roles {
 4756:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4757:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4758:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4759:     my (%dumphash,%nothide);
 4760:     if ($context eq 'userroles') {
 4761:         %dumphash = &dump('roles',$udom,$uname);
 4762:     } else {
 4763:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4764:         if ($hidepriv) {
 4765:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4766:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4767:                 if ($user !~ /:/) {
 4768:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4769:                 } else {
 4770:                     $nothide{$user} = 1;
 4771:                 }
 4772:             }
 4773:         }
 4774:     }
 4775:     my %returnhash=();
 4776:     my $now=time;
 4777:     my %privileged;
 4778:     foreach my $entry (keys(%dumphash)) {
 4779:         my ($role,$tend,$tstart);
 4780:         if ($context eq 'userroles') {
 4781:             next if ($entry =~ /^rolesdef/);
 4782: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4783:         } else {
 4784:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4785:         }
 4786:         if (($tstart) && ($tstart<0)) { next; }
 4787:         my $status = 'active';
 4788:         if (($tend) && ($tend<=$now)) {
 4789:             $status = 'previous';
 4790:         } 
 4791:         if (($tstart) && ($now<$tstart)) {
 4792:             $status = 'future';
 4793:         }
 4794:         if (ref($types) eq 'ARRAY') {
 4795:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4796:                 next;
 4797:             } 
 4798:         } else {
 4799:             if ($status ne 'active') {
 4800:                 next;
 4801:             }
 4802:         }
 4803:         my ($rolecode,$username,$domain,$section,$area);
 4804:         if ($context eq 'userroles') {
 4805:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4806:             (undef,$domain,$username,$section) = split(/\//,$area);
 4807:         } else {
 4808:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4809:         }
 4810:         if (ref($roledoms) eq 'ARRAY') {
 4811:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4812:                 next;
 4813:             }
 4814:         }
 4815:         if (ref($roles) eq 'ARRAY') {
 4816:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4817:                 if ($role =~ /^cr\//) {
 4818:                     if (!grep(/^cr$/,@{$roles})) {
 4819:                         next;
 4820:                     }
 4821:                 } elsif ($role =~ /^gr\//) {
 4822:                     if (!grep(/^gr$/,@{$roles})) {
 4823:                         next;
 4824:                     }
 4825:                 } else {
 4826:                     next;
 4827:                 }
 4828:             }
 4829:         }
 4830:         if ($hidepriv) {
 4831:             my @privroles = ('dc','su');
 4832:             if ($context eq 'userroles') {
 4833:                 next if (grep(/^\Q$role\E$/,@privroles));
 4834:             } else {
 4835:                 my $possdoms = [$domain];
 4836:                 if (ref($roledoms) eq 'ARRAY') {
 4837:                    push(@{$possdoms},@{$roledoms}); 
 4838:                 }
 4839:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4840:                     if (!$nothide{$username.':'.$domain}) {
 4841:                         next;
 4842:                     }
 4843:                 }
 4844:             }
 4845:         }
 4846:         if ($withsec) {
 4847:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4848:                 $tstart.':'.$tend;
 4849:         } else {
 4850:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4851:         }
 4852:     }
 4853:     return %returnhash;
 4854: }
 4855: 
 4856: sub get_all_adhocroles {
 4857:     my ($dom) = @_;
 4858:     my @roles_by_num = ();
 4859:     my %domdefaults = &get_domain_defaults($dom);
 4860:     my (%description,%access_in_dom,%access_info);
 4861:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4862:         my $count = 0;
 4863:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4864:         my %ordered;
 4865:         foreach my $role (sort(keys(%domcurrent))) {
 4866:             my ($order,$desc,$access_in_dom);
 4867:             if (ref($domcurrent{$role}) eq 'HASH') {
 4868:                 $order = $domcurrent{$role}{'order'};
 4869:                 $desc = $domcurrent{$role}{'desc'};
 4870:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4871:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4872:             }
 4873:             if ($order eq '') {
 4874:                 $order = $count;
 4875:             }
 4876:             $ordered{$order} = $role;
 4877:             if ($desc ne '') {
 4878:                 $description{$role} = $desc;
 4879:             } else {
 4880:                 $description{$role}= $role;
 4881:             }
 4882:             $count++;
 4883:         }
 4884:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4885:             push(@roles_by_num,$ordered{$item});
 4886:         }
 4887:     }
 4888:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4889: }
 4890: 
 4891: sub get_my_adhocroles {
 4892:     my ($cid,$checkreg) = @_;
 4893:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4894:     if ($env{'request.course.id'} eq $cid) {
 4895:         $cdom = $env{'course.'.$cid.'.domain'};
 4896:         $cnum = $env{'course.'.$cid.'.num'};
 4897:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4898:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4899:         $cdom = $1;
 4900:         $cnum = $2;
 4901:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4902:                                      $cdom,$cnum);
 4903:     }
 4904:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4905:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4906:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4907:         if ($rosterhash{$user} ne '') {
 4908:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4909:             return ([],{}) if ($type eq 'auto');
 4910:         }
 4911:     }
 4912:     if (($cdom ne '') && ($cnum ne ''))  {
 4913:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4914:             my $then=$env{'user.login.time'};
 4915:             my $update=$env{'user.update.time'};
 4916:             if (!$update) {
 4917:                 $update = $then;
 4918:             }
 4919:             my @liveroles;
 4920:             foreach my $role ('dh','da') {
 4921:                 if ($env{"user.role.$role./$cdom/"}) {
 4922:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4923:                     my $limit = $update;
 4924:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4925:                         $limit = $then;
 4926:                     }
 4927:                     my $activerole = 1;
 4928:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4929:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4930:                     if ($activerole) {
 4931:                         push(@liveroles,$role);
 4932:                     }
 4933:                 }
 4934:             }
 4935:             if (@liveroles) {
 4936:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4937:                     my ($accessref,$accessinfo,%access_in_dom);
 4938:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4939:                     if (ref($roles_by_num) eq 'ARRAY') {
 4940:                         if (@{$roles_by_num}) {
 4941:                             my %settings;
 4942:                             if ($env{'request.course.id'} eq $cid) {
 4943:                                 foreach my $envkey (keys(%env)) {
 4944:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4945:                                         $settings{$1} = $env{$envkey};
 4946:                                     }
 4947:                                 }
 4948:                             } else {
 4949:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4950:                             }
 4951:                             my %setincrs;
 4952:                             if ($settings{'internal.adhocaccess'}) {
 4953:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4954:                             }
 4955:                             my @statuses;
 4956:                             if ($env{'environment.inststatus'}) {
 4957:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4958:                             }
 4959:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4960:                             if (ref($accessref) eq 'HASH') {
 4961:                                 %access_in_dom = %{$accessref};
 4962:                             }
 4963:                             foreach my $role (@{$roles_by_num}) {
 4964:                                 my ($curraccess,@okstatus,@personnel);
 4965:                                 if ($setincrs{$role}) {
 4966:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4967:                                     if ($curraccess eq 'status') {
 4968:                                         @okstatus = split(/\&/,$rest);
 4969:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4970:                                         @personnel = split(/\&/,$rest);
 4971:                                     }
 4972:                                 } else {
 4973:                                     $curraccess = $access_in_dom{$role};
 4974:                                     if (ref($accessinfo) eq 'HASH') {
 4975:                                         if ($curraccess eq 'status') {
 4976:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4977:                                                 @okstatus = @{$accessinfo->{$role}};
 4978:                                             }
 4979:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4980:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4981:                                                 @personnel = @{$accessinfo->{$role}};
 4982:                                             }
 4983:                                         }
 4984:                                     }
 4985:                                 }
 4986:                                 if ($curraccess eq 'none') {
 4987:                                     next;
 4988:                                 } elsif ($curraccess eq 'all') {
 4989:                                     push(@possroles,$role);
 4990:                                 } elsif ($curraccess eq 'dh') {
 4991:                                     if (grep(/^dh$/,@liveroles)) {
 4992:                                         push(@possroles,$role);
 4993:                                     } else {
 4994:                                         next;
 4995:                                     }
 4996:                                 } elsif ($curraccess eq 'da') {
 4997:                                     if (grep(/^da$/,@liveroles)) {
 4998:                                         push(@possroles,$role);
 4999:                                     } else {
 5000:                                         next;
 5001:                                     }
 5002:                                 } elsif ($curraccess eq 'status') {
 5003:                                     if (@okstatus) {
 5004:                                         if (!@statuses) {
 5005:                                             if (grep(/^default$/,@okstatus)) {
 5006:                                                 push(@possroles,$role);
 5007:                                             }
 5008:                                         } else {
 5009:                                             foreach my $status (@okstatus) {
 5010:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5011:                                                     push(@possroles,$role);
 5012:                                                     last;
 5013:                                                 }
 5014:                                             }
 5015:                                         }
 5016:                                     }
 5017:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5018:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5019:                                         if ($curraccess eq 'exc') {
 5020:                                             push(@possroles,$role);
 5021:                                         }
 5022:                                     } elsif ($curraccess eq 'inc') {
 5023:                                         push(@possroles,$role);
 5024:                                     }
 5025:                                 }
 5026:                             }
 5027:                         }
 5028:                     }
 5029:                 }
 5030:             }
 5031:         }
 5032:     }
 5033:     unless (ref($description) eq 'HASH') {
 5034:         if (ref($roles_by_num) eq 'ARRAY') {
 5035:             my %desc;
 5036:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5037:             $description = \%desc;
 5038:         } else {
 5039:             $description = {};
 5040:         }
 5041:     }
 5042:     return (\@possroles,$description);
 5043: }
 5044: 
 5045: # ----------------------------------------------------- Frontpage Announcements
 5046: #
 5047: #
 5048: 
 5049: sub postannounce {
 5050:     my ($server,$text)=@_;
 5051:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5052:     unless ($text=~/\w/) { $text=''; }
 5053:     return &reply('setannounce:'.&escape($text),$server);
 5054: }
 5055: 
 5056: sub getannounce {
 5057: 
 5058:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5059: 	my $announcement='';
 5060: 	while (my $line = <$fh>) { $announcement .= $line; }
 5061: 	close($fh);
 5062: 	if ($announcement=~/\w/) { 
 5063: 	    return 
 5064:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5065:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5066: 	} else {
 5067: 	    return '';
 5068: 	}
 5069:     } else {
 5070: 	return '';
 5071:     }
 5072: }
 5073: 
 5074: # ---------------------------------------------------------- Course ID routines
 5075: # Deal with domain's nohist_courseid.db files
 5076: #
 5077: 
 5078: sub courseidput {
 5079:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5080:     return unless (ref($storehash) eq 'HASH');
 5081:     my $outcome;
 5082:     if ($caller eq 'timeonly') {
 5083:         my $cids = '';
 5084:         foreach my $item (keys(%$storehash)) {
 5085:             $cids.=&escape($item).'&';
 5086:         }
 5087:         $cids=~s/\&$//;
 5088:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5089:                           $coursehome);       
 5090:     } else {
 5091:         my $items = '';
 5092:         foreach my $item (keys(%$storehash)) {
 5093:             $items.= &escape($item).'='.
 5094:                      &freeze_escape($$storehash{$item}).'&';
 5095:         }
 5096:         $items=~s/\&$//;
 5097:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5098:                           $coursehome);
 5099:     }
 5100:     if ($outcome eq 'unknown_cmd') {
 5101:         my $what;
 5102:         foreach my $cid (keys(%$storehash)) {
 5103:             $what .= &escape($cid).'=';
 5104:             foreach my $item ('description','inst_code','owner','type') {
 5105:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5106:             }
 5107:             $what =~ s/\:$/&/;
 5108:         }
 5109:         $what =~ s/\&$//;  
 5110:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5111:     } else {
 5112:         return $outcome;
 5113:     }
 5114: }
 5115: 
 5116: sub courseiddump {
 5117:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5118:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5119:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5120:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5121:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5122:     my $as_hash = 1;
 5123:     my %returnhash;
 5124:     if (!$domfilter) { $domfilter=''; }
 5125:     my %libserv = &all_library();
 5126:     foreach my $tryserver (keys(%libserv)) {
 5127:         if ( (  $hostidflag == 1 
 5128: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5129: 	     || (!defined($hostidflag)) ) {
 5130: 
 5131: 	    if (($domfilter eq '') ||
 5132: 		(&host_domain($tryserver) eq $domfilter)) {
 5133:                 my $rep;
 5134:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5135:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5136:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5137:                                 &escape($descfilter), &escape($instcodefilter), 
 5138:                                 &escape($ownerfilter), &escape($coursefilter),
 5139:                                 &escape($typefilter), &escape($regexp_ok), 
 5140:                                 $as_hash, &escape($selfenrollonly), 
 5141:                                 &escape($catfilter), $showhidden, $caller, 
 5142:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5143:                                 &escape($createdbefore), &escape($createdafter), 
 5144:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5145:                                 $reqcrsdom,&escape($reqinstcode))));
 5146:                 } else {
 5147:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5148:                              $sincefilter.':'.&escape($descfilter).':'.
 5149:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5150:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5151:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5152:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5153:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5154:                              &escape($cc_clone).':'.$cloneonly.':'.
 5155:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5156:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5157:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5158:                 }
 5159:                      
 5160:                 my @pairs=split(/\&/,$rep);
 5161:                 foreach my $item (@pairs) {
 5162:                     my ($key,$value)=split(/\=/,$item,2);
 5163:                     $key = &unescape($key);
 5164:                     next if ($key =~ /^error: 2 /);
 5165:                     my $result = &thaw_unescape($value);
 5166:                     if (ref($result) eq 'HASH') {
 5167:                         $returnhash{$key}=$result;
 5168:                     } else {
 5169:                         my @responses = split(/:/,$value);
 5170:                         my @items = ('description','inst_code','owner','type');
 5171:                         for (my $i=0; $i<@responses; $i++) {
 5172:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5173:                         }
 5174:                     }
 5175:                 }
 5176:             }
 5177:         }
 5178:     }
 5179:     return %returnhash;
 5180: }
 5181: 
 5182: sub courselastaccess {
 5183:     my ($cdom,$cnum,$hostidref) = @_;
 5184:     my %returnhash;
 5185:     if ($cdom && $cnum) {
 5186:         my $chome = &homeserver($cnum,$cdom);
 5187:         if ($chome ne 'no_host') {
 5188:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5189:             &extract_lastaccess(\%returnhash,$rep);
 5190:         }
 5191:     } else {
 5192:         if (!$cdom) { $cdom=''; }
 5193:         my %libserv = &all_library();
 5194:         foreach my $tryserver (keys(%libserv)) {
 5195:             if (ref($hostidref) eq 'ARRAY') {
 5196:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5197:             } 
 5198:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5199:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5200:                 &extract_lastaccess(\%returnhash,$rep);
 5201:             }
 5202:         }
 5203:     }
 5204:     return %returnhash;
 5205: }
 5206: 
 5207: sub extract_lastaccess {
 5208:     my ($returnhash,$rep) = @_;
 5209:     if (ref($returnhash) eq 'HASH') {
 5210:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5211:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5212:                  $rep eq '') {
 5213:             my @pairs=split(/\&/,$rep);
 5214:             foreach my $item (@pairs) {
 5215:                 my ($key,$value)=split(/\=/,$item,2);
 5216:                 $key = &unescape($key);
 5217:                 next if ($key =~ /^error: 2 /);
 5218:                 $returnhash->{$key} = &thaw_unescape($value);
 5219:             }
 5220:         }
 5221:     }
 5222:     return;
 5223: }
 5224: 
 5225: # ---------------------------------------------------------- DC e-mail
 5226: 
 5227: sub dcmailput {
 5228:     my ($domain,$msgid,$message,$server)=@_;
 5229:     my $status = &Apache::lonnet::critical(
 5230:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5231:        &escape($message),$server);
 5232:     return $status;
 5233: }
 5234: 
 5235: sub dcmaildump {
 5236:     my ($dom,$startdate,$enddate,$senders) = @_;
 5237:     my %returnhash=();
 5238: 
 5239:     if (defined(&domain($dom,'primary'))) {
 5240:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5241:                                                          &escape($enddate).':';
 5242: 	my @esc_senders=map { &escape($_)} @$senders;
 5243: 	$cmd.=&escape(join('&',@esc_senders));
 5244: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5245:             my ($key,$value) = split(/\=/,$line,2);
 5246:             if (($key) && ($value)) {
 5247:                 $returnhash{&unescape($key)} = &unescape($value);
 5248:             }
 5249:         }
 5250:     }
 5251:     return %returnhash;
 5252: }
 5253: # ---------------------------------------------------------- Domain roles
 5254: 
 5255: sub get_domain_roles {
 5256:     my ($dom,$roles,$startdate,$enddate)=@_;
 5257:     if ((!defined($startdate)) || ($startdate eq '')) {
 5258:         $startdate = '.';
 5259:     }
 5260:     if ((!defined($enddate)) || ($enddate eq '')) {
 5261:         $enddate = '.';
 5262:     }
 5263:     my $rolelist;
 5264:     if (ref($roles) eq 'ARRAY') {
 5265:         $rolelist = join('&',@{$roles});
 5266:     }
 5267:     my %personnel = ();
 5268: 
 5269:     my %servers = &get_servers($dom,'library');
 5270:     foreach my $tryserver (keys(%servers)) {
 5271: 	%{$personnel{$tryserver}}=();
 5272: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5273: 					    &escape($startdate).':'.
 5274: 					    &escape($enddate).':'.
 5275: 					    &escape($rolelist), $tryserver))) {
 5276: 	    my ($key,$value) = split(/\=/,$line,2);
 5277: 	    if (($key) && ($value)) {
 5278: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5279: 	    }
 5280: 	}
 5281:     }
 5282:     return %personnel;
 5283: }
 5284: 
 5285: sub get_active_domroles {
 5286:     my ($dom,$roles) = @_;
 5287:     return () unless (ref($roles) eq 'ARRAY');
 5288:     my $now = time;
 5289:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5290:     my %domroles;
 5291:     foreach my $server (keys(%dompersonnel)) {
 5292:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5293:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5294:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5295:         }
 5296:     }
 5297:     return %domroles;
 5298: }
 5299: 
 5300: # ----------------------------------------------------------- Interval timing 
 5301: 
 5302: {
 5303: # Caches needed for speedup of navmaps
 5304: # We don't want to cache this for very long at all (5 seconds at most)
 5305: # 
 5306: # The user for whom we cache
 5307: my $cachedkey='';
 5308: # The cached times for this user
 5309: my %cachedtimes=();
 5310: # When this was last done
 5311: my $cachedtime='';
 5312: 
 5313: sub load_all_first_access {
 5314:     my ($uname,$udom,$ignorecache)=@_;
 5315:     if (($cachedkey eq $uname.':'.$udom) &&
 5316:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5317:         (!$ignorecache)) {
 5318:         return;
 5319:     }
 5320:     $cachedtime=time;
 5321:     $cachedkey=$uname.':'.$udom;
 5322:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5323: }
 5324: 
 5325: sub get_first_access {
 5326:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5327:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5328:     if ($argsymb) { $symb=$argsymb; }
 5329:     my ($map,$id,$res)=&decode_symb($symb);
 5330:     if ($argmap) { $map = $argmap; }
 5331:     if ($type eq 'course') {
 5332: 	$res='course';
 5333:     } elsif ($type eq 'map') {
 5334: 	$res=&symbread($map);
 5335:     } else {
 5336: 	$res=$symb;
 5337:     }
 5338:     &load_all_first_access($uname,$udom,$ignorecache);
 5339:     return $cachedtimes{"$courseid\0$res"};
 5340: }
 5341: 
 5342: sub set_first_access {
 5343:     my ($type,$interval)=@_;
 5344:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5345:     my ($map,$id,$res)=&decode_symb($symb);
 5346:     if ($type eq 'course') {
 5347: 	$res='course';
 5348:     } elsif ($type eq 'map') {
 5349: 	$res=&symbread($map);
 5350:     } else {
 5351: 	$res=$symb;
 5352:     }
 5353:     $cachedkey='';
 5354:     my $firstaccess=&get_first_access($type,$symb,$map);
 5355:     if ($firstaccess) {
 5356:         &logthis("First access time already set ($firstaccess) when attempting ".
 5357:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
 5358:                  "in $courseid"); 
 5359:         return 'already_set';
 5360:     } else {
 5361:         my $start = time;
 5362: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5363:                           $udom,$uname);
 5364:         if ($putres eq 'ok') {
 5365:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5366:                  $udom,$uname); 
 5367:             &appenv(
 5368:                      {
 5369:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5370:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5371:                      }
 5372:                   );
 5373:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5374:                 $cachedtimes{"$courseid\0$res"} = $start;
 5375:             }
 5376:         } elsif ($putres ne 'refused') {
 5377:             &logthis("Result: $putres when attempting to set first access time ".
 5378:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5379:         }
 5380:         return $putres;
 5381:     }
 5382:     return 'already_set';
 5383: }
 5384: }
 5385: 
 5386: # --------------------------------------------- Set Expire Date for Spreadsheet
 5387: 
 5388: sub expirespread {
 5389:     my ($uname,$udom,$stype,$usymb)=@_;
 5390:     my $cid=$env{'request.course.id'}; 
 5391:     if ($cid) {
 5392:        my $now=time;
 5393:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5394:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5395:                             $env{'course.'.$cid.'.num'}.
 5396: 	        	    ':nohist_expirationdates:'.
 5397:                             &escape($key).'='.$now,
 5398:                             $env{'course.'.$cid.'.home'})
 5399:     }
 5400:     return 'ok';
 5401: }
 5402: 
 5403: # ----------------------------------------------------- Devalidate Spreadsheets
 5404: 
 5405: sub devalidate {
 5406:     my ($symb,$uname,$udom)=@_;
 5407:     my $cid=$env{'request.course.id'}; 
 5408:     if ($cid) {
 5409:         # delete the stored spreadsheets for
 5410:         # - the student level sheet of this user in course's homespace
 5411:         # - the assessment level sheet for this resource 
 5412:         #   for this user in user's homespace
 5413: 	# - current conditional state info
 5414: 	my $key=$uname.':'.$udom.':';
 5415:         my $status=
 5416: 	    &del('nohist_calculatedsheets',
 5417: 		 [$key.'studentcalc:'],
 5418: 		 $env{'course.'.$cid.'.domain'},
 5419: 		 $env{'course.'.$cid.'.num'})
 5420: 		.' '.
 5421: 	    &del('nohist_calculatedsheets_'.$cid,
 5422: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5423:         unless ($status eq 'ok ok') {
 5424:            &logthis('Could not devalidate spreadsheet '.
 5425:                     $uname.' at '.$udom.' for '.
 5426: 		    $symb.': '.$status);
 5427:         }
 5428: 	&delenv('user.state.'.$cid);
 5429:     }
 5430: }
 5431: 
 5432: sub get_scalar {
 5433:     my ($string,$end) = @_;
 5434:     my $value;
 5435:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5436: 	$value = $1;
 5437:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5438: 	$value = $1;
 5439:     }
 5440:     return &unescape($value);
 5441: }
 5442: 
 5443: sub array2str {
 5444:   my (@array) = @_;
 5445:   my $result=&arrayref2str(\@array);
 5446:   $result=~s/^__ARRAY_REF__//;
 5447:   $result=~s/__END_ARRAY_REF__$//;
 5448:   return $result;
 5449: }
 5450: 
 5451: sub arrayref2str {
 5452:   my ($arrayref) = @_;
 5453:   my $result='__ARRAY_REF__';
 5454:   foreach my $elem (@$arrayref) {
 5455:     if(ref($elem) eq 'ARRAY') {
 5456:       $result.=&arrayref2str($elem).'&';
 5457:     } elsif(ref($elem) eq 'HASH') {
 5458:       $result.=&hashref2str($elem).'&';
 5459:     } elsif(ref($elem)) {
 5460:       #print("Got a ref of ".(ref($elem))." skipping.");
 5461:     } else {
 5462:       $result.=&escape($elem).'&';
 5463:     }
 5464:   }
 5465:   $result=~s/\&$//;
 5466:   $result .= '__END_ARRAY_REF__';
 5467:   return $result;
 5468: }
 5469: 
 5470: sub hash2str {
 5471:   my (%hash) = @_;
 5472:   my $result=&hashref2str(\%hash);
 5473:   $result=~s/^__HASH_REF__//;
 5474:   $result=~s/__END_HASH_REF__$//;
 5475:   return $result;
 5476: }
 5477: 
 5478: sub hashref2str {
 5479:   my ($hashref)=@_;
 5480:   my $result='__HASH_REF__';
 5481:   foreach my $key (sort(keys(%$hashref))) {
 5482:     if (ref($key) eq 'ARRAY') {
 5483:       $result.=&arrayref2str($key).'=';
 5484:     } elsif (ref($key) eq 'HASH') {
 5485:       $result.=&hashref2str($key).'=';
 5486:     } elsif (ref($key)) {
 5487:       $result.='=';
 5488:       #print("Got a ref of ".(ref($key))." skipping.");
 5489:     } else {
 5490: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5491:     }
 5492: 
 5493:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5494:       $result.=&arrayref2str($hashref->{$key}).'&';
 5495:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5496:       $result.=&hashref2str($hashref->{$key}).'&';
 5497:     } elsif(ref($hashref->{$key})) {
 5498:        $result.='&';
 5499:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5500:     } else {
 5501:       $result.=&escape($hashref->{$key}).'&';
 5502:     }
 5503:   }
 5504:   $result=~s/\&$//;
 5505:   $result .= '__END_HASH_REF__';
 5506:   return $result;
 5507: }
 5508: 
 5509: sub str2hash {
 5510:     my ($string)=@_;
 5511:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5512:     return %$hash;
 5513: }
 5514: 
 5515: sub str2hashref {
 5516:   my ($string) = @_;
 5517: 
 5518:   my %hash;
 5519: 
 5520:   if($string !~ /^__HASH_REF__/) {
 5521:       if (! ($string eq '' || !defined($string))) {
 5522: 	  $hash{'error'}='Not hash reference';
 5523:       }
 5524:       return (\%hash, $string);
 5525:   }
 5526: 
 5527:   $string =~ s/^__HASH_REF__//;
 5528: 
 5529:   while($string !~ /^__END_HASH_REF__/) {
 5530:       #key
 5531:       my $key='';
 5532:       if($string =~ /^__HASH_REF__/) {
 5533:           ($key, $string)=&str2hashref($string);
 5534:           if(defined($key->{'error'})) {
 5535:               $hash{'error'}='Bad data';
 5536:               return (\%hash, $string);
 5537:           }
 5538:       } elsif($string =~ /^__ARRAY_REF__/) {
 5539:           ($key, $string)=&str2arrayref($string);
 5540:           if($key->[0] eq 'Array reference error') {
 5541:               $hash{'error'}='Bad data';
 5542:               return (\%hash, $string);
 5543:           }
 5544:       } else {
 5545:           $string =~ s/^(.*?)=//;
 5546: 	  $key=&unescape($1);
 5547:       }
 5548:       $string =~ s/^=//;
 5549: 
 5550:       #value
 5551:       my $value='';
 5552:       if($string =~ /^__HASH_REF__/) {
 5553:           ($value, $string)=&str2hashref($string);
 5554:           if(defined($value->{'error'})) {
 5555:               $hash{'error'}='Bad data';
 5556:               return (\%hash, $string);
 5557:           }
 5558:       } elsif($string =~ /^__ARRAY_REF__/) {
 5559:           ($value, $string)=&str2arrayref($string);
 5560:           if($value->[0] eq 'Array reference error') {
 5561:               $hash{'error'}='Bad data';
 5562:               return (\%hash, $string);
 5563:           }
 5564:       } else {
 5565: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5566:       }
 5567:       $string =~ s/^&//;
 5568: 
 5569:       $hash{$key}=$value;
 5570:   }
 5571: 
 5572:   $string =~ s/^__END_HASH_REF__//;
 5573: 
 5574:   return (\%hash, $string);
 5575: }
 5576: 
 5577: sub str2array {
 5578:     my ($string)=@_;
 5579:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5580:     return @$array;
 5581: }
 5582: 
 5583: sub str2arrayref {
 5584:   my ($string) = @_;
 5585:   my @array;
 5586: 
 5587:   if($string !~ /^__ARRAY_REF__/) {
 5588:       if (! ($string eq '' || !defined($string))) {
 5589: 	  $array[0]='Array reference error';
 5590:       }
 5591:       return (\@array, $string);
 5592:   }
 5593: 
 5594:   $string =~ s/^__ARRAY_REF__//;
 5595: 
 5596:   while($string !~ /^__END_ARRAY_REF__/) {
 5597:       my $value='';
 5598:       if($string =~ /^__HASH_REF__/) {
 5599:           ($value, $string)=&str2hashref($string);
 5600:           if(defined($value->{'error'})) {
 5601:               $array[0] ='Array reference error';
 5602:               return (\@array, $string);
 5603:           }
 5604:       } elsif($string =~ /^__ARRAY_REF__/) {
 5605:           ($value, $string)=&str2arrayref($string);
 5606:           if($value->[0] eq 'Array reference error') {
 5607:               $array[0] ='Array reference error';
 5608:               return (\@array, $string);
 5609:           }
 5610:       } else {
 5611: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5612:       }
 5613:       $string =~ s/^&//;
 5614: 
 5615:       push(@array, $value);
 5616:   }
 5617: 
 5618:   $string =~ s/^__END_ARRAY_REF__//;
 5619: 
 5620:   return (\@array, $string);
 5621: }
 5622: 
 5623: # -------------------------------------------------------------------Temp Store
 5624: 
 5625: sub tmpreset {
 5626:   my ($symb,$namespace,$domain,$stuname) = @_;
 5627:   if (!$symb) {
 5628:     $symb=&symbread();
 5629:     if (!$symb) { $symb= $env{'request.url'}; }
 5630:   }
 5631:   $symb=escape($symb);
 5632: 
 5633:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5634:   $namespace=~s/\//\_/g;
 5635:   $namespace=~s/\W//g;
 5636: 
 5637:   if (!$domain) { $domain=$env{'user.domain'}; }
 5638:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5639:   if ($domain eq 'public' && $stuname eq 'public') {
 5640:       $stuname=$ENV{'REMOTE_ADDR'};
 5641:   }
 5642:   my $path=LONCAPA::tempdir();
 5643:   my %hash;
 5644:   if (tie(%hash,'GDBM_File',
 5645: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5646: 	  &GDBM_WRCREAT(),0640)) {
 5647:     foreach my $key (keys(%hash)) {
 5648:       if ($key=~ /:$symb/) {
 5649: 	delete($hash{$key});
 5650:       }
 5651:     }
 5652:   }
 5653: }
 5654: 
 5655: sub tmpstore {
 5656:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5657: 
 5658:   if (!$symb) {
 5659:     $symb=&symbread();
 5660:     if (!$symb) { $symb= $env{'request.url'}; }
 5661:   }
 5662:   $symb=escape($symb);
 5663: 
 5664:   if (!$namespace) {
 5665:     # I don't think we would ever want to store this for a course.
 5666:     # it seems this will only be used if we don't have a course.
 5667:     #$namespace=$env{'request.course.id'};
 5668:     #if (!$namespace) {
 5669:       $namespace=$env{'request.state'};
 5670:     #}
 5671:   }
 5672:   $namespace=~s/\//\_/g;
 5673:   $namespace=~s/\W//g;
 5674:   if (!$domain) { $domain=$env{'user.domain'}; }
 5675:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5676:   if ($domain eq 'public' && $stuname eq 'public') {
 5677:       $stuname=$ENV{'REMOTE_ADDR'};
 5678:   }
 5679:   my $now=time;
 5680:   my %hash;
 5681:   my $path=LONCAPA::tempdir();
 5682:   if (tie(%hash,'GDBM_File',
 5683: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5684: 	  &GDBM_WRCREAT(),0640)) {
 5685:     $hash{"version:$symb"}++;
 5686:     my $version=$hash{"version:$symb"};
 5687:     my $allkeys=''; 
 5688:     foreach my $key (keys(%$storehash)) {
 5689:       $allkeys.=$key.':';
 5690:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5691:     }
 5692:     $hash{"$version:$symb:timestamp"}=$now;
 5693:     $allkeys.='timestamp';
 5694:     $hash{"$version:keys:$symb"}=$allkeys;
 5695:     if (untie(%hash)) {
 5696:       return 'ok';
 5697:     } else {
 5698:       return "error:$!";
 5699:     }
 5700:   } else {
 5701:     return "error:$!";
 5702:   }
 5703: }
 5704: 
 5705: # -----------------------------------------------------------------Temp Restore
 5706: 
 5707: sub tmprestore {
 5708:   my ($symb,$namespace,$domain,$stuname) = @_;
 5709: 
 5710:   if (!$symb) {
 5711:     $symb=&symbread();
 5712:     if (!$symb) { $symb= $env{'request.url'}; }
 5713:   }
 5714:   $symb=escape($symb);
 5715: 
 5716:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5717: 
 5718:   if (!$domain) { $domain=$env{'user.domain'}; }
 5719:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5720:   if ($domain eq 'public' && $stuname eq 'public') {
 5721:       $stuname=$ENV{'REMOTE_ADDR'};
 5722:   }
 5723:   my %returnhash;
 5724:   $namespace=~s/\//\_/g;
 5725:   $namespace=~s/\W//g;
 5726:   my %hash;
 5727:   my $path=LONCAPA::tempdir();
 5728:   if (tie(%hash,'GDBM_File',
 5729: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5730: 	  &GDBM_READER(),0640)) {
 5731:     my $version=$hash{"version:$symb"};
 5732:     $returnhash{'version'}=$version;
 5733:     my $scope;
 5734:     for ($scope=1;$scope<=$version;$scope++) {
 5735:       my $vkeys=$hash{"$scope:keys:$symb"};
 5736:       my @keys=split(/:/,$vkeys);
 5737:       my $key;
 5738:       $returnhash{"$scope:keys"}=$vkeys;
 5739:       foreach $key (@keys) {
 5740: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5741: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5742:       }
 5743:     }
 5744:     if (!(untie(%hash))) {
 5745:       return "error:$!";
 5746:     }
 5747:   } else {
 5748:     return "error:$!";
 5749:   }
 5750:   return %returnhash;
 5751: }
 5752: 
 5753: # ----------------------------------------------------------------------- Store
 5754: 
 5755: sub store {
 5756:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5757:     my $home='';
 5758: 
 5759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5760: 
 5761:     $symb=&symbclean($symb);
 5762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5763: 
 5764:     if (!$domain) { $domain=$env{'user.domain'}; }
 5765:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5766: 
 5767:     &devalidate($symb,$stuname,$domain);
 5768: 
 5769:     $symb=escape($symb);
 5770:     if (!$namespace) { 
 5771:        unless ($namespace=$env{'request.course.id'}) { 
 5772:           return ''; 
 5773:        } 
 5774:     }
 5775:     if (!$home) { $home=$env{'user.home'}; }
 5776: 
 5777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5778:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5779: 
 5780:     my $namevalue='';
 5781:     foreach my $key (keys(%$storehash)) {
 5782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5783:     }
 5784:     $namevalue=~s/\&$//;
 5785:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5786:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5787: }
 5788: 
 5789: # -------------------------------------------------------------- Critical Store
 5790: 
 5791: sub cstore {
 5792:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5793:     my $home='';
 5794: 
 5795:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5796: 
 5797:     $symb=&symbclean($symb);
 5798:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5799: 
 5800:     if (!$domain) { $domain=$env{'user.domain'}; }
 5801:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5802: 
 5803:     &devalidate($symb,$stuname,$domain);
 5804: 
 5805:     $symb=escape($symb);
 5806:     if (!$namespace) { 
 5807:        unless ($namespace=$env{'request.course.id'}) { 
 5808:           return ''; 
 5809:        } 
 5810:     }
 5811:     if (!$home) { $home=$env{'user.home'}; }
 5812: 
 5813:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5814:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5815: 
 5816:     my $namevalue='';
 5817:     foreach my $key (keys(%$storehash)) {
 5818:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5819:     }
 5820:     $namevalue=~s/\&$//;
 5821:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5822:     return critical
 5823:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5824: }
 5825: 
 5826: # --------------------------------------------------------------------- Restore
 5827: 
 5828: sub restore {
 5829:     my ($symb,$namespace,$domain,$stuname) = @_;
 5830:     my $home='';
 5831: 
 5832:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5833: 
 5834:     if (!$symb) {
 5835:         return if ($namespace eq 'courserequests');
 5836:         unless ($symb=escape(&symbread())) { return ''; }
 5837:     } else {
 5838:         unless ($namespace eq 'courserequests') {
 5839:             $symb=&escape(&symbclean($symb));
 5840:         }
 5841:     }
 5842:     if (!$namespace) { 
 5843:        unless ($namespace=$env{'request.course.id'}) { 
 5844:           return ''; 
 5845:        } 
 5846:     }
 5847:     if (!$domain) { $domain=$env{'user.domain'}; }
 5848:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5849:     if (!$home) { $home=$env{'user.home'}; }
 5850:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5851: 
 5852:     my %returnhash=();
 5853:     foreach my $line (split(/\&/,$answer)) {
 5854: 	my ($name,$value)=split(/\=/,$line);
 5855:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5856:     }
 5857:     my $version;
 5858:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5859:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5860:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5861:        }
 5862:     }
 5863:     return %returnhash;
 5864: }
 5865: 
 5866: # ---------------------------------------------------------- Course Description
 5867: #
 5868: #  
 5869: 
 5870: sub coursedescription {
 5871:     my ($courseid,$args)=@_;
 5872:     $courseid=~s/^\///;
 5873:     $courseid=~s/\_/\//g;
 5874:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5875:     my $chome=&homeserver($cnum,$cdomain);
 5876:     my $normalid=$cdomain.'_'.$cnum;
 5877:     # need to always cache even if we get errors otherwise we keep 
 5878:     # trying and trying and trying to get the course description.
 5879:     my %envhash=();
 5880:     my %returnhash=();
 5881:     
 5882:     my $expiretime=600;
 5883:     if ($env{'request.course.id'} eq $normalid) {
 5884: 	$expiretime=120;
 5885:     }
 5886: 
 5887:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5888:     if (!$args->{'freshen_cache'}
 5889: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5890: 	foreach my $key (keys(%env)) {
 5891: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5892: 	    my ($setting) = $1;
 5893: 	    $returnhash{$setting} = $env{$key};
 5894: 	}
 5895: 	return %returnhash;
 5896:     }
 5897: 
 5898:     # get the data again
 5899: 
 5900:     if (!$args->{'one_time'}) {
 5901: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5902:     }
 5903: 
 5904:     if ($chome ne 'no_host') {
 5905:        %returnhash=&dump('environment',$cdomain,$cnum);
 5906:        if (!exists($returnhash{'con_lost'})) {
 5907: 	   my $username = $env{'user.name'}; # Defult username
 5908: 	   if(defined $args->{'user'}) {
 5909: 	       $username = $args->{'user'};
 5910: 	   }
 5911:            $returnhash{'home'}= $chome;
 5912: 	   $returnhash{'domain'} = $cdomain;
 5913: 	   $returnhash{'num'} = $cnum;
 5914:            if (!defined($returnhash{'type'})) {
 5915:                $returnhash{'type'} = 'Course';
 5916:            }
 5917:            while (my ($name,$value) = each %returnhash) {
 5918:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5919:            }
 5920:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5921:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5922: 	       $username.'_'.$cdomain.'_'.$cnum;
 5923:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5924:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5925:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5926:        }
 5927:     }
 5928:     if (!$args->{'one_time'}) {
 5929: 	&appenv(\%envhash);
 5930:     }
 5931:     return %returnhash;
 5932: }
 5933: 
 5934: sub update_released_required {
 5935:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5936:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5937:         $cid = $env{'request.course.id'};
 5938:         $cdom = $env{'course.'.$cid.'.domain'};
 5939:         $cnum = $env{'course.'.$cid.'.num'};
 5940:         $chome = $env{'course.'.$cid.'.home'};
 5941:     }
 5942:     if ($needsrelease) {
 5943:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5944:         my $needsupdate;
 5945:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5946:             $needsupdate = 1;
 5947:         } else {
 5948:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5949:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5950:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5951:                 $needsupdate = 1;
 5952:             }
 5953:         }
 5954:         if ($needsupdate) {
 5955:             my %needshash = (
 5956:                              'internal.releaserequired' => $needsrelease,
 5957:                             );
 5958:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5959:             if ($putresult eq 'ok') {
 5960:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5961:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5962:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5963:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5964:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5965:                 }
 5966:             }
 5967:         }
 5968:     }
 5969:     return;
 5970: }
 5971: 
 5972: # -------------------------------------------------See if a user is privileged
 5973: 
 5974: sub privileged {
 5975:     my ($username,$domain,$possdomains,$possroles)=@_;
 5976:     my $now = time;
 5977:     my $roles;
 5978:     if (ref($possroles) eq 'ARRAY') {
 5979:         $roles = $possroles; 
 5980:     } else {
 5981:         $roles = ['dc','su'];
 5982:     }
 5983:     if (ref($possdomains) eq 'ARRAY') {
 5984:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5985:         foreach my $dom (@{$possdomains}) {
 5986:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5987:                 (ref($privileged{$dom}) eq 'HASH')) {
 5988:                 foreach my $role (@{$roles}) {
 5989:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5990:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5991:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5992:                             return 1 unless (($end && $end < $now) ||
 5993:                                              ($start && $start > $now));
 5994:                         }
 5995:                     }
 5996:                 }
 5997:             }
 5998:         }
 5999:     } else {
 6000:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6001:         my $now = time;
 6002: 
 6003:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6004:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6005:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6006:                 return 1 unless ($tend && $tend < $now) 
 6007:                         or ($tstart && $tstart > $now);
 6008:             }
 6009:         }
 6010:     }
 6011:     return 0;
 6012: }
 6013: 
 6014: sub privileged_by_domain {
 6015:     my ($domains,$roles) = @_;
 6016:     my %privileged = ();
 6017:     my $cachetime = 60*60*24;
 6018:     my $now = time;
 6019:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6020:         return %privileged;
 6021:     }
 6022:     foreach my $dom (@{$domains}) {
 6023:         next if (ref($privileged{$dom}) eq 'HASH');
 6024:         my $needroles;
 6025:         foreach my $role (@{$roles}) {
 6026:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6027:             if (defined($cached)) {
 6028:                 if (ref($result) eq 'HASH') {
 6029:                     $privileged{$dom}{$role} = $result;
 6030:                 }
 6031:             } else {
 6032:                 $needroles = 1;
 6033:             }
 6034:         }
 6035:         if ($needroles) {
 6036:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6037:             $privileged{$dom} = {};
 6038:             foreach my $server (keys(%dompersonnel)) {
 6039:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6040:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6041:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6042:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6043:                         next if ($end && $end < $now);
 6044:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6045:                             $dompersonnel{$server}{$item};
 6046:                     }
 6047:                 }
 6048:             }
 6049:             if (ref($privileged{$dom}) eq 'HASH') {
 6050:                 foreach my $role (@{$roles}) {
 6051:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6052:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6053:                     } else {
 6054:                         my %hash = ();
 6055:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6056:                     }
 6057:                 }
 6058:             }
 6059:         }
 6060:     }
 6061:     return %privileged;
 6062: }
 6063: 
 6064: # -------------------------------------------------------- Get user privileges
 6065: 
 6066: sub rolesinit {
 6067:     my ($domain, $username) = @_;
 6068:     my %userroles = ('user.login.time' => time);
 6069:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6070: 
 6071:     # firstaccess and timerinterval are related to timed maps/resources. 
 6072:     # also, blocking can be triggered by an activating timer
 6073:     # it's saved in the user's %env.
 6074:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6075:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6076:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6077:         %timerintchk, %timerintenv);
 6078: 
 6079:     foreach my $key (keys(%firstaccess)) {
 6080:         my ($cid, $rest) = split(/\0/, $key);
 6081:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6082:     }
 6083: 
 6084:     foreach my $key (keys(%timerinterval)) {
 6085:         my ($cid,$rest) = split(/\0/,$key);
 6086:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6087:     }
 6088: 
 6089:     my %allroles=();
 6090:     my %allgroups=();
 6091: 
 6092:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6093:         my $role = $rolesdump{$area};
 6094:         $area =~ s/\_\w\w$//;
 6095: 
 6096:         my ($trole, $tend, $tstart, $group_privs);
 6097: 
 6098:         if ($role =~ /^cr/) {
 6099:         # Custom role, defined by a user 
 6100:         # e.g., user.role.cr/msu/smith/mynewrole
 6101:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6102:                 $trole = $1;
 6103:                 ($tend, $tstart) = split('_', $2);
 6104:             } else {
 6105:                 $trole = $role;
 6106:             }
 6107:         } elsif ($role =~ m|^gr/|) {
 6108:         # Role of member in a group, defined within a course/community
 6109:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6110:             ($trole, $tend, $tstart) = split(/_/, $role);
 6111:             next if $tstart eq '-1';
 6112:             ($trole, $group_privs) = split(/\//, $trole);
 6113:             $group_privs = &unescape($group_privs);
 6114:         } else {
 6115:         # Just a normal role, defined in roles.tab
 6116:             ($trole, $tend, $tstart) = split(/_/,$role);
 6117:         }
 6118: 
 6119:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6120:                  $username);
 6121:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6122: 
 6123:         # role expired or not available yet?
 6124:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6125:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6126: 
 6127:         next if $area eq '' or $trole eq '';
 6128: 
 6129:         my $spec = "$trole.$area";
 6130:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6131: 
 6132:         if ($trole =~ /^cr\//) {
 6133:         # Custom role, defined by a user
 6134:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6135:         } elsif ($trole eq 'gr') {
 6136:         # Role of a member in a group, defined within a course/community
 6137:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6138:             next;
 6139:         } else {
 6140:         # Normal role, defined in roles.tab
 6141:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6142:         }
 6143: 
 6144:         my $cid = $tdomain.'_'.$trest;
 6145:         unless ($firstaccchk{$cid}) {
 6146:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6147:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6148:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6149:                         $coursetimerstarts{$cid}{$item}; 
 6150:                 }
 6151:             }
 6152:             $firstaccchk{$cid} = 1;
 6153:         }
 6154:         unless ($timerintchk{$cid}) {
 6155:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6156:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6157:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6158:                        $coursetimerintervals{$cid}{$item};
 6159:                 }
 6160:             }
 6161:             $timerintchk{$cid} = 1;
 6162:         }
 6163:     }
 6164: 
 6165:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6166:                                                           \%allroles, \%allgroups);
 6167:     $env{'user.adv'} = $userroles{'user.adv'};
 6168:     $env{'user.rar'} = $userroles{'user.rar'};
 6169: 
 6170:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6171: }
 6172: 
 6173: sub set_arearole {
 6174:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6175:     unless ($nolog) {
 6176: # log the associated role with the area
 6177:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6178:     }
 6179:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6180: }
 6181: 
 6182: sub custom_roleprivs {
 6183:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6184:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6185:     my $homsvr = &homeserver($rauthor,$rdomain);
 6186:     if (&hostname($homsvr) ne '') {
 6187:         my ($rdummy,$roledef)=
 6188:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6189:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6190:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6191:             if (defined($syspriv)) {
 6192:                 if ($trest =~ /^$match_community$/) {
 6193:                     $syspriv =~ s/bre\&S//; 
 6194:                 }
 6195:                 $$allroles{'cm./'}.=':'.$syspriv;
 6196:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6197:             }
 6198:             if ($tdomain ne '') {
 6199:                 if (defined($dompriv)) {
 6200:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6201:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6202:                 }
 6203:                 if (($trest ne '') && (defined($coursepriv))) {
 6204:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6205:                         my $rolename = $1;
 6206:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6207:                     }
 6208:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6209:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6210:                 }
 6211:             }
 6212:         }
 6213:     }
 6214: }
 6215: 
 6216: sub course_adhocrole_privs {
 6217:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6218:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6219:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6220:         my (%currprivs,%storeprivs);
 6221:         foreach my $item (split(/:/,$coursepriv)) {
 6222:             my ($priv,$restrict) = split(/\&/,$item);
 6223:             $currprivs{$priv} = $restrict;
 6224:         }
 6225:         my (%possadd,%possremove,%full);
 6226:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6227:             my ($priv,$restrict)=split(/\&/,$item);
 6228:             $full{$priv} = $restrict;
 6229:         }
 6230:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6231:              next if ($item eq '');
 6232:              my ($rule,$rest) = split(/=/,$item);
 6233:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6234:              foreach my $priv (split(/:/,$rest)) {
 6235:                  if ($priv ne '') {
 6236:                      if ($rule eq 'off') {
 6237:                          $possremove{$priv} = 1;
 6238:                      } else {
 6239:                          $possadd{$priv} = 1;
 6240:                      }
 6241:                  }
 6242:              }
 6243:          }
 6244:          foreach my $priv (sort(keys(%full))) {
 6245:              if (exists($currprivs{$priv})) {
 6246:                  unless (exists($possremove{$priv})) {
 6247:                      $storeprivs{$priv} = $currprivs{$priv};
 6248:                  }
 6249:              } elsif (exists($possadd{$priv})) {
 6250:                  $storeprivs{$priv} = $full{$priv};
 6251:              }
 6252:          }
 6253:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6254:      }
 6255:      return $coursepriv;
 6256: }
 6257: 
 6258: sub group_roleprivs {
 6259:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6260:     my $access = 1;
 6261:     my $now = time;
 6262:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6263:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6264:     if ($access) {
 6265:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6266:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6267:     }
 6268: }
 6269: 
 6270: sub standard_roleprivs {
 6271:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6272:     if (defined($pr{$trole.':s'})) {
 6273:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6274:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6275:     }
 6276:     if ($tdomain ne '') {
 6277:         if (defined($pr{$trole.':d'})) {
 6278:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6279:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6280:         }
 6281:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6282:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6283:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6284:         }
 6285:     }
 6286: }
 6287: 
 6288: sub set_userprivs {
 6289:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6290:     my $author=0;
 6291:     my $adv=0;
 6292:     my $rar=0;
 6293:     my %grouproles = ();
 6294:     if (keys(%{$allgroups}) > 0) {
 6295:         my @groupkeys; 
 6296:         foreach my $role (keys(%{$allroles})) {
 6297:             push(@groupkeys,$role);
 6298:         }
 6299:         if (ref($groups_roles) eq 'HASH') {
 6300:             foreach my $key (keys(%{$groups_roles})) {
 6301:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6302:                     push(@groupkeys,$key);
 6303:                 }
 6304:             }
 6305:         }
 6306:         if (@groupkeys > 0) {
 6307:             foreach my $role (@groupkeys) {
 6308:                 my ($trole,$area,$sec,$extendedarea);
 6309:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6310:                     $trole = $1;
 6311:                     $area = $2;
 6312:                     $sec = $3;
 6313:                     $extendedarea = $area.$sec;
 6314:                     if (exists($$allgroups{$area})) {
 6315:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6316:                             my $spec = $trole.'.'.$extendedarea;
 6317:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6318:                                                 $$allgroups{$area}{$group};
 6319:                         }
 6320:                     }
 6321:                 }
 6322:             }
 6323:         }
 6324:     }
 6325:     foreach my $group (keys(%grouproles)) {
 6326:         $$allroles{$group} = $grouproles{$group};
 6327:     }
 6328:     foreach my $role (keys(%{$allroles})) {
 6329:         my %thesepriv;
 6330:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6331:         foreach my $item (split(/:/,$$allroles{$role})) {
 6332:             if ($item ne '') {
 6333:                 my ($privilege,$restrictions)=split(/&/,$item);
 6334:                 if ($restrictions eq '') {
 6335:                     $thesepriv{$privilege}='F';
 6336:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6337:                     $thesepriv{$privilege}.=$restrictions;
 6338:                 }
 6339:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6340:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6341:             }
 6342:         }
 6343:         my $thesestr='';
 6344:         foreach my $priv (sort(keys(%thesepriv))) {
 6345: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6346: 	}
 6347:         $userroles->{'user.priv.'.$role} = $thesestr;
 6348:     }
 6349:     return ($author,$adv,$rar);
 6350: }
 6351: 
 6352: sub role_status {
 6353:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6354:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6355:         my ($one,$two) = split(m{\./},$rolekey,2);
 6356:         (undef,undef,$$role) = split(/\./,$one,3);
 6357:         unless (!defined($$role) || $$role eq '') {
 6358:             $$where = '/'.$two;
 6359:             $$trolecode=$$role.'.'.$$where;
 6360:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6361:             $$tstatus='is';
 6362:             if ($$tstart && $$tstart>$update) {
 6363:                 $$tstatus='future';
 6364:                 if ($$tstart<$now) {
 6365:                     if ($$tstart && $$tstart>$refresh) {
 6366:                         if (($$where ne '') && ($$role ne '')) {
 6367:                             my (%allroles,%allgroups,$group_privs,
 6368:                                 %groups_roles,@rolecodes);
 6369:                             my %userroles = (
 6370:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6371:                             );
 6372:                             @rolecodes = ('cm'); 
 6373:                             my $spec=$$role.'.'.$$where;
 6374:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6375:                             if ($$role =~ /^cr\//) {
 6376:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6377:                                 push(@rolecodes,'cr');
 6378:                             } elsif ($$role eq 'gr') {
 6379:                                 push(@rolecodes,$$role);
 6380:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6381:                                                     $env{'user.name'});
 6382:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6383:                                 (undef,my $group_privs) = split(/\//,$trole);
 6384:                                 $group_privs = &unescape($group_privs);
 6385:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6386:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6387:                                 &get_groups_roles($tdomain,$trest,
 6388:                                                   \%course_roles,\@rolecodes,
 6389:                                                   \%groups_roles);
 6390:                             } else {
 6391:                                 push(@rolecodes,$$role);
 6392:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6393:                             }
 6394:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6395:                                                                    \%groups_roles);
 6396:                             &appenv(\%userroles,\@rolecodes);
 6397:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6398:                         }
 6399:                     }
 6400:                     $$tstatus = 'is';
 6401:                 }
 6402:             }
 6403:             if ($$tend) {
 6404:                 if ($$tend<$update) {
 6405:                     $$tstatus='expired';
 6406:                 } elsif ($$tend<$now) {
 6407:                     $$tstatus='will_not';
 6408:                 }
 6409:             }
 6410:         }
 6411:     }
 6412: }
 6413: 
 6414: sub get_groups_roles {
 6415:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6416:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6417:                   (ref($rolecodes) eq 'ARRAY') && 
 6418:                   (ref($groups_roles) eq 'HASH')); 
 6419:     if (keys(%{$cdom_courseroles}) > 0) {
 6420:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6421:         if ($cdom ne '' && $cnum ne '') {
 6422:             foreach my $key (keys(%{$cdom_courseroles})) {
 6423:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6424:                     my $crsrole = $1;
 6425:                     my $crssec = $2;
 6426:                     if ($crsrole =~ /^cr/) {
 6427:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6428:                             push(@{$rolecodes},'cr');
 6429:                         }
 6430:                     } else {
 6431:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6432:                             push(@{$rolecodes},$crsrole);
 6433:                         }
 6434:                     }
 6435:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6436:                     if ($crssec ne '') {
 6437:                         $rolekey .= "/$crssec";
 6438:                     }
 6439:                     $rolekey .= './';
 6440:                     $groups_roles->{$rolekey} = $rolecodes;
 6441:                 }
 6442:             }
 6443:         }
 6444:     }
 6445:     return;
 6446: }
 6447: 
 6448: sub delete_env_groupprivs {
 6449:     my ($where,$courseroles,$possroles) = @_;
 6450:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6451:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6452:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6453:         %{$courseroles->{$udom}} =
 6454:             &get_my_roles('','','userroles',['active'],
 6455:                           $possroles,[$udom],1);
 6456:     }
 6457:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6458:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6459:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6460:             my $area = '/'.$cdom.'/'.$cnum;
 6461:             my $privkey = "user.priv.$crsrole.$area";
 6462:             if ($crssec ne '') {
 6463:                 $privkey .= '/'.$crssec;
 6464:             }
 6465:             $privkey .= ".$area/$group";
 6466:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6467:         }
 6468:     }
 6469:     return;
 6470: }
 6471: 
 6472: sub check_adhoc_privs {
 6473:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6474:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6475:     if ($sec) {
 6476:         $cckey .= '/'.$sec;
 6477:     } 
 6478:     my $setprivs;
 6479:     if ($env{$cckey}) {
 6480:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6481:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6482:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6483:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6484:             $setprivs = 1;
 6485:         }
 6486:     } else {
 6487:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6488:         $setprivs = 1;
 6489:     }
 6490:     return $setprivs;
 6491: }
 6492: 
 6493: sub set_adhoc_privileges {
 6494: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6495:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6496:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6497:     if ($sec ne '') {
 6498:         $area .= '/'.$sec;
 6499:     }
 6500:     my $spec = $role.'.'.$area;
 6501:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6502:                                   $env{'user.name'},1);
 6503:     my %rolehash = ();
 6504:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6505:         my $rolename = $1;
 6506:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6507:         my %domdef = &get_domain_defaults($dcdom);
 6508:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6509:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6510:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6511:             }
 6512:         }
 6513:     } else {
 6514:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6515:     }
 6516:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6517:     &appenv(\%userroles,[$role,'cm']);
 6518:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6519:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6520:         &appenv( {'request.role'        => $spec,
 6521:                   'request.role.domain' => $dcdom,
 6522:                   'request.course.sec'  => $sec,
 6523:                  }
 6524:                );
 6525:         my $tadv=0;
 6526:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6527:         &appenv({'request.role.adv'    => $tadv});
 6528:     }
 6529: }
 6530: 
 6531: # --------------------------------------------------------------- get interface
 6532: 
 6533: sub get {
 6534:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6535:    my $items='';
 6536:    foreach my $item (@$storearr) {
 6537:        $items.=&escape($item).'&';
 6538:    }
 6539:    $items=~s/\&$//;
 6540:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6541:    if (!$uname) { $uname=$env{'user.name'}; }
 6542:    my $uhome=&homeserver($uname,$udomain);
 6543: 
 6544:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6545:    my @pairs=split(/\&/,$rep);
 6546:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6547:      return @pairs;
 6548:    }
 6549:    my %returnhash=();
 6550:    my $i=0;
 6551:    foreach my $item (@$storearr) {
 6552:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6553:       $i++;
 6554:    }
 6555:    return %returnhash;
 6556: }
 6557: 
 6558: # --------------------------------------------------------------- del interface
 6559: 
 6560: sub del {
 6561:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6562:    my $items='';
 6563:    foreach my $item (@$storearr) {
 6564:        $items.=&escape($item).'&';
 6565:    }
 6566: 
 6567:    $items=~s/\&$//;
 6568:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6569:    if (!$uname) { $uname=$env{'user.name'}; }
 6570:    my $uhome=&homeserver($uname,$udomain);
 6571:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6572: }
 6573: 
 6574: # -------------------------------------------------------------- dump interface
 6575: 
 6576: sub unserialize {
 6577:     my ($rep, $escapedkeys) = @_;
 6578: 
 6579:     return {} if $rep =~ /^error/;
 6580: 
 6581:     my %returnhash=();
 6582: 	foreach my $item (split(/\&/,$rep)) {
 6583: 	    my ($key, $value) = split(/=/, $item, 2);
 6584: 	    $key = unescape($key) unless $escapedkeys;
 6585: 	    next if $key =~ /^error: 2 /;
 6586: 	    $returnhash{$key} = &thaw_unescape($value);
 6587: 	}
 6588:     #return %returnhash;
 6589:     return \%returnhash;
 6590: }        
 6591: 
 6592: # see Lond::dump_with_regexp
 6593: # if $escapedkeys hash keys won't get unescaped.
 6594: sub dump {
 6595:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6596:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6597:     if (!$uname) { $uname=$env{'user.name'}; }
 6598:     my $uhome=&homeserver($uname,$udomain);
 6599: 
 6600:     if ($regexp) {
 6601:         $regexp=&escape($regexp);
 6602:     } else {
 6603:         $regexp='.';
 6604:     }
 6605:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6606:         # user is hosted on this machine
 6607:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6608:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6609:         return %{unserialize($reply, $escapedkeys)};
 6610:     }
 6611:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6612:     my @pairs=split(/\&/,$rep);
 6613:     my %returnhash=();
 6614:     if (!($rep =~ /^error/ )) {
 6615: 	foreach my $item (@pairs) {
 6616: 	    my ($key,$value)=split(/=/,$item,2);
 6617:         $key = unescape($key) unless $escapedkeys;
 6618:         #$key = &unescape($key);
 6619: 	    next if ($key =~ /^error: 2 /);
 6620: 	    $returnhash{$key}=&thaw_unescape($value);
 6621: 	}
 6622:     }
 6623:     return %returnhash;
 6624: }
 6625: 
 6626: 
 6627: # --------------------------------------------------------- dumpstore interface
 6628: 
 6629: sub dumpstore {
 6630:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6631:    # same as dump but keys must be escaped. They may contain colon separated
 6632:    # lists of values that may themself contain colons (e.g. symbs).
 6633:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6634: }
 6635: 
 6636: # -------------------------------------------------------------- keys interface
 6637: 
 6638: sub getkeys {
 6639:    my ($namespace,$udomain,$uname)=@_;
 6640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6641:    if (!$uname) { $uname=$env{'user.name'}; }
 6642:    my $uhome=&homeserver($uname,$udomain);
 6643:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6644:    my @keyarray=();
 6645:    foreach my $key (split(/\&/,$rep)) {
 6646:       next if ($key =~ /^error: 2 /);
 6647:       push(@keyarray,&unescape($key));
 6648:    }
 6649:    return @keyarray;
 6650: }
 6651: 
 6652: # --------------------------------------------------------------- currentdump
 6653: sub currentdump {
 6654:    my ($courseid,$sdom,$sname)=@_;
 6655:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6656:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6657:    $sname    = $env{'user.name'}         if (! defined($sname));
 6658:    my $uhome = &homeserver($sname,$sdom);
 6659:    my $rep;
 6660: 
 6661:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6662:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6663:                    $courseid)));
 6664:    } else {
 6665:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6666:    }
 6667: 
 6668:    return if ($rep =~ /^(error:|no_such_host)/);
 6669:    #
 6670:    my %returnhash=();
 6671:    #
 6672:    if ($rep eq 'unknown_cmd') {
 6673:        # an old lond will not know currentdump
 6674:        # Do a dump and make it look like a currentdump
 6675:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6676:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6677:        my %hash = @tmp;
 6678:        @tmp=();
 6679:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6680:    } else {
 6681:        my @pairs=split(/\&/,$rep);
 6682:        foreach my $pair (@pairs) {
 6683:            my ($key,$value)=split(/=/,$pair,2);
 6684:            my ($symb,$param) = split(/:/,$key);
 6685:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6686:                                                         &thaw_unescape($value);
 6687:        }
 6688:    }
 6689:    return %returnhash;
 6690: }
 6691: 
 6692: sub convert_dump_to_currentdump{
 6693:     my %hash = %{shift()};
 6694:     my %returnhash;
 6695:     # Code ripped from lond, essentially.  The only difference
 6696:     # here is the unescaping done by lonnet::dump().  Conceivably
 6697:     # we might run in to problems with parameter names =~ /^v\./
 6698:     while (my ($key,$value) = each(%hash)) {
 6699:         my ($v,$symb,$param) = split(/:/,$key);
 6700: 	$symb  = &unescape($symb);
 6701: 	$param = &unescape($param);
 6702:         next if ($v eq 'version' || $symb eq 'keys');
 6703:         next if (exists($returnhash{$symb}) &&
 6704:                  exists($returnhash{$symb}->{$param}) &&
 6705:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6706:         $returnhash{$symb}->{$param}=$value;
 6707:         $returnhash{$symb}->{'v.'.$param}=$v;
 6708:     }
 6709:     #
 6710:     # Remove all of the keys in the hashes which keep track of
 6711:     # the version of the parameter.
 6712:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6713:         # use a foreach because we are going to delete from the hash.
 6714:         foreach my $key (keys(%$param_hash)) {
 6715:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6716:         }
 6717:     }
 6718:     return \%returnhash;
 6719: }
 6720: 
 6721: # ------------------------------------------------------ critical inc interface
 6722: 
 6723: sub cinc {
 6724:     return &inc(@_,'critical');
 6725: }
 6726: 
 6727: # --------------------------------------------------------------- inc interface
 6728: 
 6729: sub inc {
 6730:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6731:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6732:     if (!$uname) { $uname=$env{'user.name'}; }
 6733:     my $uhome=&homeserver($uname,$udomain);
 6734:     my $items='';
 6735:     if (! ref($store)) {
 6736:         # got a single value, so use that instead
 6737:         $items = &escape($store).'=&';
 6738:     } elsif (ref($store) eq 'SCALAR') {
 6739:         $items = &escape($$store).'=&';        
 6740:     } elsif (ref($store) eq 'ARRAY') {
 6741:         $items = join('=&',map {&escape($_);} @{$store});
 6742:     } elsif (ref($store) eq 'HASH') {
 6743:         while (my($key,$value) = each(%{$store})) {
 6744:             $items.= &escape($key).'='.&escape($value).'&';
 6745:         }
 6746:     }
 6747:     $items=~s/\&$//;
 6748:     if ($critical) {
 6749: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6750:     } else {
 6751: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6752:     }
 6753: }
 6754: 
 6755: # --------------------------------------------------------------- put interface
 6756: 
 6757: sub put {
 6758:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6759:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6760:    if (!$uname) { $uname=$env{'user.name'}; }
 6761:    my $uhome=&homeserver($uname,$udomain);
 6762:    my $items='';
 6763:    foreach my $item (keys(%$storehash)) {
 6764:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6765:    }
 6766:    $items=~s/\&$//;
 6767:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6768: }
 6769: 
 6770: # ------------------------------------------------------------ newput interface
 6771: 
 6772: sub newput {
 6773:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6774:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6775:    if (!$uname) { $uname=$env{'user.name'}; }
 6776:    my $uhome=&homeserver($uname,$udomain);
 6777:    my $items='';
 6778:    foreach my $key (keys(%$storehash)) {
 6779:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6780:    }
 6781:    $items=~s/\&$//;
 6782:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6783: }
 6784: 
 6785: # ---------------------------------------------------------  putstore interface
 6786: 
 6787: sub putstore {
 6788:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6789:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6790:    if (!$uname) { $uname=$env{'user.name'}; }
 6791:    my $uhome=&homeserver($uname,$udomain);
 6792:    my $items='';
 6793:    foreach my $key (keys(%$storehash)) {
 6794:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6795:    }
 6796:    $items=~s/\&$//;
 6797:    my $esc_symb=&escape($symb);
 6798:    my $esc_v=&escape($version);
 6799:    my $reply =
 6800:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6801: 	      $uhome);
 6802:    if (($tolog) && ($reply eq 'ok')) {
 6803:        my $namevalue='';
 6804:        foreach my $key (keys(%{$storehash})) {
 6805:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6806:        }
 6807:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6808:                      '&host='.&escape($perlvar{'lonHostID'}).
 6809:                      '&version='.$esc_v.
 6810:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6811:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6812:    }
 6813:    if ($reply eq 'unknown_cmd') {
 6814:        # gfall back to way things use to be done
 6815:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6816: 			    $uname);
 6817:    }
 6818:    return $reply;
 6819: }
 6820: 
 6821: sub old_putstore {
 6822:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6823:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6824:     if (!$uname) { $uname=$env{'user.name'}; }
 6825:     my $uhome=&homeserver($uname,$udomain);
 6826:     my %newstorehash;
 6827:     foreach my $item (keys(%$storehash)) {
 6828: 	my $key = $version.':'.&escape($symb).':'.$item;
 6829: 	$newstorehash{$key} = $storehash->{$item};
 6830:     }
 6831:     my $items='';
 6832:     my %allitems = ();
 6833:     foreach my $item (keys(%newstorehash)) {
 6834: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6835: 	    my $key = $1.':keys:'.$2;
 6836: 	    $allitems{$key} .= $3.':';
 6837: 	}
 6838: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6839:     }
 6840:     foreach my $item (keys(%allitems)) {
 6841: 	$allitems{$item} =~ s/\:$//;
 6842: 	$items.= $item.'='.$allitems{$item}.'&';
 6843:     }
 6844:     $items=~s/\&$//;
 6845:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6846: }
 6847: 
 6848: # ------------------------------------------------------ critical put interface
 6849: 
 6850: sub cput {
 6851:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6853:    if (!$uname) { $uname=$env{'user.name'}; }
 6854:    my $uhome=&homeserver($uname,$udomain);
 6855:    my $items='';
 6856:    foreach my $item (keys(%$storehash)) {
 6857:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6858:    }
 6859:    $items=~s/\&$//;
 6860:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6861: }
 6862: 
 6863: # -------------------------------------------------------------- eget interface
 6864: 
 6865: sub eget {
 6866:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6867:    my $items='';
 6868:    foreach my $item (@$storearr) {
 6869:        $items.=&escape($item).'&';
 6870:    }
 6871:    $items=~s/\&$//;
 6872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6873:    if (!$uname) { $uname=$env{'user.name'}; }
 6874:    my $uhome=&homeserver($uname,$udomain);
 6875:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6876:    my @pairs=split(/\&/,$rep);
 6877:    my %returnhash=();
 6878:    my $i=0;
 6879:    foreach my $item (@$storearr) {
 6880:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6881:       $i++;
 6882:    }
 6883:    return %returnhash;
 6884: }
 6885: 
 6886: # ------------------------------------------------------------ tmpput interface
 6887: sub tmpput {
 6888:     my ($storehash,$server,$context)=@_;
 6889:     my $items='';
 6890:     foreach my $item (keys(%$storehash)) {
 6891: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6892:     }
 6893:     $items=~s/\&$//;
 6894:     if (defined($context)) {
 6895:         $items .= ':'.&escape($context);
 6896:     }
 6897:     return &reply("tmpput:$items",$server);
 6898: }
 6899: 
 6900: # ------------------------------------------------------------ tmpget interface
 6901: sub tmpget {
 6902:     my ($token,$server)=@_;
 6903:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6904:     my $rep=&reply("tmpget:$token",$server);
 6905:     my %returnhash;
 6906:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6907:         return %returnhash;
 6908:     }
 6909:     foreach my $item (split(/\&/,$rep)) {
 6910: 	my ($key,$value)=split(/=/,$item);
 6911: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6912:     }
 6913:     return %returnhash;
 6914: }
 6915: 
 6916: # ------------------------------------------------------------ tmpdel interface
 6917: sub tmpdel {
 6918:     my ($token,$server)=@_;
 6919:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6920:     return &reply("tmpdel:$token",$server);
 6921: }
 6922: 
 6923: # ------------------------------------------------------------ get_timebased_id 
 6924: 
 6925: sub get_timebased_id {
 6926:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6927:         $maxtries) = @_;
 6928:     my ($newid,$error,$dellock);
 6929:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6930:         return ('','ok','invalid call to get suffix');
 6931:     }
 6932: 
 6933: # set defaults for any optional args for which values were not supplied
 6934:     if ($who eq '') {
 6935:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6936:     }
 6937:     if (!$locktries) {
 6938:         $locktries = 3;
 6939:     }
 6940:     if (!$maxtries) {
 6941:         $maxtries = 10;
 6942:     }
 6943:     
 6944:     if (($cdom eq '') || ($cnum eq '')) {
 6945:         if ($env{'request.course.id'}) {
 6946:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6947:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6948:         }
 6949:         if (($cdom eq '') || ($cnum eq '')) {
 6950:             return ('','ok','call to get suffix not in course context');
 6951:         }
 6952:     }
 6953: 
 6954: # construct locking item
 6955:     my $lockhash = {
 6956:                       $prefix."\0".'locked_'.$keyid => $who,
 6957:                    };
 6958:     my $tries = 0;
 6959: 
 6960: # attempt to get lock on nohist_$namespace file
 6961:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6962:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6963:         $tries ++;
 6964:         sleep 1;
 6965:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6966:     }
 6967: 
 6968: # attempt to get unique identifier, based on current timestamp
 6969:     if ($gotlock eq 'ok') {
 6970:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6971:         my $id = time;
 6972:         $newid = $id;
 6973:         if ($idtype eq 'addcode') {
 6974:             $newid .= &sixnum_code();
 6975:         }
 6976:         my $idtries = 0;
 6977:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6978:             if ($idtype eq 'concat') {
 6979:                 $newid = $id.$idtries;
 6980:             } elsif ($idtype eq 'addcode') {
 6981:                 $newid = $newid.&sixnum_code();
 6982:             } else {
 6983:                 $newid ++;
 6984:             }
 6985:             $idtries ++;
 6986:         }
 6987:         if (!exists($inuse{$prefix."\0".$newid})) {
 6988:             my %new_item =  (
 6989:                               $prefix."\0".$newid => $who,
 6990:                             );
 6991:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6992:                                                  $cdom,$cnum);
 6993:             if ($putresult ne 'ok') {
 6994:                 undef($newid);
 6995:                 $error = 'error saving new item: '.$putresult;
 6996:             }
 6997:         } else {
 6998:              undef($newid);
 6999:              $error = ('error: no unique suffix available for the new item ');
 7000:         }
 7001: #  remove lock
 7002:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7003:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7004:     } else {
 7005:         $error = "error: could not obtain lockfile\n";
 7006:         $dellock = 'ok';
 7007:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7008:             $dellock = 'nolock';
 7009:         }
 7010:     }
 7011:     return ($newid,$dellock,$error);
 7012: }
 7013: 
 7014: sub sixnum_code {
 7015:     my $code;
 7016:     for (0..6) {
 7017:         $code .= int( rand(9) );
 7018:     }
 7019:     return $code;
 7020: }
 7021: 
 7022: # -------------------------------------------------- portfolio access checking
 7023: 
 7024: sub portfolio_access {
 7025:     my ($requrl,$clientip) = @_;
 7026:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7027:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7028:     if ($result) {
 7029:         my %setters;
 7030:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7031:             my ($startblock,$endblock) =
 7032:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7033:             if ($startblock && $endblock) {
 7034:                 return 'B';
 7035:             }
 7036:         } else {
 7037:             my ($startblock,$endblock) =
 7038:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7039:             if ($startblock && $endblock) {
 7040:                 return 'B';
 7041:             }
 7042:         }
 7043:     }
 7044:     if ($result eq 'ok') {
 7045:        return 'F';
 7046:     } elsif ($result =~ /^[^:]+:guest_/) {
 7047:        return 'A';
 7048:     }
 7049:     return '';
 7050: }
 7051: 
 7052: sub get_portfolio_access {
 7053:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7054: 
 7055:     if (!ref($access_hash)) {
 7056: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7057: 	my %access_controls = &get_access_controls($current_perms,$group,
 7058: 						   $file_name);
 7059: 	$access_hash = $access_controls{$file_name};
 7060:     }
 7061: 
 7062:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7063:     my $now = time;
 7064:     if (ref($access_hash) eq 'HASH') {
 7065:         foreach my $key (keys(%{$access_hash})) {
 7066:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7067:             if ($start > $now) {
 7068:                 next;
 7069:             }
 7070:             if ($end && $end<$now) {
 7071:                 next;
 7072:             }
 7073:             if ($scope eq 'public') {
 7074:                 $public = $key;
 7075:                 last;
 7076:             } elsif ($scope eq 'guest') {
 7077:                 $guest = $key;
 7078:             } elsif ($scope eq 'domains') {
 7079:                 push(@domains,$key);
 7080:             } elsif ($scope eq 'users') {
 7081:                 push(@users,$key);
 7082:             } elsif ($scope eq 'course') {
 7083:                 push(@courses,$key);
 7084:             } elsif ($scope eq 'group') {
 7085:                 push(@groups,$key);
 7086:             } elsif ($scope eq 'ip') {
 7087:                 push(@ips,$key);
 7088:             }
 7089:         }
 7090:         if ($public) {
 7091:             return 'ok';
 7092:         } elsif (@ips > 0) {
 7093:             my $allowed;
 7094:             foreach my $ipkey (@ips) {
 7095:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7096:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7097:                         $allowed = 1;
 7098:                         last; 
 7099:                     }
 7100:                 }
 7101:             }
 7102:             if ($allowed) {
 7103:                 return 'ok';
 7104:             }
 7105:         }
 7106:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7107:             if ($guest) {
 7108:                 return $guest;
 7109:             }
 7110:         } else {
 7111:             if (@domains > 0) {
 7112:                 foreach my $domkey (@domains) {
 7113:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7114:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7115:                             return 'ok';
 7116:                         }
 7117:                     }
 7118:                 }
 7119:             }
 7120:             if (@users > 0) {
 7121:                 foreach my $userkey (@users) {
 7122:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7123:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7124:                             if (ref($item) eq 'HASH') {
 7125:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7126:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7127:                                     return 'ok';
 7128:                                 }
 7129:                             }
 7130:                         }
 7131:                     } 
 7132:                 }
 7133:             }
 7134:             my %roleshash;
 7135:             my @courses_and_groups = @courses;
 7136:             push(@courses_and_groups,@groups); 
 7137:             if (@courses_and_groups > 0) {
 7138:                 my (%allgroups,%allroles); 
 7139:                 my ($start,$end,$role,$sec,$group);
 7140:                 foreach my $envkey (%env) {
 7141:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7142:                         my $cid = $2.'_'.$3; 
 7143:                         if ($1 eq 'gr') {
 7144:                             $group = $4;
 7145:                             $allgroups{$cid}{$group} = $env{$envkey};
 7146:                         } else {
 7147:                             if ($4 eq '') {
 7148:                                 $sec = 'none';
 7149:                             } else {
 7150:                                 $sec = $4;
 7151:                             }
 7152:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7153:                         }
 7154:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7155:                         my $cid = $2.'_'.$3;
 7156:                         if ($4 eq '') {
 7157:                             $sec = 'none';
 7158:                         } else {
 7159:                             $sec = $4;
 7160:                         }
 7161:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7162:                     }
 7163:                 }
 7164:                 if (keys(%allroles) == 0) {
 7165:                     return;
 7166:                 }
 7167:                 foreach my $key (@courses_and_groups) {
 7168:                     my %content = %{$$access_hash{$key}};
 7169:                     my $cnum = $content{'number'};
 7170:                     my $cdom = $content{'domain'};
 7171:                     my $cid = $cdom.'_'.$cnum;
 7172:                     if (!exists($allroles{$cid})) {
 7173:                         next;
 7174:                     }    
 7175:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7176:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7177:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7178:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7179:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7180:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7181:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7182:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7183:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7184:                                         if (grep/^all$/,@sections) {
 7185:                                             return 'ok';
 7186:                                         } else {
 7187:                                             if (grep/^$sec$/,@sections) {
 7188:                                                 return 'ok';
 7189:                                             }
 7190:                                         }
 7191:                                     }
 7192:                                 }
 7193:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7194:                                     if (grep/^none$/,@groups) {
 7195:                                         return 'ok';
 7196:                                     }
 7197:                                 } else {
 7198:                                     if (grep/^all$/,@groups) {
 7199:                                         return 'ok';
 7200:                                     } 
 7201:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7202:                                         if (grep/^$group$/,@groups) {
 7203:                                             return 'ok';
 7204:                                         }
 7205:                                     }
 7206:                                 } 
 7207:                             }
 7208:                         }
 7209:                     }
 7210:                 }
 7211:             }
 7212:             if ($guest) {
 7213:                 return $guest;
 7214:             }
 7215:         }
 7216:     }
 7217:     return;
 7218: }
 7219: 
 7220: sub course_group_datechecker {
 7221:     my ($dates,$now,$status) = @_;
 7222:     my ($start,$end) = split(/\./,$dates);
 7223:     if (!$start && !$end) {
 7224:         return 'ok';
 7225:     }
 7226:     if (grep/^active$/,@{$status}) {
 7227:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7228:             return 'ok';
 7229:         }
 7230:     }
 7231:     if (grep/^previous$/,@{$status}) {
 7232:         if ($end > $now ) {
 7233:             return 'ok';
 7234:         }
 7235:     }
 7236:     if (grep/^future$/,@{$status}) {
 7237:         if ($start > $now) {
 7238:             return 'ok';
 7239:         }
 7240:     }
 7241:     return; 
 7242: }
 7243: 
 7244: sub parse_portfolio_url {
 7245:     my ($url) = @_;
 7246: 
 7247:     my ($type,$udom,$unum,$group,$file_name);
 7248:     
 7249:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7250: 	$type = 1;
 7251:         $udom = $1;
 7252:         $unum = $2;
 7253:         $file_name = $3;
 7254:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7255: 	$type = 2;
 7256:         $udom = $1;
 7257:         $unum = $2;
 7258:         $group = $3;
 7259:         $file_name = $3.'/'.$4;
 7260:     }
 7261:     if (wantarray) {
 7262: 	return ($type,$udom,$unum,$file_name,$group);
 7263:     }
 7264:     return $type;
 7265: }
 7266: 
 7267: sub is_portfolio_url {
 7268:     my ($url) = @_;
 7269:     return scalar(&parse_portfolio_url($url));
 7270: }
 7271: 
 7272: sub is_portfolio_file {
 7273:     my ($file) = @_;
 7274:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7275:         return 1;
 7276:     }
 7277:     return;
 7278: }
 7279: 
 7280: sub usertools_access {
 7281:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7282:     my ($access,%tools);
 7283:     if ($context eq '') {
 7284:         $context = 'tools';
 7285:     }
 7286:     if ($context eq 'requestcourses') {
 7287:         %tools = (
 7288:                       official   => 1,
 7289:                       unofficial => 1,
 7290:                       community  => 1,
 7291:                       textbook   => 1,
 7292:                       placement  => 1,
 7293:                       lti        => 1,
 7294:                  );
 7295:     } elsif ($context eq 'requestauthor') {
 7296:         %tools = (
 7297:                       requestauthor => 1,
 7298:                  );
 7299:     } else {
 7300:         %tools = (
 7301:                       aboutme   => 1,
 7302:                       blog      => 1,
 7303:                       webdav    => 1,
 7304:                       portfolio => 1,
 7305:                  );
 7306:     }
 7307:     return if (!defined($tools{$tool}));
 7308: 
 7309:     if (($udom eq '') || ($uname eq '')) {
 7310:         $udom = $env{'user.domain'};
 7311:         $uname = $env{'user.name'};
 7312:     }
 7313: 
 7314:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7315:         if ($action ne 'reload') {
 7316:             if ($context eq 'requestcourses') {
 7317:                 return $env{'environment.canrequest.'.$tool};
 7318:             } elsif ($context eq 'requestauthor') {
 7319:                 return $env{'environment.canrequest.author'};
 7320:             } else {
 7321:                 return $env{'environment.availabletools.'.$tool};
 7322:             }
 7323:         }
 7324:     }
 7325: 
 7326:     my ($toolstatus,$inststatus,$envkey);
 7327:     if ($context eq 'requestauthor') {
 7328:         $envkey = $context; 
 7329:     } else {
 7330:         $envkey = $context.'.'.$tool;
 7331:     }
 7332: 
 7333:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7334:          ($action ne 'reload')) {
 7335:         $toolstatus = $env{'environment.'.$envkey};
 7336:         $inststatus = $env{'environment.inststatus'};
 7337:     } else {
 7338:         if (ref($userenvref) eq 'HASH') {
 7339:             $toolstatus = $userenvref->{$envkey};
 7340:             $inststatus = $userenvref->{'inststatus'};
 7341:         } else {
 7342:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7343:             $toolstatus = $userenv{$envkey};
 7344:             $inststatus = $userenv{'inststatus'};
 7345:         }
 7346:     }
 7347: 
 7348:     if ($toolstatus ne '') {
 7349:         if ($toolstatus) {
 7350:             $access = 1;
 7351:         } else {
 7352:             $access = 0;
 7353:         }
 7354:         return $access;
 7355:     }
 7356: 
 7357:     my ($is_adv,%domdef);
 7358:     if (ref($is_advref) eq 'HASH') {
 7359:         $is_adv = $is_advref->{'is_adv'};
 7360:     } else {
 7361:         $is_adv = &is_advanced_user($udom,$uname);
 7362:     }
 7363:     if (ref($domdefref) eq 'HASH') {
 7364:         %domdef = %{$domdefref};
 7365:     } else {
 7366:         %domdef = &get_domain_defaults($udom);
 7367:     }
 7368:     if (ref($domdef{$tool}) eq 'HASH') {
 7369:         if ($is_adv) {
 7370:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7371:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7372:                     $access = 1;
 7373:                 } else {
 7374:                     $access = 0;
 7375:                 }
 7376:                 return $access;
 7377:             }
 7378:         }
 7379:         if ($inststatus ne '') {
 7380:             my ($hasaccess,$hasnoaccess);
 7381:             foreach my $affiliation (split(/:/,$inststatus)) {
 7382:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7383:                     if ($domdef{$tool}{$affiliation}) {
 7384:                         $hasaccess = 1;
 7385:                     } else {
 7386:                         $hasnoaccess = 1;
 7387:                     }
 7388:                 }
 7389:             }
 7390:             if ($hasaccess || $hasnoaccess) {
 7391:                 if ($hasaccess) {
 7392:                     $access = 1;
 7393:                 } elsif ($hasnoaccess) {
 7394:                     $access = 0; 
 7395:                 }
 7396:                 return $access;
 7397:             }
 7398:         } else {
 7399:             if ($domdef{$tool}{'default'} ne '') {
 7400:                 if ($domdef{$tool}{'default'}) {
 7401:                     $access = 1;
 7402:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7403:                     $access = 0;
 7404:                 }
 7405:                 return $access;
 7406:             }
 7407:         }
 7408:     } else {
 7409:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7410:             $access = 1;
 7411:         } else {
 7412:             $access = 0;
 7413:         }
 7414:         return $access;
 7415:     }
 7416: }
 7417: 
 7418: sub is_course_owner {
 7419:     my ($cdom,$cnum,$udom,$uname) = @_;
 7420:     if (($udom eq '') || ($uname eq '')) {
 7421:         $udom = $env{'user.domain'};
 7422:         $uname = $env{'user.name'};
 7423:     }
 7424:     unless (($udom eq '') || ($uname eq '')) {
 7425:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7426:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7427:                 return 1;
 7428:             } else {
 7429:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7430:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7431:                     return 1;
 7432:                 }
 7433:             }
 7434:         }
 7435:     }
 7436:     return;
 7437: }
 7438: 
 7439: sub is_advanced_user {
 7440:     my ($udom,$uname) = @_;
 7441:     if ($udom ne '' && $uname ne '') {
 7442:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7443:             if (wantarray) {
 7444:                 return ($env{'user.adv'},$env{'user.author'});
 7445:             } else {
 7446:                 return $env{'user.adv'};
 7447:             }
 7448:         }
 7449:     }
 7450:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7451:     my %allroles;
 7452:     my ($is_adv,$is_author);
 7453:     foreach my $role (keys(%roleshash)) {
 7454:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7455:         my $area = '/'.$tdomain.'/'.$trest;
 7456:         if ($sec ne '') {
 7457:             $area .= '/'.$sec;
 7458:         }
 7459:         if (($area ne '') && ($trole ne '')) {
 7460:             my $spec=$trole.'.'.$area;
 7461:             if ($trole =~ /^cr\//) {
 7462:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7463:             } elsif ($trole ne 'gr') {
 7464:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7465:             }
 7466:             if ($trole eq 'au') {
 7467:                 $is_author = 1;
 7468:             }
 7469:         }
 7470:     }
 7471:     foreach my $role (keys(%allroles)) {
 7472:         last if ($is_adv);
 7473:         foreach my $item (split(/:/,$allroles{$role})) {
 7474:             if ($item ne '') {
 7475:                 my ($privilege,$restrictions)=split(/&/,$item);
 7476:                 if ($privilege eq 'adv') {
 7477:                     $is_adv = 1;
 7478:                     last;
 7479:                 }
 7480:             }
 7481:         }
 7482:     }
 7483:     if (wantarray) {
 7484:         return ($is_adv,$is_author);
 7485:     }
 7486:     return $is_adv;
 7487: }
 7488: 
 7489: sub check_can_request {
 7490:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7491:     my $canreq = 0;
 7492:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7493:         $uname = $env{'user.name'};
 7494:         $udom = $env{'user.domain'};
 7495:     }
 7496:     my ($types,$typename) = &Apache::loncommon::course_types();
 7497:     my @options = ('approval','validate','autolimit');
 7498:     my $optregex = join('|',@options);
 7499:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7500:         foreach my $type (@{$types}) {
 7501:             if (&usertools_access($uname,$udom,$type,undef,
 7502:                                   'requestcourses')) {
 7503:                 $canreq ++;
 7504:                 if (ref($request_domains) eq 'HASH') {
 7505:                     push(@{$request_domains->{$type}},$udom);
 7506:                 }
 7507:                 if ($dom eq $udom) {
 7508:                     $can_request->{$type} = 1;
 7509:                 }
 7510:             }
 7511:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7512:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7513:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7514:                 if (@curr > 0) {
 7515:                     foreach my $item (@curr) {
 7516:                         if (ref($request_domains) eq 'HASH') {
 7517:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7518:                             if ($otherdom ne '') {
 7519:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7520:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7521:                                         push(@{$request_domains->{$type}},$otherdom);
 7522:                                     }
 7523:                                 } else {
 7524:                                     push(@{$request_domains->{$type}},$otherdom);
 7525:                                 }
 7526:                             }
 7527:                         }
 7528:                     }
 7529:                     unless ($dom eq $env{'user.domain'}) {
 7530:                         $canreq ++;
 7531:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7532:                             $can_request->{$type} = 1;
 7533:                         }
 7534:                     }
 7535:                 }
 7536:             }
 7537:         }
 7538:     }
 7539:     return $canreq;
 7540: }
 7541: 
 7542: # ---------------------------------------------- Custom access rule evaluation
 7543: 
 7544: sub customaccess {
 7545:     my ($priv,$uri)=@_;
 7546:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7547:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7548:     $udom = &LONCAPA::clean_domain($udom);
 7549:     $ucrs = &LONCAPA::clean_username($ucrs);
 7550:     my $access=0;
 7551:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7552: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7553: 	if ($type eq 'user') {
 7554: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7555: 		my ($tdom,$tuname)=split(m{/},$scope);
 7556: 		if ($tdom) {
 7557: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7558: 		}
 7559: 		if ($tuname) {
 7560: 		    if ($tuname ne $env{'user.name'}) { next; }
 7561: 		}
 7562: 		$access=($effect eq 'allow');
 7563: 		last;
 7564: 	    }
 7565: 	} else {
 7566: 	    if ($role) {
 7567: 		if ($role ne $urole) { next; }
 7568: 	    }
 7569: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7570: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7571: 		if ($tdom) {
 7572: 		    if ($tdom ne $udom) { next; }
 7573: 		}
 7574: 		if ($tcrs) {
 7575: 		    if ($tcrs ne $ucrs) { next; }
 7576: 		}
 7577: 		if ($tsec) {
 7578: 		    if ($tsec ne $usec) { next; }
 7579: 		}
 7580: 		$access=($effect eq 'allow');
 7581: 		last;
 7582: 	    }
 7583: 	    if ($realm eq '' && $role eq '') {
 7584: 		$access=($effect eq 'allow');
 7585: 	    }
 7586: 	}
 7587:     }
 7588:     return $access;
 7589: }
 7590: 
 7591: # ------------------------------------------------- Check for a user privilege
 7592: 
 7593: sub allowed {
 7594:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7595:     my $ver_orguri=$uri;
 7596:     $uri=&deversion($uri);
 7597:     my $orguri=$uri;
 7598:     $uri=&declutter($uri);
 7599: 
 7600:     if ($priv eq 'evb') {
 7601: # Evade communication block restrictions for specified role in a course
 7602:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7603:             return $1;
 7604:         } else {
 7605:             return;
 7606:         }
 7607:     }
 7608: 
 7609:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7610: # Free bre access to adm and meta resources
 7611:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7612: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7613: 	&& ($priv eq 'bre')) {
 7614: 	return 'F';
 7615:     }
 7616: 
 7617: # Free bre access to user's own portfolio contents
 7618:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7619:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7620: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7621:         my %setters;
 7622:         my ($startblock,$endblock) = 
 7623:             &Apache::loncommon::blockcheck(\%setters,'port');
 7624:         if ($startblock && $endblock) {
 7625:             return 'B';
 7626:         } else {
 7627:             return 'F';
 7628:         }
 7629:     }
 7630: 
 7631: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7632:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7633:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7634:         if (exists($env{'request.course.id'})) {
 7635:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7636:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7637:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7638:                 my $courseprivid=$env{'request.course.id'};
 7639:                 $courseprivid=~s/\_/\//;
 7640:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7641:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7642:                     return $1; 
 7643:                 } else {
 7644:                     if ($env{'request.course.sec'}) {
 7645:                         $courseprivid.='/'.$env{'request.course.sec'};
 7646:                     }
 7647:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7648:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7649:                         return $2;
 7650:                     }
 7651:                 }
 7652:             }
 7653:         }
 7654:     }
 7655: 
 7656: # Free bre to public access
 7657: 
 7658:     if ($priv eq 'bre') {
 7659:         my $copyright;
 7660:         unless ($uri =~ /ext\.tool/) {
 7661:             $copyright=&metadata($uri,'copyright');
 7662:         }
 7663: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7664:            return 'F'; 
 7665:         }
 7666:         if ($copyright eq 'priv') {
 7667:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7668: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7669: 		return '';
 7670:             }
 7671:         }
 7672:         if ($copyright eq 'domain') {
 7673:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7674: 	    unless (($env{'user.domain'} eq $1) ||
 7675:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7676: 		return '';
 7677:             }
 7678:         }
 7679:         if ($env{'request.role'}=~ /li\.\//) {
 7680:             # Library role, so allow browsing of resources in this domain.
 7681:             return 'F';
 7682:         }
 7683:         if ($copyright eq 'custom') {
 7684: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7685:         }
 7686:     }
 7687:     # Domain coordinator is trying to create a course
 7688:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7689:         # uri is the requested domain in this case.
 7690:         # comparison to 'request.role.domain' shows if the user has selected
 7691:         # a role of dc for the domain in question.
 7692:         return 'F' if ($uri eq $env{'request.role.domain'});
 7693:     }
 7694: 
 7695:     my $thisallowed='';
 7696:     my $statecond=0;
 7697:     my $courseprivid='';
 7698: 
 7699:     my $ownaccess;
 7700:     # Community Coordinator or Assistant Co-author browsing resource space.
 7701:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7702:         if ($uri eq '') {
 7703:             $ownaccess = 1;
 7704:         } else {
 7705:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7706:                 my $udom = $env{'user.domain'};
 7707:                 my $uname = $env{'user.name'};
 7708:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7709:                     $ownaccess = 1;
 7710:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7711:                     unless ($uri =~ m{\.\./}) {
 7712:                         $ownaccess = 1;
 7713:                     }
 7714:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7715:                     my $now = time;
 7716:                     if ($uri =~ m{^([^/]+)/?$}) {
 7717:                         my $adom = $1;
 7718:                         foreach my $key (keys(%env)) {
 7719:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7720:                                 my ($start,$end) = split('.',$env{$key});
 7721:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7722:                                     $ownaccess = 1;
 7723:                                     last;
 7724:                                 }
 7725:                             }
 7726:                         }
 7727:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7728:                         my $adom = $1;
 7729:                         my $aname = $2;
 7730:                         foreach my $role ('ca','aa') { 
 7731:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7732:                                 my ($start,$end) =
 7733:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7734:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7735:                                     $ownaccess = 1;
 7736:                                     last;
 7737:                                 }
 7738:                             }
 7739:                         }
 7740:                     }
 7741:                 }
 7742:             }
 7743:         }
 7744:     }
 7745: 
 7746: # Course
 7747: 
 7748:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7749:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7750:             $thisallowed.=$1;
 7751:         }
 7752:     }
 7753: 
 7754: # Domain
 7755: 
 7756:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7757:        =~/\Q$priv\E\&([^\:]*)/) {
 7758:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7759:             $thisallowed.=$1;
 7760:         }
 7761:     }
 7762: 
 7763: # User who is not author or co-author might still be able to edit
 7764: # resource of an author in the domain (e.g., if Domain Coordinator).
 7765:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7766:         (&allowed('mdc',$env{'request.course.id'}))) {
 7767:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7768:             $thisallowed.=$1;
 7769:         }
 7770:     }
 7771: 
 7772: # Course: uri itself is a course
 7773:     my $courseuri=$uri;
 7774:     $courseuri=~s/\_(\d)/\/$1/;
 7775:     $courseuri=~s/^([^\/])/\/$1/;
 7776: 
 7777:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7778:        =~/\Q$priv\E\&([^\:]*)/) {
 7779:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7780:             $thisallowed.=$1;
 7781:         }
 7782:     }
 7783: 
 7784: # URI is an uploaded document for this course, default permissions don't matter
 7785: # not allowing 'edit' access (editupload) to uploaded course docs
 7786:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7787: 	$thisallowed='';
 7788:         my ($match)=&is_on_map($uri);
 7789:         if ($match) {
 7790:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7791:                   =~/\Q$priv\E\&([^\:]*)/) {
 7792:                 my $value = $1;
 7793:                 if ($noblockcheck) {
 7794:                     $thisallowed.=$value;
 7795:                 } else {
 7796:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7797:                     if (@blockers > 0) {
 7798:                         $thisallowed = 'B';
 7799:                     } else {
 7800:                         $thisallowed.=$value;
 7801:                     }
 7802:                 }
 7803:             }
 7804:         } else {
 7805:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7806:             if ($refuri) {
 7807:                 if ($refuri =~ m|^/adm/|) {
 7808:                     $thisallowed='F';
 7809:                 } else {
 7810:                     $refuri=&declutter($refuri);
 7811:                     my ($match) = &is_on_map($refuri);
 7812:                     if ($match) {
 7813:                         if ($noblockcheck) {
 7814:                             $thisallowed='F';
 7815:                         } else {
 7816:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7817:                             if (@blockers > 0) {
 7818:                                 $thisallowed = 'B';
 7819:                             } else {
 7820:                                 $thisallowed='F';
 7821:                             }
 7822:                         }
 7823:                     }
 7824:                 }
 7825:             }
 7826:         }
 7827:     }
 7828: 
 7829:     if ($priv eq 'bre'
 7830: 	&& $thisallowed ne 'F' 
 7831: 	&& $thisallowed ne '2'
 7832: 	&& &is_portfolio_url($uri)) {
 7833: 	$thisallowed = &portfolio_access($uri,$clientip);
 7834:     }
 7835: 
 7836: # Full access at system, domain or course-wide level? Exit.
 7837:     if ($thisallowed=~/F/) {
 7838: 	return 'F';
 7839:     }
 7840: 
 7841: # If this is generating or modifying users, exit with special codes
 7842: 
 7843:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7844: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7845: 	    my ($audom,$auname)=split('/',$uri);
 7846: # no author name given, so this just checks on the general right to make a co-author in this domain
 7847: 	    unless ($auname) { return $thisallowed; }
 7848: # an author name is given, so we are about to actually make a co-author for a certain account
 7849: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7850: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7851: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7852: 	}
 7853: 	return $thisallowed;
 7854:     }
 7855: #
 7856: # Gathered so far: system, domain and course wide privileges
 7857: #
 7858: # Course: See if uri or referer is an individual resource that is part of 
 7859: # the course
 7860: 
 7861:     if ($env{'request.course.id'}) {
 7862: 
 7863:        $courseprivid=$env{'request.course.id'};
 7864:        if ($env{'request.course.sec'}) {
 7865:           $courseprivid.='/'.$env{'request.course.sec'};
 7866:        }
 7867:        $courseprivid=~s/\_/\//;
 7868:        my $checkreferer=1;
 7869:        my ($match,$cond)=&is_on_map($uri);
 7870:        if ($match) {
 7871:            $statecond=$cond;
 7872:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7873:                =~/\Q$priv\E\&([^\:]*)/) {
 7874:                my $value = $1;
 7875:                if ($priv eq 'bre') {
 7876:                    if ($noblockcheck) {
 7877:                        $thisallowed.=$value;
 7878:                    } else {
 7879:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7880:                        if (@blockers > 0) {
 7881:                            $thisallowed = 'B';
 7882:                        } else {
 7883:                            $thisallowed.=$value;
 7884:                        }
 7885:                    }
 7886:                } else {
 7887:                    $thisallowed.=$value;
 7888:                }
 7889:                $checkreferer=0;
 7890:            }
 7891:        }
 7892:        
 7893:        if ($checkreferer) {
 7894: 	  my $refuri=$env{'httpref.'.$orguri};
 7895:             unless ($refuri) {
 7896:                 foreach my $key (keys(%env)) {
 7897: 		    if ($key=~/^httpref\..*\*/) {
 7898: 			my $pattern=$key;
 7899:                         $pattern=~s/^httpref\.\/res\///;
 7900:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7901:                         $pattern=~s/\//\\\//g;
 7902:                         if ($orguri=~/$pattern/) {
 7903: 			    $refuri=$env{$key};
 7904:                         }
 7905:                     }
 7906:                 }
 7907:             }
 7908: 
 7909:          if ($refuri) { 
 7910: 	  $refuri=&declutter($refuri);
 7911:           my ($match,$cond)=&is_on_map($refuri);
 7912:             if ($match) {
 7913:               my $refstatecond=$cond;
 7914:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7915:                   =~/\Q$priv\E\&([^\:]*)/) {
 7916:                   my $value = $1;
 7917:                   if ($priv eq 'bre') {
 7918:                       if ($noblockcheck) {
 7919:                           $thisallowed.=$value;
 7920:                       } else {
 7921:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7922:                           if (@blockers > 0) {
 7923:                               $thisallowed = 'B';
 7924:                           } else {
 7925:                               $thisallowed.=$value;
 7926:                           }
 7927:                       }
 7928:                   } else {
 7929:                       $thisallowed.=$value;
 7930:                   }
 7931:                   $uri=$refuri;
 7932:                   $statecond=$refstatecond;
 7933:               }
 7934:           }
 7935:         }
 7936:        }
 7937:    }
 7938: 
 7939: #
 7940: # Gathered now: all privileges that could apply, and condition number
 7941: # 
 7942: #
 7943: # Full or no access?
 7944: #
 7945: 
 7946:     if ($thisallowed=~/F/) {
 7947: 	return 'F';
 7948:     }
 7949: 
 7950:     unless ($thisallowed) {
 7951:         return '';
 7952:     }
 7953: 
 7954: # Restrictions exist, deal with them
 7955: #
 7956: #   C:according to course preferences
 7957: #   R:according to resource settings
 7958: #   L:unless locked
 7959: #   X:according to user session state
 7960: #
 7961: 
 7962: # Possibly locked functionality, check all courses
 7963: # Locks might take effect only after 10 minutes cache expiration for other
 7964: # courses, and 2 minutes for current course
 7965: 
 7966:     my $envkey;
 7967:     if ($thisallowed=~/L/) {
 7968:         foreach $envkey (keys(%env)) {
 7969:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7970:                my $courseid=$2;
 7971:                my $roleid=$1.'.'.$2;
 7972:                $courseid=~s/^\///;
 7973:                my $expiretime=600;
 7974:                if ($env{'request.role'} eq $roleid) {
 7975: 		  $expiretime=120;
 7976:                }
 7977: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7978:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7979:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7980: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7981:                }
 7982:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7983:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7984: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7985:                        &log($env{'user.domain'},$env{'user.name'},
 7986:                             $env{'user.home'},
 7987:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7988:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7989:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7990: 		       return '';
 7991:                    }
 7992:                }
 7993:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7994:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7995: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7996:                        &log($env{'user.domain'},$env{'user.name'},
 7997:                             $env{'user.home'},
 7998:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7999:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8000:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8001: 		       return '';
 8002:                    }
 8003:                }
 8004: 	   }
 8005:        }
 8006:     }
 8007:    
 8008: #
 8009: # Rest of the restrictions depend on selected course
 8010: #
 8011: 
 8012:     unless ($env{'request.course.id'}) {
 8013: 	if ($thisallowed eq 'A') {
 8014: 	    return 'A';
 8015:         } elsif ($thisallowed eq 'B') {
 8016:             return 'B';
 8017: 	} else {
 8018: 	    return '1';
 8019: 	}
 8020:     }
 8021: 
 8022: #
 8023: # Now user is definitely in a course
 8024: #
 8025: 
 8026: 
 8027: # Course preferences
 8028: 
 8029:    if ($thisallowed=~/C/) {
 8030:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8031:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8032:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8033: 	   =~/\Q$rolecode\E/) {
 8034: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8035: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8036: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8037: 			$env{'request.course.id'});
 8038: 	   }
 8039:            return '';
 8040:        }
 8041: 
 8042:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8043: 	   =~/\Q$unamedom\E/) {
 8044: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8045: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8046: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8047: 			$env{'request.course.id'});
 8048: 	   }
 8049:            return '';
 8050:        }
 8051:    }
 8052: 
 8053: # Resource preferences
 8054: 
 8055:    if ($thisallowed=~/R/) {
 8056:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8057:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8058: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8059: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8060: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8061: 	   }
 8062: 	   return '';
 8063:        }
 8064:    }
 8065: 
 8066: # Restricted by state or randomout?
 8067: 
 8068:    if ($thisallowed=~/X/) {
 8069:       if ($env{'acc.randomout'}) {
 8070: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8071:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8072:             return ''; 
 8073:          }
 8074:       }
 8075:       if (&condval($statecond)) {
 8076: 	 return '2';
 8077:       } else {
 8078:          return '';
 8079:       }
 8080:    }
 8081: 
 8082:     if ($thisallowed eq 'A') {
 8083: 	return 'A';
 8084:     } elsif ($thisallowed eq 'B') {
 8085:         return 'B';
 8086:     }
 8087:    return 'F';
 8088: }
 8089: 
 8090: # ------------------------------------------- Check construction space access
 8091: 
 8092: sub constructaccess {
 8093:     my ($url,$setpriv)=@_;
 8094: 
 8095: # We do not allow editing of previous versions of files
 8096:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8097: 
 8098: # Get username and domain from URL
 8099:     my ($ownername,$ownerdomain,$ownerhome);
 8100: 
 8101:     ($ownerdomain,$ownername) =
 8102:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8103: 
 8104: # The URL does not really point to any authorspace, forget it
 8105:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8106: 
 8107: # Now we need to see if the user has access to the authorspace of
 8108: # $ownername at $ownerdomain
 8109: 
 8110:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8111: # Real author for this?
 8112:        $ownerhome = $env{'user.home'};
 8113:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8114:           return ($ownername,$ownerdomain,$ownerhome);
 8115:        }
 8116:     } else {
 8117: # Co-author for this?
 8118:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8119:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8120:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8121:             return ($ownername,$ownerdomain,$ownerhome);
 8122:         }
 8123:         if ($env{'request.course.id'}) {
 8124:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8125:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8126:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8127:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8128:                     return ($ownername,$ownerdomain,$ownerhome);
 8129:                 }
 8130:             }
 8131:         }
 8132:     }
 8133: 
 8134: # We don't have any access right now. If we are not possibly going to do anything about this,
 8135: # we might as well leave
 8136:    unless ($setpriv) { return ''; }
 8137: 
 8138: # Backdoor access?
 8139:     my $allowed=&allowed('eco',$ownerdomain);
 8140: # Nope
 8141:     unless ($allowed) { return ''; }
 8142: # Looks like we may have access, but could be locked by the owner of the construction space
 8143:     if ($allowed eq 'U') {
 8144:         my %blocked=&get('environment',['domcoord.author'],
 8145:                          $ownerdomain,$ownername);
 8146: # Is blocked by owner
 8147:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8148:     }
 8149:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8150: # Grant temporary access
 8151:         my $then=$env{'user.login.time'};
 8152:         my $update=$env{'user.update.time'};
 8153:         if (!$update) { $update = $then; }
 8154:         my $refresh=$env{'user.refresh.time'};
 8155:         if (!$refresh) { $refresh = $update; }
 8156:         my $now = time;
 8157:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8158:                            $now,'ca','constructaccess');
 8159:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8160:         return($ownername,$ownerdomain,$ownerhome);
 8161:     }
 8162: # No business here
 8163:     return '';
 8164: }
 8165: 
 8166: # ----------------------------------------------------------- Content Blocking
 8167: 
 8168: {
 8169: # Caches for faster Course Contents display where content blocking
 8170: # is in operation (i.e., interval param set) for timed quiz.
 8171: #
 8172: # User for whom data are being temporarily cached.
 8173: my $cacheduser='';
 8174: # Cached blockers for this user (a hash of blocking items). 
 8175: my %cachedblockers=();
 8176: # When the data were last cached.
 8177: my $cachedlast='';
 8178: 
 8179: sub load_all_blockers {
 8180:     my ($uname,$udom,$blocks)=@_;
 8181:     if (($uname ne '') && ($udom ne '')) { 
 8182:         if (($cacheduser eq $uname.':'.$udom) &&
 8183:             (abs($cachedlast-time)<5)) {
 8184:             return;
 8185:         }
 8186:     }
 8187:     $cachedlast=time;
 8188:     $cacheduser=$uname.':'.$udom;
 8189:     %cachedblockers = &get_commblock_resources($blocks);
 8190: }
 8191: 
 8192: sub get_comm_blocks {
 8193:     my ($cdom,$cnum) = @_;
 8194:     if ($cdom eq '' || $cnum eq '') {
 8195:         return unless ($env{'request.course.id'});
 8196:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8197:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8198:     }
 8199:     my %commblocks;
 8200:     my $hashid=$cdom.'_'.$cnum;
 8201:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8202:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8203:         %commblocks = %{$blocksref};
 8204:     } else {
 8205:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8206:         my $cachetime = 600;
 8207:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8208:     }
 8209:     return %commblocks;
 8210: }
 8211: 
 8212: sub get_commblock_resources {
 8213:     my ($blocks) = @_;
 8214:     my %blockers = ();
 8215:     return %blockers unless ($env{'request.course.id'});
 8216:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8217:     my %commblocks;
 8218:     if (ref($blocks) eq 'HASH') {
 8219:         %commblocks = %{$blocks};
 8220:     } else {
 8221:         %commblocks = &get_comm_blocks();
 8222:     }
 8223:     return %blockers unless (keys(%commblocks) > 0); 
 8224:     my $navmap = Apache::lonnavmaps::navmap->new();
 8225:     return %blockers unless (ref($navmap));
 8226:     my $now = time;
 8227:     foreach my $block (keys(%commblocks)) {
 8228:         if ($block =~ /^(\d+)____(\d+)$/) {
 8229:             my ($start,$end) = ($1,$2);
 8230:             if ($start <= $now && $end >= $now) {
 8231:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8232:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8233:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8234:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8235:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8236:                             }
 8237:                         }
 8238:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8239:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8240:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8241:                             }
 8242:                         }
 8243:                     }
 8244:                 }
 8245:             }
 8246:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8247:             my $item = $1;
 8248:             my @to_test;
 8249:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8250:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8251:                     my @interval;
 8252:                     my $type = 'map';
 8253:                     if ($item eq 'course') {
 8254:                         $type = 'course';
 8255:                         @interval=&EXT("resource.0.interval");
 8256:                     } else {
 8257:                         if ($item =~ /___\d+___/) {
 8258:                             $type = 'resource';
 8259:                             @interval=&EXT("resource.0.interval",$item);
 8260:                             if (ref($navmap)) {                        
 8261:                                 my $res = $navmap->getBySymb($item); 
 8262:                                 push(@to_test,$res);
 8263:                             }
 8264:                         } else {
 8265:                             my $mapsymb = &symbread($item,1);
 8266:                             if ($mapsymb) {
 8267:                                 if (ref($navmap)) {
 8268:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8269:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8270:                                     foreach my $res (@to_test) {
 8271:                                         my $symb = $res->symb();
 8272:                                         next if ($symb eq $mapsymb);
 8273:                                         if ($symb ne '') {
 8274:                                             @interval=&EXT("resource.0.interval",$symb);
 8275:                                             if ($interval[1] eq 'map') {
 8276:                                                 last;
 8277:                                             }
 8278:                                         }
 8279:                                     }
 8280:                                 }
 8281:                             }
 8282:                         }
 8283:                     }
 8284:                     if ($interval[0] =~ /^(\d+)/) {
 8285:                         my $timelimit = $1; 
 8286:                         my $first_access;
 8287:                         if ($type eq 'resource') {
 8288:                             $first_access=&get_first_access($interval[1],$item);
 8289:                         } elsif ($type eq 'map') {
 8290:                             $first_access=&get_first_access($interval[1],undef,$item);
 8291:                         } else {
 8292:                             $first_access=&get_first_access($interval[1]);
 8293:                         }
 8294:                         if ($first_access) {
 8295:                             my $timesup = $first_access+$timelimit;
 8296:                             if ($timesup > $now) {
 8297:                                 my $activeblock;
 8298:                                 foreach my $res (@to_test) {
 8299:                                     if ($res->answerable()) {
 8300:                                         $activeblock = 1;
 8301:                                         last;
 8302:                                     }
 8303:                                 }
 8304:                                 if ($activeblock) {
 8305:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8306:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8307:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8308:                                          }
 8309:                                     }
 8310:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8311:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8312:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8313:                                         }
 8314:                                     }
 8315:                                 }
 8316:                             }
 8317:                         }
 8318:                     }
 8319:                 }
 8320:             }
 8321:         }
 8322:     }
 8323:     return %blockers;
 8324: }
 8325: 
 8326: sub has_comm_blocking {
 8327:     my ($priv,$symb,$uri,$blocks) = @_;
 8328:     my @blockers;
 8329:     return unless ($env{'request.course.id'});
 8330:     return unless ($priv eq 'bre');
 8331:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8332:     return if ($env{'request.state'} eq 'construct');
 8333:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8334:     return unless (keys(%cachedblockers) > 0);
 8335:     my (%possibles,@symbs);
 8336:     if (!$symb) {
 8337:         $symb = &symbread($uri,1,1,1,\%possibles);
 8338:     }
 8339:     if ($symb) {
 8340:         @symbs = ($symb);
 8341:     } elsif (keys(%possibles)) { 
 8342:         @symbs = keys(%possibles);
 8343:     }
 8344:     my $noblock;
 8345:     foreach my $symb (@symbs) {
 8346:         last if ($noblock);
 8347:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8348:         foreach my $block (keys(%cachedblockers)) {
 8349:             if ($block =~ /^firstaccess____(.+)$/) {
 8350:                 my $item = $1;
 8351:                 if (($item eq $map) || ($item eq $symb)) {
 8352:                     $noblock = 1;
 8353:                     last;
 8354:                 }
 8355:             }
 8356:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8357:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8358:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8359:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8360:                             push(@blockers,$block);
 8361:                         }
 8362:                     }
 8363:                 }
 8364:             }
 8365:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8366:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8367:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8368:                         push(@blockers,$block);
 8369:                     }
 8370:                 }
 8371:             }
 8372:         }
 8373:     }
 8374:     return if ($noblock);
 8375:     return @blockers;
 8376: }
 8377: }
 8378: 
 8379: # -------------------------------- Deversion and split uri into path an filename   
 8380: 
 8381: #
 8382: #   Removes the version from a URI and
 8383: #   splits it in to its filename and path to the filename.
 8384: #   Seems like File::Basename could have done this more clearly.
 8385: #   Parameters:
 8386: #      $uri   - input URI
 8387: #   Returns:
 8388: #     Two element list consisting of 
 8389: #     $pathname  - the URI up to and excluding the trailing /
 8390: #     $filename  - The part of the URI following the last /
 8391: #  NOTE:
 8392: #    Another realization of this is simply:
 8393: #    use File::Basename;
 8394: #    ...
 8395: #    $uri = shift;
 8396: #    $filename = basename($uri);
 8397: #    $path     = dirname($uri);
 8398: #    return ($filename, $path);
 8399: #
 8400: #     The implementation below is probably faster however.
 8401: #
 8402: sub split_uri_for_cond {
 8403:     my $uri=&deversion(&declutter(shift));
 8404:     my @uriparts=split(/\//,$uri);
 8405:     my $filename=pop(@uriparts);
 8406:     my $pathname=join('/',@uriparts);
 8407:     return ($pathname,$filename);
 8408: }
 8409: # --------------------------------------------------- Is a resource on the map?
 8410: 
 8411: sub is_on_map {
 8412:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8413:     #Trying to find the conditional for the file
 8414:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8415: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8416:     if ($match) {
 8417: 	return (1,$1);
 8418:     } else {
 8419: 	return (0,0);
 8420:     }
 8421: }
 8422: 
 8423: # --------------------------------------------------------- Get symb from alias
 8424: 
 8425: sub get_symb_from_alias {
 8426:     my $symb=shift;
 8427:     my ($map,$resid,$url)=&decode_symb($symb);
 8428: # Already is a symb
 8429:     if ($url) { return $symb; }
 8430: # Must be an alias
 8431:     my $aliassymb='';
 8432:     my %bighash;
 8433:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8434:                             &GDBM_READER(),0640)) {
 8435:         my $rid=$bighash{'mapalias_'.$symb};
 8436: 	if ($rid) {
 8437: 	    my ($mapid,$resid)=split(/\./,$rid);
 8438: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8439: 				    $resid,$bighash{'src_'.$rid});
 8440: 	}
 8441:         untie %bighash;
 8442:     }
 8443:     return $aliassymb;
 8444: }
 8445: 
 8446: # ----------------------------------------------------------------- Define Role
 8447: 
 8448: sub definerole {
 8449:   if (allowed('mcr','/')) {
 8450:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8451:     foreach my $role (split(':',$sysrole)) {
 8452: 	my ($crole,$cqual)=split(/\&/,$role);
 8453:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8454:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8455: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8456:                return "refused:s:$crole&$cqual"; 
 8457:             }
 8458:         }
 8459:     }
 8460:     foreach my $role (split(':',$domrole)) {
 8461: 	my ($crole,$cqual)=split(/\&/,$role);
 8462:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8463:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8464: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8465:                return "refused:d:$crole&$cqual"; 
 8466:             }
 8467:         }
 8468:     }
 8469:     foreach my $role (split(':',$courole)) {
 8470: 	my ($crole,$cqual)=split(/\&/,$role);
 8471:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8472:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8473: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8474:                return "refused:c:$crole&$cqual"; 
 8475:             }
 8476:         }
 8477:     }
 8478:     my $uhome;
 8479:     if (($uname ne '') && ($udom ne '')) {
 8480:         $uhome = &homeserver($uname,$udom);
 8481:         return $uhome if ($uhome eq 'no_host');
 8482:     } else {
 8483:         $uname = $env{'user.name'};
 8484:         $udom = $env{'user.domain'};
 8485:         $uhome = $env{'user.home'};
 8486:     }
 8487:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8488:                 "$udom:$uname:rolesdef_$rolename=".
 8489:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8490:     return reply($command,$uhome);
 8491:   } else {
 8492:     return 'refused';
 8493:   }
 8494: }
 8495: 
 8496: # ---------------- Make a metadata query against the network of library servers
 8497: 
 8498: sub metadata_query {
 8499:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8500:     my %rhash;
 8501:     my %libserv = &all_library();
 8502:     my @server_list = (defined($server_array) ? @$server_array
 8503:                                               : keys(%libserv) );
 8504:     for my $server (@server_list) {
 8505:         my $domains = ''; 
 8506:         if (ref($domains_hash) eq 'HASH') {
 8507:             $domains = $domains_hash->{$server}; 
 8508:         }
 8509: 	unless ($custom or $customshow) {
 8510: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8511: 	    $rhash{$server}=$reply;
 8512: 	}
 8513: 	else {
 8514: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8515: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8516: 			     $server);
 8517: 	    $rhash{$server}=$reply;
 8518: 	}
 8519:     }
 8520:     return \%rhash;
 8521: }
 8522: 
 8523: # ----------------------------------------- Send log queries and wait for reply
 8524: 
 8525: sub log_query {
 8526:     my ($uname,$udom,$query,%filters)=@_;
 8527:     my $uhome=&homeserver($uname,$udom);
 8528:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8529:     my $uhost=&hostname($uhome);
 8530:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8531:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8532:                        $uhome);
 8533:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8534:     return get_query_reply($queryid);
 8535: }
 8536: 
 8537: # -------------------------- Update MySQL table for portfolio file
 8538: 
 8539: sub update_portfolio_table {
 8540:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8541:     if ($group ne '') {
 8542:         $file_name =~s /^\Q$group\E//;
 8543:     }
 8544:     my $homeserver = &homeserver($uname,$udom);
 8545:     my $queryid=
 8546:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8547:                ':'.&escape($file_name).':'.$action,$homeserver);
 8548:     my $reply = &get_query_reply($queryid);
 8549:     return $reply;
 8550: }
 8551: 
 8552: # -------------------------- Update MySQL allusers table
 8553: 
 8554: sub update_allusers_table {
 8555:     my ($uname,$udom,$names) = @_;
 8556:     my $homeserver = &homeserver($uname,$udom);
 8557:     my $queryid=
 8558:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8559:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8560:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8561:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8562:                'generation='.&escape($names->{'generation'}).'%%'.
 8563:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8564:                'id='.&escape($names->{'id'}),$homeserver);
 8565:     return;
 8566: }
 8567: 
 8568: # ------- Request retrieval of institutional classlists for course(s)
 8569: 
 8570: sub fetch_enrollment_query {
 8571:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8572:     my ($homeserver,$sleep,$loopmax);
 8573:     my $maxtries = 1;
 8574:     if ($context eq 'automated') {
 8575:         $homeserver = $perlvar{'lonHostID'};
 8576:         $sleep = 2;
 8577:         $loopmax = 100;
 8578:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8579:     } else {
 8580:         $homeserver = &homeserver($cnum,$dom);
 8581:     }
 8582:     my $host=&hostname($homeserver);
 8583:     my $cmd = '';
 8584:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8585:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8586:     }
 8587:     $cmd =~ s/%%$//;
 8588:     $cmd = &escape($cmd);
 8589:     my $query = 'fetchenrollment';
 8590:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8591:     unless ($queryid=~/^\Q$host\E\_/) { 
 8592:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8593:         return 'error: '.$queryid;
 8594:     }
 8595:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8596:     my $tries = 1;
 8597:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8598:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8599:         $tries ++;
 8600:     }
 8601:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8602:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8603:     } else {
 8604:         my @responses = split(/:/,$reply);
 8605:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8606:             foreach my $line (@responses) {
 8607:                 my ($key,$value) = split(/=/,$line,2);
 8608:                 $$replyref{$key} = $value;
 8609:             }
 8610:         } else {
 8611:             my $pathname = LONCAPA::tempdir();
 8612:             foreach my $line (@responses) {
 8613:                 my ($key,$value) = split(/=/,$line);
 8614:                 $$replyref{$key} = $value;
 8615:                 if ($value > 0) {
 8616:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8617:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8618:                         my $destname = $pathname.'/'.$filename;
 8619:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8620:                         if ($xml_classlist =~ /^error/) {
 8621:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8622:                         } else {
 8623:                             if ( open(FILE,">",$destname) ) {
 8624:                                 print FILE &unescape($xml_classlist);
 8625:                                 close(FILE);
 8626:                             } else {
 8627:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8628:                             }
 8629:                         }
 8630:                     }
 8631:                 }
 8632:             }
 8633:         }
 8634:         return 'ok';
 8635:     }
 8636:     return 'error';
 8637: }
 8638: 
 8639: sub get_query_reply {
 8640:     my ($queryid,$sleep,$loopmax) = @_;;
 8641:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8642:         $sleep = 0.2;
 8643:     }
 8644:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8645:         $loopmax = 100;
 8646:     }
 8647:     my $replyfile=LONCAPA::tempdir().$queryid;
 8648:     my $reply='';
 8649:     for (1..$loopmax) {
 8650: 	sleep($sleep);
 8651:         if (-e $replyfile.'.end') {
 8652: 	    if (open(my $fh,"<",$replyfile)) {
 8653: 		$reply = join('',<$fh>);
 8654: 		close($fh);
 8655: 	   } else { return 'error: reply_file_error'; }
 8656:            return &unescape($reply);
 8657: 	}
 8658:     }
 8659:     return 'timeout:'.$queryid;
 8660: }
 8661: 
 8662: sub courselog_query {
 8663: #
 8664: # possible filters:
 8665: # url: url or symb
 8666: # username
 8667: # domain
 8668: # action: view, submit, grade
 8669: # start: timestamp
 8670: # end: timestamp
 8671: #
 8672:     my (%filters)=@_;
 8673:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8674:     if ($filters{'url'}) {
 8675: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8676:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8677:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8678:     }
 8679:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8680:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8681:     return &log_query($cname,$cdom,'courselog',%filters);
 8682: }
 8683: 
 8684: sub userlog_query {
 8685: #
 8686: # possible filters:
 8687: # action: log check role
 8688: # start: timestamp
 8689: # end: timestamp
 8690: #
 8691:     my ($uname,$udom,%filters)=@_;
 8692:     return &log_query($uname,$udom,'userlog',%filters);
 8693: }
 8694: 
 8695: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8696: 
 8697: sub auto_run {
 8698:     my ($cnum,$cdom) = @_;
 8699:     my $response = 0;
 8700:     my $settings;
 8701:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8702:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8703:         $settings = $domconfig{'autoenroll'};
 8704:         if ($settings->{'run'} eq '1') {
 8705:             $response = 1;
 8706:         }
 8707:     } else {
 8708:         my $homeserver;
 8709:         if (&is_course($cdom,$cnum)) {
 8710:             $homeserver = &homeserver($cnum,$cdom);
 8711:         } else {
 8712:             $homeserver = &domain($cdom,'primary');
 8713:         }
 8714:         if ($homeserver ne 'no_host') {
 8715:             $response = &reply('autorun:'.$cdom,$homeserver);
 8716:         }
 8717:     }
 8718:     return $response;
 8719: }
 8720: 
 8721: sub auto_get_sections {
 8722:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8723:     my $homeserver;
 8724:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8725:         $homeserver = &homeserver($cnum,$cdom);
 8726:     }
 8727:     if (!defined($homeserver)) { 
 8728:         if ($cdom =~ /^$match_domain$/) {
 8729:             $homeserver = &domain($cdom,'primary');
 8730:         }
 8731:     }
 8732:     my @secs;
 8733:     if (defined($homeserver)) {
 8734:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8735:         unless ($response eq 'refused') {
 8736:             @secs = split(/:/,$response);
 8737:         }
 8738:     }
 8739:     return @secs;
 8740: }
 8741: 
 8742: sub auto_new_course {
 8743:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8744:     my $homeserver = &homeserver($cnum,$cdom);
 8745:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8746:     return $response;
 8747: }
 8748: 
 8749: sub auto_validate_courseID {
 8750:     my ($cnum,$cdom,$inst_course_id) = @_;
 8751:     my $homeserver = &homeserver($cnum,$cdom);
 8752:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8753:     return $response;
 8754: }
 8755: 
 8756: sub auto_validate_instcode {
 8757:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8758:     my ($homeserver,$response);
 8759:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8760:         $homeserver = &homeserver($cnum,$cdom);
 8761:     }
 8762:     if (!defined($homeserver)) {
 8763:         if ($cdom =~ /^$match_domain$/) {
 8764:             $homeserver = &domain($cdom,'primary');
 8765:         }
 8766:     }
 8767:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8768:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8769:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8770:     return ($outcome,$description,$defaultcredits);
 8771: }
 8772: 
 8773: sub auto_create_password {
 8774:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8775:     my ($homeserver,$response);
 8776:     my $create_passwd = 0;
 8777:     my $authchk = '';
 8778:     if ($udom =~ /^$match_domain$/) {
 8779:         $homeserver = &domain($udom,'primary');
 8780:     }
 8781:     if ($homeserver eq '') {
 8782:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8783:             $homeserver = &homeserver($cnum,$cdom);
 8784:         }
 8785:     }
 8786:     if ($homeserver eq '') {
 8787:         $authchk = 'nodomain';
 8788:     } else {
 8789:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8790:         if ($response eq 'refused') {
 8791:             $authchk = 'refused';
 8792:         } else {
 8793:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8794:         }
 8795:     }
 8796:     return ($authparam,$create_passwd,$authchk);
 8797: }
 8798: 
 8799: sub auto_photo_permission {
 8800:     my ($cnum,$cdom,$students) = @_;
 8801:     my $homeserver = &homeserver($cnum,$cdom);
 8802:     my ($outcome,$perm_reqd,$conditions) = 
 8803: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8804:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8805: 	return (undef,undef);
 8806:     }
 8807:     return ($outcome,$perm_reqd,$conditions);
 8808: }
 8809: 
 8810: sub auto_checkphotos {
 8811:     my ($uname,$udom,$pid) = @_;
 8812:     my $homeserver = &homeserver($uname,$udom);
 8813:     my ($result,$resulttype);
 8814:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8815: 				   &escape($uname).':'.&escape($pid),
 8816: 				   $homeserver));
 8817:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8818: 	return (undef,undef);
 8819:     }
 8820:     if ($outcome) {
 8821:         ($result,$resulttype) = split(/:/,$outcome);
 8822:     } 
 8823:     return ($result,$resulttype);
 8824: }
 8825: 
 8826: sub auto_photochoice {
 8827:     my ($cnum,$cdom) = @_;
 8828:     my $homeserver = &homeserver($cnum,$cdom);
 8829:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8830: 						       &escape($cdom),
 8831: 						       $homeserver)));
 8832:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8833: 	return (undef,undef);
 8834:     }
 8835:     return ($update,$comment);
 8836: }
 8837: 
 8838: sub auto_photoupdate {
 8839:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8840:     my $homeserver = &homeserver($cnum,$dom);
 8841:     my $host=&hostname($homeserver);
 8842:     my $cmd = '';
 8843:     my $maxtries = 1;
 8844:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8845:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8846:     }
 8847:     $cmd =~ s/%%$//;
 8848:     $cmd = &escape($cmd);
 8849:     my $query = 'institutionalphotos';
 8850:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8851:     unless ($queryid=~/^\Q$host\E\_/) {
 8852:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8853:         return 'error: '.$queryid;
 8854:     }
 8855:     my $reply = &get_query_reply($queryid);
 8856:     my $tries = 1;
 8857:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8858:         $reply = &get_query_reply($queryid);
 8859:         $tries ++;
 8860:     }
 8861:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8862:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8863:     } else {
 8864:         my @responses = split(/:/,$reply);
 8865:         my $outcome = shift(@responses); 
 8866:         foreach my $item (@responses) {
 8867:             my ($key,$value) = split(/=/,$item);
 8868:             $$photo{$key} = $value;
 8869:         }
 8870:         return $outcome;
 8871:     }
 8872:     return 'error';
 8873: }
 8874: 
 8875: sub auto_instcode_format {
 8876:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8877: 	$cat_order) = @_;
 8878:     my $courses = '';
 8879:     my @homeservers;
 8880:     if ($caller eq 'global') {
 8881: 	my %servers = &get_servers($codedom,'library');
 8882: 	foreach my $tryserver (keys(%servers)) {
 8883: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8884: 		push(@homeservers,$tryserver);
 8885: 	    }
 8886:         }
 8887:     } elsif ($caller eq 'requests') {
 8888:         if ($codedom =~ /^$match_domain$/) {
 8889:             my $chome = &domain($codedom,'primary');
 8890:             unless ($chome eq 'no_host') {
 8891:                 push(@homeservers,$chome);
 8892:             }
 8893:         }
 8894:     } else {
 8895:         push(@homeservers,&homeserver($caller,$codedom));
 8896:     }
 8897:     foreach my $code (keys(%{$instcodes})) {
 8898:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8899:     }
 8900:     chop($courses);
 8901:     my $ok_response = 0;
 8902:     my $response;
 8903:     while (@homeservers > 0 && $ok_response == 0) {
 8904:         my $server = shift(@homeservers); 
 8905:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8906:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8907:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8908: 		split(/:/,$response);
 8909:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8910:             push(@{$codetitles},&str2array($codetitles_str));
 8911:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8912:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8913:             $ok_response = 1;
 8914:         }
 8915:     }
 8916:     if ($ok_response) {
 8917:         return 'ok';
 8918:     } else {
 8919:         return $response;
 8920:     }
 8921: }
 8922: 
 8923: sub auto_instcode_defaults {
 8924:     my ($domain,$returnhash,$code_order) = @_;
 8925:     my @homeservers;
 8926: 
 8927:     my %servers = &get_servers($domain,'library');
 8928:     foreach my $tryserver (keys(%servers)) {
 8929: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8930: 	    push(@homeservers,$tryserver);
 8931: 	}
 8932:     }
 8933: 
 8934:     my $response;
 8935:     foreach my $server (@homeservers) {
 8936:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8937:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8938: 	
 8939: 	foreach my $pair (split(/\&/,$response)) {
 8940: 	    my ($name,$value)=split(/\=/,$pair);
 8941: 	    if ($name eq 'code_order') {
 8942: 		@{$code_order} = split(/\&/,&unescape($value));
 8943: 	    } else {
 8944: 		$returnhash->{&unescape($name)}=&unescape($value);
 8945: 	    }
 8946: 	}
 8947: 	return 'ok';
 8948:     }
 8949: 
 8950:     return $response;
 8951: }
 8952: 
 8953: sub auto_possible_instcodes {
 8954:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8955:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8956:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8957:         return;
 8958:     }
 8959:     my (@homeservers,$uhome);
 8960:     if (defined(&domain($domain,'primary'))) {
 8961:         $uhome=&domain($domain,'primary');
 8962:         push(@homeservers,&domain($domain,'primary'));
 8963:     } else {
 8964:         my %servers = &get_servers($domain,'library');
 8965:         foreach my $tryserver (keys(%servers)) {
 8966:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8967:                 push(@homeservers,$tryserver);
 8968:             }
 8969:         }
 8970:     }
 8971:     my $response;
 8972:     foreach my $server (@homeservers) {
 8973:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8974:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8975:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8976:             split(':',$response);
 8977:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8978:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8979:         foreach my $item (split('&',$cat_title)) {   
 8980:             my ($name,$value)=split('=',$item);
 8981:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8982:         }
 8983:         foreach my $item (split('&',$cat_order)) {
 8984:             my ($name,$value)=split('=',$item);
 8985:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8986:         }
 8987:         return 'ok';
 8988:     }
 8989:     return $response;
 8990: }
 8991: 
 8992: sub auto_courserequest_checks {
 8993:     my ($dom) = @_;
 8994:     my ($homeserver,%validations);
 8995:     if ($dom =~ /^$match_domain$/) {
 8996:         $homeserver = &domain($dom,'primary');
 8997:     }
 8998:     unless ($homeserver eq 'no_host') {
 8999:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9000:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9001:             my @items = split(/&/,$response);
 9002:             foreach my $item (@items) {
 9003:                 my ($key,$value) = split('=',$item);
 9004:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9005:             }
 9006:         }
 9007:     }
 9008:     return %validations; 
 9009: }
 9010: 
 9011: sub auto_courserequest_validation {
 9012:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9013:     my ($homeserver,$response);
 9014:     if ($dom =~ /^$match_domain$/) {
 9015:         $homeserver = &domain($dom,'primary');
 9016:     }
 9017:     unless ($homeserver eq 'no_host') {
 9018:         my $customdata;
 9019:         if (ref($custominfo) eq 'HASH') {
 9020:             $customdata = &freeze_escape($custominfo);
 9021:         }
 9022:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9023:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9024:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9025:                                     $customdata,$homeserver));
 9026:     }
 9027:     return $response;
 9028: }
 9029: 
 9030: sub auto_validate_class_sec {
 9031:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9032:     my $homeserver = &homeserver($cnum,$cdom);
 9033:     my $ownerlist;
 9034:     if (ref($owners) eq 'ARRAY') {
 9035:         $ownerlist = join(',',@{$owners});
 9036:     } else {
 9037:         $ownerlist = $owners;
 9038:     }
 9039:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9040:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9041:     return $response;
 9042: }
 9043: 
 9044: sub auto_validate_instclasses {
 9045:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9046:     my ($homeserver,%validations);
 9047:     $homeserver = &homeserver($cnum,$cdom);
 9048:     unless ($homeserver eq 'no_host') {
 9049:         my $ownerlist;
 9050:         if (ref($owners) eq 'ARRAY') {
 9051:             $ownerlist = join(',',@{$owners});
 9052:         } else {
 9053:             $ownerlist = $owners;
 9054:         }
 9055:         if (ref($classesref) eq 'HASH') {
 9056:             my $classes = &freeze_escape($classesref);
 9057:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9058:                                 ':'.$cdom.':'.$classes,$homeserver);
 9059:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9060:                 my @items = split(/&/,$response);
 9061:                 foreach my $item (@items) {
 9062:                     my ($key,$value) = split('=',$item);
 9063:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9064:                 }
 9065:             }
 9066:         }
 9067:     }
 9068:     return %validations;
 9069: }
 9070: 
 9071: sub auto_crsreq_update {
 9072:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9073:         $code,$accessstart,$accessend,$inbound) = @_;
 9074:     my ($homeserver,%crsreqresponse);
 9075:     if ($cdom =~ /^$match_domain$/) {
 9076:         $homeserver = &domain($cdom,'primary');
 9077:     }
 9078:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9079:         my $info;
 9080:         if (ref($inbound) eq 'HASH') {
 9081:             $info = &freeze_escape($inbound);
 9082:         }
 9083:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9084:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9085:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9086:                             &escape($title).':'.&escape($code).':'.
 9087:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9088:                             $homeserver);
 9089:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9090:             my @items = split(/&/,$response);
 9091:             foreach my $item (@items) {
 9092:                 my ($key,$value) = split('=',$item);
 9093:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9094:             }
 9095:         }
 9096:     }
 9097:     return \%crsreqresponse;
 9098: }
 9099: 
 9100: sub auto_export_grades {
 9101:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9102:     my ($homeserver,%exportresponse);
 9103:     if ($cdom =~ /^$match_domain$/) {
 9104:         $homeserver = &domain($cdom,'primary');
 9105:     }
 9106:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9107:         my $info;
 9108:         if (ref($inforef) eq 'HASH') {
 9109:             $info = &freeze_escape($inforef);
 9110:         }
 9111:         if (ref($gradesref) eq 'HASH') {
 9112:             my $grades = &freeze_escape($gradesref);
 9113:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9114:                                 $info.':'.$grades,$homeserver);
 9115:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9116:                 my @items = split(/&/,$response);
 9117:                 foreach my $item (@items) {
 9118:                     my ($key,$value) = split('=',$item);
 9119:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9120:                 }
 9121:             }
 9122:         }
 9123:     }
 9124:     return \%exportresponse;
 9125: }
 9126: 
 9127: sub check_instcode_cloning {
 9128:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9129:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9130:         return;
 9131:     }
 9132:     my $canclone;
 9133:     if (@{$code_order} > 0) {
 9134:         my $instcoderegexp ='^';
 9135:         my @clonecodes = split(/\&/,$cloner);
 9136:         foreach my $item (@{$code_order}) {
 9137:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9138:                 foreach my $pair (@clonecodes) {
 9139:                     my ($key,$val) = split(/\=/,$pair,2);
 9140:                     $val = &unescape($val);
 9141:                     if ($key eq $item) {
 9142:                         $instcoderegexp .= '('.$val.')';
 9143:                         last;
 9144:                     }
 9145:                 }
 9146:             } else {
 9147:                 $instcoderegexp .= $codedefaults->{$item};
 9148:             }
 9149:         }
 9150:         $instcoderegexp .= '$';
 9151:         my (@from,@to);
 9152:         eval {
 9153:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9154:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9155:         };
 9156:         if ((@from > 0) && (@to > 0)) {
 9157:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9158:             if (!@diffs) {
 9159:                 $canclone = 1;
 9160:             }
 9161:         }
 9162:     }
 9163:     return $canclone;
 9164: }
 9165: 
 9166: sub default_instcode_cloning {
 9167:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9168:     my (%codedefaults,@code_order,$canclone);
 9169:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9170:         %codedefaults = %{$codedefaultsref};
 9171:         @code_order = @{$codeorderref};
 9172:     } elsif ($clonedom) {
 9173:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9174:     }
 9175:     if (($domdefclone) && (@code_order)) {
 9176:         my @clonecodes = split(/\+/,$domdefclone);
 9177:         my $instcoderegexp ='^';
 9178:         foreach my $item (@code_order) {
 9179:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9180:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9181:             } else {
 9182:                 $instcoderegexp .= $codedefaults{$item};
 9183:             }
 9184:         }
 9185:         $instcoderegexp .= '$';
 9186:         my (@from,@to);
 9187:         eval {
 9188:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9189:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9190:         };
 9191:         if ((@from > 0) && (@to > 0)) {
 9192:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9193:             if (!@diffs) {
 9194:                 $canclone = 1;
 9195:             }
 9196:         }
 9197:     }
 9198:     return $canclone;
 9199: }
 9200: 
 9201: # ------------------------------------------------------- Course Group routines
 9202: 
 9203: sub get_coursegroups {
 9204:     my ($cdom,$cnum,$group,$namespace) = @_;
 9205:     return(&dump($namespace,$cdom,$cnum,$group));
 9206: }
 9207: 
 9208: sub modify_coursegroup {
 9209:     my ($cdom,$cnum,$groupsettings) = @_;
 9210:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9211: }
 9212: 
 9213: sub toggle_coursegroup_status {
 9214:     my ($cdom,$cnum,$group,$action) = @_;
 9215:     my ($from_namespace,$to_namespace);
 9216:     if ($action eq 'delete') {
 9217:         $from_namespace = 'coursegroups';
 9218:         $to_namespace = 'deleted_groups';
 9219:     } else {
 9220:         $from_namespace = 'deleted_groups';
 9221:         $to_namespace = 'coursegroups';
 9222:     }
 9223:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9224:     if (my $tmp = &error(%curr_group)) {
 9225:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9226:         return ('read error',$tmp);
 9227:     } else {
 9228:         my %savedsettings = %curr_group; 
 9229:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9230:         my $deloutcome;
 9231:         if ($result eq 'ok') {
 9232:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9233:         } else {
 9234:             return ('write error',$result);
 9235:         }
 9236:         if ($deloutcome eq 'ok') {
 9237:             return 'ok';
 9238:         } else {
 9239:             return ('delete error',$deloutcome);
 9240:         }
 9241:     }
 9242: }
 9243: 
 9244: sub modify_group_roles {
 9245:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9246:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9247:     my $role = 'gr/'.&escape($userprivs);
 9248:     my ($uname,$udom) = split(/:/,$user);
 9249:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9250:     if ($result eq 'ok') {
 9251:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9252:     }
 9253:     return $result;
 9254: }
 9255: 
 9256: sub modify_coursegroup_membership {
 9257:     my ($cdom,$cnum,$membership) = @_;
 9258:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9259:     return $result;
 9260: }
 9261: 
 9262: sub get_active_groups {
 9263:     my ($udom,$uname,$cdom,$cnum) = @_;
 9264:     my $now = time;
 9265:     my %groups = ();
 9266:     foreach my $key (keys(%env)) {
 9267:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9268:             my ($start,$end) = split(/\./,$env{$key});
 9269:             if (($end!=0) && ($end<$now)) { next; }
 9270:             if (($start!=0) && ($start>$now)) { next; }
 9271:             if ($1 eq $cdom && $2 eq $cnum) {
 9272:                 $groups{$3} = $env{$key} ;
 9273:             }
 9274:         }
 9275:     }
 9276:     return %groups;
 9277: }
 9278: 
 9279: sub get_group_membership {
 9280:     my ($cdom,$cnum,$group) = @_;
 9281:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9282: }
 9283: 
 9284: sub get_users_groups {
 9285:     my ($udom,$uname,$courseid) = @_;
 9286:     my @usersgroups;
 9287:     my $cachetime=1800;
 9288: 
 9289:     my $hashid="$udom:$uname:$courseid";
 9290:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9291:     if (defined($cached)) {
 9292:         @usersgroups = split(/:/,$grouplist);
 9293:     } else {  
 9294:         $grouplist = '';
 9295:         my $courseurl = &courseid_to_courseurl($courseid);
 9296:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9297:         my $access_end = $env{'course.'.$courseid.
 9298:                               '.default_enrollment_end_date'};
 9299:         my $now = time;
 9300:         foreach my $key (keys(%roleshash)) {
 9301:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9302:                 my $group = $1;
 9303:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9304:                     my $start = $2;
 9305:                     my $end = $1;
 9306:                     if ($start == -1) { next; } # deleted from group
 9307:                     if (($start!=0) && ($start>$now)) { next; }
 9308:                     if (($end!=0) && ($end<$now)) {
 9309:                         if ($access_end && $access_end < $now) {
 9310:                             if ($access_end - $end < 86400) {
 9311:                                 push(@usersgroups,$group);
 9312:                             }
 9313:                         }
 9314:                         next;
 9315:                     }
 9316:                     push(@usersgroups,$group);
 9317:                 }
 9318:             }
 9319:         }
 9320:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9321:         $grouplist = join(':',@usersgroups);
 9322:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9323:     }
 9324:     return @usersgroups;
 9325: }
 9326: 
 9327: sub devalidate_getgroups_cache {
 9328:     my ($udom,$uname,$cdom,$cnum)=@_;
 9329:     my $courseid = $cdom.'_'.$cnum;
 9330: 
 9331:     my $hashid="$udom:$uname:$courseid";
 9332:     &devalidate_cache_new('getgroups',$hashid);
 9333: }
 9334: 
 9335: # ------------------------------------------------------------------ Plain Text
 9336: 
 9337: sub plaintext {
 9338:     my ($short,$type,$cid,$forcedefault) = @_;
 9339:     if ($short =~ m{^cr/}) {
 9340: 	return (split('/',$short))[-1];
 9341:     }
 9342:     if (!defined($cid)) {
 9343:         $cid = $env{'request.course.id'};
 9344:     }
 9345:     my %rolenames = (
 9346:                       Course    => 'std',
 9347:                       Community => 'alt1',
 9348:                       Placement => 'std',
 9349:                     );
 9350:     if ($cid ne '') {
 9351:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9352:             unless ($forcedefault) {
 9353:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9354:                 &Apache::lonlocal::mt_escape(\$roletext);
 9355:                 return &Apache::lonlocal::mt($roletext);
 9356:             }
 9357:         }
 9358:     }
 9359:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9360:         (defined($rolenames{$type})) && 
 9361:         (defined($prp{$short}{$rolenames{$type}}))) {
 9362:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9363:     } elsif ($cid ne '') {
 9364:         my $crstype = $env{'course.'.$cid.'.type'};
 9365:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9366:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9367:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9368:         }
 9369:     }
 9370:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9371: }
 9372: 
 9373: # ----------------------------------------------------------------- Assign Role
 9374: 
 9375: sub assignrole {
 9376:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9377:         $context)=@_;
 9378:     my $mrole;
 9379:     if ($role =~ /^cr\//) {
 9380:         my $cwosec=$url;
 9381:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9382: 	unless (&allowed('ccr',$cwosec)) {
 9383:            my $refused = 1;
 9384:            if ($context eq 'requestcourses') {
 9385:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9386:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9387:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9388:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9389:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9390:                            if ($crsenv{'internal.courseowner'} eq
 9391:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9392:                                $refused = '';
 9393:                            }
 9394:                        }
 9395:                    }
 9396:                }
 9397:            }
 9398:            if ($refused) {
 9399:                &logthis('Refused custom assignrole: '.
 9400:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9401:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9402:                return 'refused';
 9403:            }
 9404:         }
 9405:         $mrole='cr';
 9406:     } elsif ($role =~ /^gr\//) {
 9407:         my $cwogrp=$url;
 9408:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9409:         unless (&allowed('mdg',$cwogrp)) {
 9410:             &logthis('Refused group assignrole: '.
 9411:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9412:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9413:             return 'refused';
 9414:         }
 9415:         $mrole='gr';
 9416:     } else {
 9417:         my $cwosec=$url;
 9418:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9419:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9420:             my $refused;
 9421:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9422:                 if (!(&allowed('c'.$role,$url))) {
 9423:                     $refused = 1;
 9424:                 }
 9425:             } else {
 9426:                 $refused = 1;
 9427:             }
 9428:             if ($refused) {
 9429:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9430:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9431:                     my %crsenv;
 9432:                     if ($role eq 'cc' || $role eq 'co') {
 9433:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9434:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9435:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9436:                                 if ($crsenv{'internal.courseowner'} eq 
 9437:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9438:                                     $refused = '';
 9439:                                 }
 9440:                             }
 9441:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9442:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9443:                                 if ($crsenv{'internal.courseowner'} eq 
 9444:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9445:                                     $refused = '';
 9446:                                 }
 9447:                             }
 9448:                         }
 9449:                     }
 9450:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9451:                     if ($role eq 'st') {
 9452:                         $refused = '';
 9453:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9454:                         $refused = '';
 9455:                     }
 9456:                 } elsif ($context eq 'requestcourses') {
 9457:                     my @possroles = ('st','ta','ep','in','cc','co');
 9458:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9459:                         my $wrongcc;
 9460:                         if ($cnum =~ /^$match_community$/) {
 9461:                             $wrongcc = 1 if ($role eq 'cc');
 9462:                         } else {
 9463:                             $wrongcc = 1 if ($role eq 'co');
 9464:                         }
 9465:                         unless ($wrongcc) {
 9466:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9467:                             if ($crsenv{'internal.courseowner'} eq 
 9468:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9469:                                 $refused = '';
 9470:                             }
 9471:                         }
 9472:                     }
 9473:                 } elsif ($context eq 'requestauthor') {
 9474:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9475:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9476:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9477:                             $refused = '';
 9478:                         } else {
 9479:                             my %domdefaults = &get_domain_defaults($udom);
 9480:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9481:                                 my $checkbystatus;
 9482:                                 if ($env{'user.adv'}) { 
 9483:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9484:                                     if ($disposition eq 'automatic') {
 9485:                                         $refused = '';
 9486:                                     } elsif ($disposition eq '') {
 9487:                                         $checkbystatus = 1;
 9488:                                     } 
 9489:                                 } else {
 9490:                                     $checkbystatus = 1;
 9491:                                 }
 9492:                                 if ($checkbystatus) {
 9493:                                     if ($env{'environment.inststatus'}) {
 9494:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9495:                                         foreach my $type (@inststatuses) {
 9496:                                             if (($type ne '') &&
 9497:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9498:                                                 $refused = '';
 9499:                                             }
 9500:                                         }
 9501:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9502:                                         $refused = '';
 9503:                                     }
 9504:                                 }
 9505:                             }
 9506:                         }
 9507:                     }
 9508:                 }
 9509:                 if ($refused) {
 9510:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9511:                              ' '.$role.' '.$end.' '.$start.' by '.
 9512: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9513:                     return 'refused';
 9514:                 }
 9515:             }
 9516:         } elsif ($role eq 'au') {
 9517:             if ($url ne '/'.$udom.'/') {
 9518:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9519:                          ' to assign author role for '.$uname.':'.$udom.
 9520:                          ' in domain: '.$url.' refused (wrong domain).');
 9521:                 return 'refused';
 9522:             }
 9523:         }
 9524:         $mrole=$role;
 9525:     }
 9526:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9527:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9528:     if ($end) { $command.='_'.$end; }
 9529:     if ($start) {
 9530: 	if ($end) { 
 9531:            $command.='_'.$start; 
 9532:         } else {
 9533:            $command.='_0_'.$start;
 9534:         }
 9535:     }
 9536:     my $origstart = $start;
 9537:     my $origend = $end;
 9538:     my $delflag;
 9539: # actually delete
 9540:     if ($deleteflag) {
 9541: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9542: # modify command to delete the role
 9543:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9544:                 "$udom:$uname:$url".'_'."$mrole";
 9545: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9546: # set start and finish to negative values for userrolelog
 9547:            $start=-1;
 9548:            $end=-1;
 9549:            $delflag = 1;
 9550:         }
 9551:     }
 9552: # send command
 9553:     my $answer=&reply($command,&homeserver($uname,$udom));
 9554: # log new user role if status is ok
 9555:     if ($answer eq 'ok') {
 9556: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9557:         if (($role eq 'cc') || ($role eq 'in') ||
 9558:             ($role eq 'ep') || ($role eq 'ad') ||
 9559:             ($role eq 'ta') || ($role eq 'st') ||
 9560:             ($role=~/^cr/) || ($role eq 'gr') ||
 9561:             ($role eq 'co')) {
 9562: # for course roles, perform group memberships changes triggered by role change.
 9563:             unless ($role =~ /^gr/) {
 9564:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9565:                                                  $origstart,$selfenroll,$context);
 9566:             }
 9567:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9568:                            $selfenroll,$context);
 9569:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9570:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9571:                  ($role eq 'da')) {
 9572:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9573:                            $context);
 9574:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9575:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9576:                              $context); 
 9577:         }
 9578:         if ($role eq 'cc') {
 9579:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9580:         }
 9581:     }
 9582:     return $answer;
 9583: }
 9584: 
 9585: sub autoupdate_coowners {
 9586:     my ($url,$end,$start,$uname,$udom) = @_;
 9587:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9588:     if (($cdom ne '') && ($cnum ne '')) {
 9589:         my $now = time;
 9590:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9591:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9592:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9593:             my $instcode = $coursehash{'internal.coursecode'};
 9594:             if ($instcode ne '') {
 9595:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9596:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9597:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9598:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9599:                         if ($result eq 'valid') {
 9600:                             if ($coursehash{'internal.co-owners'}) {
 9601:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9602:                                     push(@newcoowners,$coowner);
 9603:                                 }
 9604:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9605:                                     push(@newcoowners,$uname.':'.$udom);
 9606:                                 }
 9607:                                 @newcoowners = sort(@newcoowners);
 9608:                             } else {
 9609:                                 push(@newcoowners,$uname.':'.$udom);
 9610:                             }
 9611:                         } else {
 9612:                             if ($coursehash{'internal.co-owners'}) {
 9613:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9614:                                     unless ($coowner eq $uname.':'.$udom) {
 9615:                                         push(@newcoowners,$coowner);
 9616:                                     }
 9617:                                 }
 9618:                                 unless (@newcoowners > 0) {
 9619:                                     $delcoowners = 1;
 9620:                                     $coowners = '';
 9621:                                 }
 9622:                             }
 9623:                         }
 9624:                         if (@newcoowners || $delcoowners) {
 9625:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9626:                                             $delcoowners,@newcoowners);
 9627:                         }
 9628:                     }
 9629:                 }
 9630:             }
 9631:         }
 9632:     }
 9633: }
 9634: 
 9635: sub store_coowners {
 9636:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9637:     my $cid = $cdom.'_'.$cnum;
 9638:     my ($coowners,$delresult,$putresult);
 9639:     if (@newcoowners) {
 9640:         $coowners = join(',',@newcoowners);
 9641:         my %coownershash = (
 9642:                             'internal.co-owners' => $coowners,
 9643:                            );
 9644:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9645:         if ($putresult eq 'ok') {
 9646:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9647:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9648:             }
 9649:         }
 9650:     }
 9651:     if ($delcoowners) {
 9652:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9653:         if ($delresult eq 'ok') {
 9654:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9655:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9656:             }
 9657:         }
 9658:     }
 9659:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9660:         my %crsinfo =
 9661:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9662:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9663:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9664:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9665:         }
 9666:     }
 9667: }
 9668: 
 9669: # -------------------------------------------------- Modify user authentication
 9670: # Overrides without validation
 9671: 
 9672: sub modifyuserauth {
 9673:     my ($udom,$uname,$umode,$upass)=@_;
 9674:     my $uhome=&homeserver($uname,$udom);
 9675:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9676:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9677:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9678:              ' in domain '.$env{'request.role.domain'});  
 9679:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9680: 		     &escape($upass),$uhome);
 9681:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9682:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9683:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9684:     &log($udom,,$uname,$uhome,
 9685:         'Authentication changed by '.$env{'user.domain'}.', '.
 9686:                                      $env{'user.name'}.', '.$umode.
 9687:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9688:     unless ($reply eq 'ok') {
 9689:         &logthis('Authentication mode error: '.$reply);
 9690: 	return 'error: '.$reply;
 9691:     }   
 9692:     return 'ok';
 9693: }
 9694: 
 9695: # --------------------------------------------------------------- Modify a user
 9696: 
 9697: sub modifyuser {
 9698:     my ($udom,    $uname, $uid,
 9699:         $umode,   $upass, $first,
 9700:         $middle,  $last,  $gene,
 9701:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9702:     $udom= &LONCAPA::clean_domain($udom);
 9703:     $uname=&LONCAPA::clean_username($uname);
 9704:     my $showcandelete = 'none';
 9705:     if (ref($candelete) eq 'ARRAY') {
 9706:         if (@{$candelete} > 0) {
 9707:             $showcandelete = join(', ',@{$candelete});
 9708:         }
 9709:     }
 9710:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9711:              $umode.', '.$first.', '.$middle.', '.
 9712: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9713:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9714:                                      ' desiredhome not specified'). 
 9715:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9716:              ' in domain '.$env{'request.role.domain'});
 9717:     my $uhome=&homeserver($uname,$udom,'true');
 9718:     my $newuser;
 9719:     if ($uhome eq 'no_host') {
 9720:         $newuser = 1;
 9721:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9722:                 ($umode eq 'lti')) {
 9723:             return 'error: more information needed to create new user';
 9724:         }
 9725:     }
 9726: # ----------------------------------------------------------------- Create User
 9727:     if (($uhome eq 'no_host') && 
 9728: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9729:         my $unhome='';
 9730:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9731:             $unhome = $desiredhome;
 9732: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9733: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9734:         } else { # load balancing routine for determining $unhome
 9735:             my $loadm=10000000;
 9736: 	    my %servers = &get_servers($udom,'library');
 9737: 	    foreach my $tryserver (keys(%servers)) {
 9738: 		my $answer=reply('load',$tryserver);
 9739: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9740: 		    $loadm=$answer;
 9741: 		    $unhome=$tryserver;
 9742: 		}
 9743: 	    }
 9744:         }
 9745:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9746: 	    return 'error: unable to find a home server for '.$uname.
 9747:                    ' in domain '.$udom;
 9748:         }
 9749:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9750:                          &escape($upass),$unhome);
 9751: 	unless ($reply eq 'ok') {
 9752:             return 'error: '.$reply;
 9753:         }   
 9754:         $uhome=&homeserver($uname,$udom,'true');
 9755:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9756: 	    return 'error: unable verify users home machine.';
 9757:         }
 9758:     }   # End of creation of new user
 9759: # ---------------------------------------------------------------------- Add ID
 9760:     if ($uid) {
 9761:        $uid=~tr/A-Z/a-z/;
 9762:        my %uidhash=&idrget($udom,$uname);
 9763:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9764:          && (!$forceid)) {
 9765: 	  unless ($uid eq $uidhash{$uname}) {
 9766: 	      return 'error: user id "'.$uid.'" does not match '.
 9767:                   'current user id "'.$uidhash{$uname}.'".';
 9768:           }
 9769:        } else {
 9770: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9771:        }
 9772:     }
 9773: # -------------------------------------------------------------- Add names, etc
 9774:     my @tmp=&get('environment',
 9775: 		   ['firstname','middlename','lastname','generation','id',
 9776:                     'permanentemail','inststatus'],
 9777: 		   $udom,$uname);
 9778:     my (%names,%oldnames);
 9779:     if ($tmp[0] =~ m/^error:.*/) { 
 9780:         %names=(); 
 9781:     } else {
 9782:         %names = @tmp;
 9783:         %oldnames = %names;
 9784:     }
 9785: #
 9786: # If name, email and/or uid are blank (e.g., because an uploaded file
 9787: # of users did not contain them), do not overwrite existing values
 9788: # unless field is in $candelete array ref.  
 9789: #
 9790: 
 9791:     my @fields = ('firstname','middlename','lastname','generation',
 9792:                   'permanentemail','id');
 9793:     my %newvalues;
 9794:     if (ref($candelete) eq 'ARRAY') {
 9795:         foreach my $field (@fields) {
 9796:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9797:                 if ($field eq 'firstname') {
 9798:                     $names{$field} = $first;
 9799:                 } elsif ($field eq 'middlename') {
 9800:                     $names{$field} = $middle;
 9801:                 } elsif ($field eq 'lastname') {
 9802:                     $names{$field} = $last;
 9803:                 } elsif ($field eq 'generation') { 
 9804:                     $names{$field} = $gene;
 9805:                 } elsif ($field eq 'permanentemail') {
 9806:                     $names{$field} = $email;
 9807:                 } elsif ($field eq 'id') {
 9808:                     $names{$field}  = $uid;
 9809:                 }
 9810:             }
 9811:         }
 9812:     }
 9813:     if ($first)  { $names{'firstname'}  = $first; }
 9814:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9815:     if ($last)   { $names{'lastname'}   = $last; }
 9816:     if (defined($gene))   { $names{'generation'} = $gene; }
 9817:     if ($email) {
 9818:        $email=~s/[^\w\@\.\-\,]//gs;
 9819:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9820:     }
 9821:     if ($uid) { $names{'id'}  = $uid; }
 9822:     if (defined($inststatus)) {
 9823:         $names{'inststatus'} = '';
 9824:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9825:         if (ref($usertypes) eq 'HASH') {
 9826:             my @okstatuses; 
 9827:             foreach my $item (split(/:/,$inststatus)) {
 9828:                 if (defined($usertypes->{$item})) {
 9829:                     push(@okstatuses,$item);  
 9830:                 }
 9831:             }
 9832:             if (@okstatuses) {
 9833:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9834:             }
 9835:         }
 9836:     }
 9837:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9838:                  $umode.', '.$first.', '.$middle.', '.
 9839:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9840:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9841:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9842:     } else {
 9843:         $logmsg .= ' during self creation';
 9844:     }
 9845:     my $changed;
 9846:     if ($newuser) {
 9847:         $changed = 1;
 9848:     } else {
 9849:         foreach my $field (@fields) {
 9850:             if ($names{$field} ne $oldnames{$field}) {
 9851:                 $changed = 1;
 9852:                 last;
 9853:             }
 9854:         }
 9855:     }
 9856:     unless ($changed) {
 9857:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9858:         &logthis($logmsg);
 9859:         return 'ok';
 9860:     }
 9861:     my $reply = &put('environment', \%names, $udom,$uname);
 9862:     if ($reply ne 'ok') { 
 9863:         return 'error: '.$reply;
 9864:     }
 9865:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9866:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9867:     }
 9868:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9869:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9870:     $logmsg = 'Success modifying user '.$logmsg;
 9871:     &logthis($logmsg);
 9872:     return 'ok';
 9873: }
 9874: 
 9875: # -------------------------------------------------------------- Modify student
 9876: 
 9877: sub modifystudent {
 9878:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9879:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9880:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9881:     if (!$cid) {
 9882: 	unless ($cid=$env{'request.course.id'}) {
 9883: 	    return 'not_in_class';
 9884: 	}
 9885:     }
 9886: # --------------------------------------------------------------- Make the user
 9887:     my $reply=&modifyuser
 9888: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9889:          $desiredhome,$email,$inststatus);
 9890:     unless ($reply eq 'ok') { return $reply; }
 9891:     # This will cause &modify_student_enrollment to get the uid from the
 9892:     # student's environment
 9893:     $uid = undef if (!$forceid);
 9894:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9895:                                         $gene,$usec,$end,$start,$type,$locktype,
 9896:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9897:     return $reply;
 9898: }
 9899: 
 9900: sub modify_student_enrollment {
 9901:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9902:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9903:     my ($cdom,$cnum,$chome);
 9904:     if (!$cid) {
 9905: 	unless ($cid=$env{'request.course.id'}) {
 9906: 	    return 'not_in_class';
 9907: 	}
 9908: 	$cdom=$env{'course.'.$cid.'.domain'};
 9909: 	$cnum=$env{'course.'.$cid.'.num'};
 9910:     } else {
 9911: 	($cdom,$cnum)=split(/_/,$cid);
 9912:     }
 9913:     $chome=$env{'course.'.$cid.'.home'};
 9914:     if (!$chome) {
 9915: 	$chome=&homeserver($cnum,$cdom);
 9916:     }
 9917:     if (!$chome) { return 'unknown_course'; }
 9918:     # Make sure the user exists
 9919:     my $uhome=&homeserver($uname,$udom);
 9920:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9921: 	return 'error: no such user';
 9922:     }
 9923:     # Get student data if we were not given enough information
 9924:     if (!defined($first)  || $first  eq '' || 
 9925:         !defined($last)   || $last   eq '' || 
 9926:         !defined($uid)    || $uid    eq '' || 
 9927:         !defined($middle) || $middle eq '' || 
 9928:         !defined($gene)   || $gene   eq '') {
 9929:         # They did not supply us with enough data to enroll the student, so
 9930:         # we need to pick up more information.
 9931:         my %tmp = &get('environment',
 9932:                        ['firstname','middlename','lastname', 'generation','id']
 9933:                        ,$udom,$uname);
 9934: 
 9935:         #foreach my $key (keys(%tmp)) {
 9936:         #    &logthis("key $key = ".$tmp{$key});
 9937:         #}
 9938:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9939:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9940:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9941:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9942:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9943:     }
 9944:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9945:     my $user = "$uname:$udom";
 9946:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9947:     my $reply=cput('classlist',
 9948: 		   {$user => 
 9949: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9950: 		   $cdom,$cnum);
 9951:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9952:         &devalidate_getsection_cache($udom,$uname,$cid);
 9953:     } else { 
 9954: 	return 'error: '.$reply;
 9955:     }
 9956:     # Add student role to user
 9957:     my $uurl='/'.$cid;
 9958:     $uurl=~s/\_/\//g;
 9959:     if ($usec) {
 9960: 	$uurl.='/'.$usec;
 9961:     }
 9962:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9963:                              $selfenroll,$context);
 9964:     if ($result ne 'ok') {
 9965:         if ($old_entry{$user} ne '') {
 9966:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9967:         } else {
 9968:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9969:         }
 9970:     }
 9971:     return $result; 
 9972: }
 9973: 
 9974: sub format_name {
 9975:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9976:     my $name;
 9977:     if ($first ne 'lastname') {
 9978: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9979:     } else {
 9980: 	if ($lastname=~/\S/) {
 9981: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9982: 	    $name=~s/\s+,/,/;
 9983: 	} else {
 9984: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9985: 	}
 9986:     }
 9987:     $name=~s/^\s+//;
 9988:     $name=~s/\s+$//;
 9989:     $name=~s/\s+/ /g;
 9990:     return $name;
 9991: }
 9992: 
 9993: # ------------------------------------------------- Write to course preferences
 9994: 
 9995: sub writecoursepref {
 9996:     my ($courseid,%prefs)=@_;
 9997:     $courseid=~s/^\///;
 9998:     $courseid=~s/\_/\//g;
 9999:     my ($cdomain,$cnum)=split(/\//,$courseid);
10000:     my $chome=homeserver($cnum,$cdomain);
10001:     if (($chome eq '') || ($chome eq 'no_host')) { 
10002: 	return 'error: no such course';
10003:     }
10004:     my $cstring='';
10005:     foreach my $pref (keys(%prefs)) {
10006: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10007:     }
10008:     $cstring=~s/\&$//;
10009:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10010: }
10011: 
10012: # ---------------------------------------------------------- Make/modify course
10013: 
10014: sub createcourse {
10015:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10016:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10017:     $url=&declutter($url);
10018:     my $cid='';
10019:     if ($context eq 'requestcourses') {
10020:         my $can_create = 0;
10021:         my ($ownername,$ownerdom) = split(':',$course_owner);
10022:         if ($udom eq $ownerdom) {
10023:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10024:                                   $context)) {
10025:                 $can_create = 1;
10026:             }
10027:         } else {
10028:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10029:                                            $category);
10030:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10031:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10032:                 if (@curr > 0) {
10033:                     my @options = qw(approval validate autolimit);
10034:                     my $optregex = join('|',@options);
10035:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10036:                         $can_create = 1;
10037:                     }
10038:                 }
10039:             }
10040:         }
10041:         if ($can_create) {
10042:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10043:                 unless (&allowed('ccc',$udom)) {
10044:                     return 'refused'; 
10045:                 }
10046:             }
10047:         } else {
10048:             return 'refused';
10049:         }
10050:     } elsif (!&allowed('ccc',$udom)) {
10051:         return 'refused';
10052:     }
10053: # --------------------------------------------------------------- Get Unique ID
10054:     my $uname;
10055:     if ($cnum =~ /^$match_courseid$/) {
10056:         my $chome=&homeserver($cnum,$udom,'true');
10057:         if (($chome eq '') || ($chome eq 'no_host')) {
10058:             $uname = $cnum;
10059:         } else {
10060:             $uname = &generate_coursenum($udom,$crstype);
10061:         }
10062:     } else {
10063:         $uname = &generate_coursenum($udom,$crstype);
10064:     }
10065:     return $uname if ($uname =~ /^error/);
10066: # -------------------------------------------------- Check supplied server name
10067:     if (!defined($course_server)) {
10068:         if (defined(&domain($udom,'primary'))) {
10069:             $course_server = &domain($udom,'primary');
10070:         } else {
10071:             $course_server = $env{'user.home'}; 
10072:         }
10073:     }
10074:     my %host_servers =
10075:         &Apache::lonnet::get_servers($udom,'library');
10076:     unless ($host_servers{$course_server}) {
10077:         return 'error: invalid home server for course: '.$course_server;
10078:     }
10079: # ------------------------------------------------------------- Make the course
10080:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10081:                       $course_server);
10082:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10083:     my $uhome=&homeserver($uname,$udom,'true');
10084:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10085: 	return 'error: no such course';
10086:     }
10087: # ----------------------------------------------------------------- Course made
10088: # log existence
10089:     my $now = time;
10090:     my $newcourse = {
10091:                     $udom.'_'.$uname => {
10092:                                      description => $description,
10093:                                      inst_code   => $inst_code,
10094:                                      owner       => $course_owner,
10095:                                      type        => $crstype,
10096:                                      creator     => $env{'user.name'}.':'.
10097:                                                     $env{'user.domain'},
10098:                                      created     => $now,
10099:                                      context     => $context,
10100:                                                 },
10101:                     };
10102:     &courseidput($udom,$newcourse,$uhome,'notime');
10103: # set toplevel url
10104:     my $topurl=$url;
10105:     unless ($nonstandard) {
10106: # ------------------------------------------ For standard courses, make top url
10107:         my $mapurl=&clutter($url);
10108:         if ($mapurl eq '/res/') { $mapurl=''; }
10109:         $env{'form.initmap'}=(<<ENDINITMAP);
10110: <map>
10111: <resource id="1" type="start"></resource>
10112: <resource id="2" src="$mapurl"></resource>
10113: <resource id="3" type="finish"></resource>
10114: <link index="1" from="1" to="2"></link>
10115: <link index="2" from="2" to="3"></link>
10116: </map>
10117: ENDINITMAP
10118:         $topurl=&declutter(
10119:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10120:                           );
10121:     }
10122: # ----------------------------------------------------------- Write preferences
10123:     &writecoursepref($udom.'_'.$uname,
10124:                      ('description'              => $description,
10125:                       'url'                      => $topurl,
10126:                       'internal.creator'         => $env{'user.name'}.':'.
10127:                                                     $env{'user.domain'},
10128:                       'internal.created'         => $now,
10129:                       'internal.creationcontext' => $context)
10130:                     );
10131:     return '/'.$udom.'/'.$uname;
10132: }
10133: 
10134: # ------------------------------------------------------------------- Create ID
10135: sub generate_coursenum {
10136:     my ($udom,$crstype) = @_;
10137:     my $domdesc = &domain($udom);
10138:     return 'error: invalid domain' if ($domdesc eq '');
10139:     my $first;
10140:     if ($crstype eq 'Community') {
10141:         $first = '0';
10142:     } else {
10143:         $first = int(1+rand(9)); 
10144:     } 
10145:     my $uname=$first.
10146:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10147:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10148:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10149: # ----------------------------------------------- Make sure that does not exist
10150:     my $uhome=&homeserver($uname,$udom,'true');
10151:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10152:         if ($crstype eq 'Community') {
10153:             $first = '0';
10154:         } else {
10155:             $first = int(1+rand(9));
10156:         }
10157:         $uname=$first.
10158:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10159:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10160:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10161:         $uhome=&homeserver($uname,$udom,'true');
10162:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10163:             return 'error: unable to generate unique course-ID';
10164:         }
10165:     }
10166:     return $uname;
10167: }
10168: 
10169: sub is_course {
10170:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10171:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10172: 
10173:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10174:     my $uhome=&homeserver($cnum,$cdom);
10175:     my $iscourse;
10176:     if (grep { $_ eq $uhome } current_machine_ids()) {
10177:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10178:     } else {
10179:         my $hashid = $cdom.':'.$cnum;
10180:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10181:         unless (defined($cached)) {
10182:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10183:                                         $cnum,undef,undef,'.');
10184:             $iscourse = 0;
10185:             if (exists($courses{$cdom.'_'.$cnum})) {
10186:                 $iscourse = 1;
10187:             }
10188:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10189:         }
10190:     }
10191:     return unless ($iscourse);
10192:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10193: }
10194: 
10195: sub store_userdata {
10196:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10197:     my $result;
10198:     if ($datakey ne '') {
10199:         if (ref($storehash) eq 'HASH') {
10200:             if ($udom eq '' || $uname eq '') {
10201:                 $udom = $env{'user.domain'};
10202:                 $uname = $env{'user.name'};
10203:             }
10204:             my $uhome=&homeserver($uname,$udom);
10205:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10206:                 $result = 'error: no_host';
10207:             } else {
10208:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10209:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10210: 
10211:                 my $namevalue='';
10212:                 foreach my $key (keys(%{$storehash})) {
10213:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10214:                 }
10215:                 $namevalue=~s/\&$//;
10216:                 unless ($namespace eq 'courserequests') {
10217:                     $datakey = &escape($datakey);
10218:                 }
10219:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10220:                                   $namevalue,$uhome);
10221:             }
10222:         } else {
10223:             $result = 'error: data to store was not a hash reference'; 
10224:         }
10225:     } else {
10226:         $result= 'error: invalid requestkey'; 
10227:     }
10228:     return $result;
10229: }
10230: 
10231: # ---------------------------------------------------------- Assign Custom Role
10232: 
10233: sub assigncustomrole {
10234:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10235:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10236:                        $end,$start,$deleteflag,$selfenroll,$context);
10237: }
10238: 
10239: # ----------------------------------------------------------------- Revoke Role
10240: 
10241: sub revokerole {
10242:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10243:     my $now=time;
10244:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10245: }
10246: 
10247: # ---------------------------------------------------------- Revoke Custom Role
10248: 
10249: sub revokecustomrole {
10250:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10251:     my $now=time;
10252:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10253:            $deleteflag,$selfenroll,$context);
10254: }
10255: 
10256: # ------------------------------------------------------------ Disk usage
10257: sub diskusage {
10258:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10259:     $directorypath =~ s/\/$//;
10260:     my $listing=&reply('du2:'.&escape($directorypath).':'
10261:                        .&escape($getpropath).':'.&escape($uname).':'
10262:                        .&escape($udom),homeserver($uname,$udom));
10263:     if ($listing eq 'unknown_cmd') {
10264:         if ($getpropath) {
10265:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10266:         }
10267:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10268:     }
10269:     return $listing;
10270: }
10271: 
10272: sub is_locked {
10273:     my ($file_name, $domain, $user, $which) = @_;
10274:     my @check;
10275:     my $is_locked;
10276:     push (@check,$file_name);
10277:     my %locked = &get('file_permissions',\@check,
10278: 		      $env{'user.domain'},$env{'user.name'});
10279:     my ($tmp)=keys(%locked);
10280:     if ($tmp=~/^error:/) { undef(%locked); }
10281:     
10282:     if (ref($locked{$file_name}) eq 'ARRAY') {
10283:         $is_locked = 'false';
10284:         foreach my $entry (@{$locked{$file_name}}) {
10285:            if (ref($entry) eq 'ARRAY') {
10286:                $is_locked = 'true';
10287:                if (ref($which) eq 'ARRAY') {
10288:                    push(@{$which},$entry);
10289:                } else {
10290:                    last;
10291:                }
10292:            }
10293:        }
10294:     } else {
10295:         $is_locked = 'false';
10296:     }
10297:     return $is_locked;
10298: }
10299: 
10300: sub declutter_portfile {
10301:     my ($file) = @_;
10302:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10303:     return $file;
10304: }
10305: 
10306: # ------------------------------------------------------------- Mark as Read Only
10307: 
10308: sub mark_as_readonly {
10309:     my ($domain,$user,$files,$what) = @_;
10310:     my %current_permissions = &dump('file_permissions',$domain,$user);
10311:     my ($tmp)=keys(%current_permissions);
10312:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10313:     foreach my $file (@{$files}) {
10314: 	$file = &declutter_portfile($file);
10315:         push(@{$current_permissions{$file}},$what);
10316:     }
10317:     &put('file_permissions',\%current_permissions,$domain,$user);
10318:     return;
10319: }
10320: 
10321: # ------------------------------------------------------------Save Selected Files
10322: 
10323: sub save_selected_files {
10324:     my ($user, $path, @files) = @_;
10325:     my $filename = $user."savedfiles";
10326:     my @other_files = &files_not_in_path($user, $path);
10327:     open (OUT,'>',LONCAPA::tempdir().$filename);
10328:     foreach my $file (@files) {
10329:         print (OUT $env{'form.currentpath'}.$file."\n");
10330:     }
10331:     foreach my $file (@other_files) {
10332:         print (OUT $file."\n");
10333:     }
10334:     close (OUT);
10335:     return 'ok';
10336: }
10337: 
10338: sub clear_selected_files {
10339:     my ($user) = @_;
10340:     my $filename = $user."savedfiles";
10341:     open (OUT,'>',LONCAPA::tempdir().$filename);
10342:     print (OUT undef);
10343:     close (OUT);
10344:     return ("ok");    
10345: }
10346: 
10347: sub files_in_path {
10348:     my ($user, $path) = @_;
10349:     my $filename = $user."savedfiles";
10350:     my %return_files;
10351:     open (IN,'<',LONCAPA::tempdir().$filename);
10352:     while (my $line_in = <IN>) {
10353:         chomp ($line_in);
10354:         my @paths_and_file = split (m!/!, $line_in);
10355:         my $file_part = pop (@paths_and_file);
10356:         my $path_part = join ('/', @paths_and_file);
10357:         $path_part.='/';
10358:         my $path_and_file = $path_part.$file_part;
10359:         if ($path_part eq $path) {
10360:             $return_files{$file_part}= 'selected';
10361:         }
10362:     }
10363:     close (IN);
10364:     return (\%return_files);
10365: }
10366: 
10367: # called in portfolio select mode, to show files selected NOT in current directory
10368: sub files_not_in_path {
10369:     my ($user, $path) = @_;
10370:     my $filename = $user."savedfiles";
10371:     my @return_files;
10372:     my $path_part;
10373:     open(IN, '<',LONCAPA::tempdir().$filename);
10374:     while (my $line = <IN>) {
10375:         #ok, I know it's clunky, but I want it to work
10376:         my @paths_and_file = split(m|/|, $line);
10377:         my $file_part = pop(@paths_and_file);
10378:         chomp($file_part);
10379:         my $path_part = join('/', @paths_and_file);
10380:         $path_part .= '/';
10381:         my $path_and_file = $path_part.$file_part;
10382:         if ($path_part ne $path) {
10383:             push(@return_files, ($path_and_file));
10384:         }
10385:     }
10386:     close(OUT);
10387:     return (@return_files);
10388: }
10389: 
10390: #------------------------------Submitted/Handedback Portfolio Files Versioning
10391:  
10392: sub portfiles_versioning {
10393:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10394:     my $portfolio_root = '/userfiles/portfolio';
10395:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10396:     foreach my $file (@{$portfiles}) {
10397:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10398:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10399:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10400:         my $getpropath = 1;
10401:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10402:                                              $stu_name,$getpropath);
10403:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10404:         my $new_answer = 
10405:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10406:         if ($new_answer ne 'problem getting file') {
10407:             push(@{$versioned_portfiles}, $directory.$new_answer);
10408:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10409:                               [$symb,$env{'request.course.id'},'graded']);
10410:         }
10411:     }
10412: }
10413: 
10414: sub get_next_version {
10415:     my ($answer_name, $answer_ext, $dir_list) = @_;
10416:     my $version;
10417:     if (ref($dir_list) eq 'ARRAY') {
10418:         foreach my $row (@{$dir_list}) {
10419:             my ($file) = split(/\&/,$row,2);
10420:             my ($file_name,$file_version,$file_ext) =
10421:                 &file_name_version_ext($file);
10422:             if (($file_name eq $answer_name) &&
10423:                 ($file_ext eq $answer_ext)) {
10424:                      # gets here if filename and extension match,
10425:                      # regardless of version
10426:                 if ($file_version ne '') {
10427:                     # a versioned file is found  so save it for later
10428:                     if ($file_version > $version) {
10429:                         $version = $file_version;
10430:                     }
10431:                 }
10432:             }
10433:         }
10434:     }
10435:     $version ++;
10436:     return($version);
10437: }
10438: 
10439: sub version_selected_portfile {
10440:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10441:     my ($answer_name,$answer_ver,$answer_ext) =
10442:         &file_name_version_ext($file_name);
10443:     my $new_answer;
10444:     $env{'form.copy'} =
10445:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10446:     if($env{'form.copy'} eq '-1') {
10447:         $new_answer = 'problem getting file';
10448:     } else {
10449:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10450:         my $copy_result = 
10451:             &finishuserfileupload($stu_name,$domain,'copy',
10452:                                   '/portfolio'.$directory.$new_answer);
10453:     }
10454:     undef($env{'form.copy'});
10455:     return ($new_answer);
10456: }
10457: 
10458: sub file_name_version_ext {
10459:     my ($file)=@_;
10460:     my @file_parts = split(/\./, $file);
10461:     my ($name,$version,$ext);
10462:     if (@file_parts > 1) {
10463:         $ext=pop(@file_parts);
10464:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10465:             $version=pop(@file_parts);
10466:         }
10467:         $name=join('.',@file_parts);
10468:     } else {
10469:         $name=join('.',@file_parts);
10470:     }
10471:     return($name,$version,$ext);
10472: }
10473: 
10474: #----------------------------------------------Get portfolio file permissions
10475: 
10476: sub get_portfile_permissions {
10477:     my ($domain,$user) = @_;
10478:     my %current_permissions = &dump('file_permissions',$domain,$user);
10479:     my ($tmp)=keys(%current_permissions);
10480:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10481:     return \%current_permissions;
10482: }
10483: 
10484: #---------------------------------------------Get portfolio file access controls
10485: 
10486: sub get_access_controls {
10487:     my ($current_permissions,$group,$file) = @_;
10488:     my %access;
10489:     my $real_file = $file;
10490:     $file =~ s/\.meta$//;
10491:     if (defined($file)) {
10492:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10493:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10494:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10495:             }
10496:         }
10497:     } else {
10498:         foreach my $key (keys(%{$current_permissions})) {
10499:             if ($key =~ /\0accesscontrol$/) {
10500:                 if (defined($group)) {
10501:                     if ($key !~ m-^\Q$group\E/-) {
10502:                         next;
10503:                     }
10504:                 }
10505:                 my ($fullpath) = split(/\0/,$key);
10506:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10507:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10508:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10509:                     }
10510:                 }
10511:             }
10512:         }
10513:     }
10514:     return %access;
10515: }
10516: 
10517: sub modify_access_controls {
10518:     my ($file_name,$changes,$domain,$user)=@_;
10519:     my ($outcome,$deloutcome);
10520:     my %store_permissions;
10521:     my %new_values;
10522:     my %new_control;
10523:     my %translation;
10524:     my @deletions = ();
10525:     my $now = time;
10526:     if (exists($$changes{'activate'})) {
10527:         if (ref($$changes{'activate'}) eq 'HASH') {
10528:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10529:             my $numnew = scalar(@newitems);
10530:             for (my $i=0; $i<$numnew; $i++) {
10531:                 my $newkey = $newitems[$i];
10532:                 my $newid = &Apache::loncommon::get_cgi_id();
10533:                 if ($newkey =~ /^\d+:/) { 
10534:                     $newkey =~ s/^(\d+)/$newid/;
10535:                     $translation{$1} = $newid;
10536:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10537:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10538:                     $translation{$1} = $newid;
10539:                 }
10540:                 $new_values{$file_name."\0".$newkey} = 
10541:                                           $$changes{'activate'}{$newitems[$i]};
10542:                 $new_control{$newkey} = $now;
10543:             }
10544:         }
10545:     }
10546:     my %todelete;
10547:     my %changed_items;
10548:     foreach my $action ('delete','update') {
10549:         if (exists($$changes{$action})) {
10550:             if (ref($$changes{$action}) eq 'HASH') {
10551:                 foreach my $key (keys(%{$$changes{$action}})) {
10552:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10553:                     if ($action eq 'delete') { 
10554:                         $todelete{$itemnum} = 1;
10555:                     } else {
10556:                         $changed_items{$itemnum} = $key;
10557:                     }
10558:                 }
10559:             }
10560:         }
10561:     }
10562:     # get lock on access controls for file.
10563:     my $lockhash = {
10564:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10565:                                                        ':'.$env{'user.domain'},
10566:                    }; 
10567:     my $tries = 0;
10568:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10569:    
10570:     while (($gotlock ne 'ok') && $tries < 10) {
10571:         $tries ++;
10572:         sleep(0.1);
10573:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10574:     }
10575:     if ($gotlock eq 'ok') {
10576:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10577:         my ($tmp)=keys(%curr_permissions);
10578:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10579:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10580:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10581:             if (ref($curr_controls) eq 'HASH') {
10582:                 foreach my $control_item (keys(%{$curr_controls})) {
10583:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10584:                     if (defined($todelete{$itemnum})) {
10585:                         push(@deletions,$file_name."\0".$control_item);
10586:                     } else {
10587:                         if (defined($changed_items{$itemnum})) {
10588:                             $new_control{$changed_items{$itemnum}} = $now;
10589:                             push(@deletions,$file_name."\0".$control_item);
10590:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10591:                         } else {
10592:                             $new_control{$control_item} = $$curr_controls{$control_item};
10593:                         }
10594:                     }
10595:                 }
10596:             }
10597:         }
10598:         my ($group);
10599:         if (&is_course($domain,$user)) {
10600:             ($group,my $file) = split(/\//,$file_name,2);
10601:         }
10602:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10603:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10604:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10605:         #  remove lock
10606:         my @del_lock = ($file_name."\0".'locked_access_records');
10607:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10608:         my $sqlresult =
10609:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10610:                                     $group);
10611:     } else {
10612:         $outcome = "error: could not obtain lockfile\n";  
10613:     }
10614:     return ($outcome,$deloutcome,\%new_values,\%translation);
10615: }
10616: 
10617: sub make_public_indefinitely {
10618:     my (@requrl) = @_;
10619:     return &automated_portfile_access('public',\@requrl);
10620: }
10621: 
10622: sub automated_portfile_access {
10623:     my ($accesstype,$addsref,$delsref,$info) = @_;
10624:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10625:         return 'invalid';
10626:     }
10627:     my %urls;
10628:     if (ref($addsref) eq 'ARRAY') {
10629:         foreach my $requrl (@{$addsref}) {
10630:             if (&is_portfolio_url($requrl)) {
10631:                 unless (exists($urls{$requrl})) {
10632:                     $urls{$requrl} = 'add';
10633:                 }
10634:             }
10635:         }
10636:     }
10637:     if (ref($delsref) eq 'ARRAY') {
10638:         foreach my $requrl (@{$delsref}) { 
10639:             if (&is_portfolio_url($requrl)) {
10640:                 unless (exists($urls{$requrl})) {
10641:                     $urls{$requrl} = 'delete'; 
10642:                 }
10643:             }
10644:         }
10645:     }
10646:     unless (keys(%urls)) {
10647:         return 'invalid';
10648:     }
10649:     my $ip;
10650:     if ($accesstype eq 'ip') {
10651:         if (ref($info) eq 'HASH') {
10652:             if ($info->{'ip'} ne '') {
10653:                 $ip = $info->{'ip'};
10654:             }
10655:         }
10656:         if ($ip eq '') {
10657:             return 'invalid';
10658:         }
10659:     }
10660:     my $errors;
10661:     my $now = time;
10662:     my %current_perms;
10663:     foreach my $requrl (sort(keys(%urls))) {
10664:         my $action;
10665:         if ($urls{$requrl} eq 'add') {
10666:             $action = 'activate';
10667:         } else {
10668:             $action = 'none';
10669:         }
10670:         my $aclnum = 0;
10671:         my (undef,$udom,$unum,$file_name,$group) =
10672:             &parse_portfolio_url($requrl);
10673:         unless (exists($current_perms{$unum.':'.$udom})) {
10674:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10675:         }
10676:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10677:                                                    $group,$file_name);
10678:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10679:             my ($num,$scope,$end,$start) = 
10680:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10681:             if ($scope eq $accesstype) {
10682:                 if (($start <= $now) && ($end == 0)) {
10683:                     if ($accesstype eq 'ip') {
10684:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10685:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10686:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10687:                                     if ($urls{$requrl} eq 'add') {
10688:                                         $action = 'none';
10689:                                         last;
10690:                                     } else {
10691:                                         $action = 'delete';
10692:                                         $aclnum = $num;
10693:                                         last;
10694:                                     }
10695:                                 }
10696:                             }
10697:                         }
10698:                     } elsif ($accesstype eq 'public') {
10699:                         if ($urls{$requrl} eq 'add') {
10700:                             $action = 'none';
10701:                             last;
10702:                         } else {
10703:                             $action = 'delete';
10704:                             $aclnum = $num;
10705:                             last;
10706:                         }
10707:                     }
10708:                 } elsif ($accesstype eq 'public') {
10709:                     $action = 'update';
10710:                     $aclnum = $num;
10711:                     last;
10712:                 }
10713:             }
10714:         }
10715:         if ($action eq 'none') {
10716:             next;
10717:         } else {
10718:             my %changes;
10719:             my $newend = 0;
10720:             my $newstart = $now;
10721:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10722:             $changes{$action}{$newkey} = {
10723:                 type => $accesstype,
10724:                 time => {
10725:                     start => $newstart,
10726:                     end   => $newend,
10727:                 },
10728:             };
10729:             if ($accesstype eq 'ip') {
10730:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10731:             }
10732:             my ($outcome,$deloutcome,$new_values,$translation) =
10733:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10734:             unless ($outcome eq 'ok') {
10735:                 $errors .= $outcome.' ';
10736:             }
10737:         }
10738:     }
10739:     if ($errors) {
10740:         $errors =~ s/\s$//;
10741:         return $errors;
10742:     } else {
10743:         return 'ok';
10744:     }
10745: }
10746: 
10747: #------------------------------------------------------Get Marked as Read Only
10748: 
10749: sub get_marked_as_readonly {
10750:     my ($domain,$user,$what,$group) = @_;
10751:     my $current_permissions = &get_portfile_permissions($domain,$user);
10752:     my @readonly_files;
10753:     my $cmp1=$what;
10754:     if (ref($what)) { $cmp1=join('',@{$what}) };
10755:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10756:         if (defined($group)) {
10757:             if ($file_name !~ m-^\Q$group\E/-) {
10758:                 next;
10759:             }
10760:         }
10761:         if (ref($value) eq "ARRAY"){
10762:             foreach my $stored_what (@{$value}) {
10763:                 my $cmp2=$stored_what;
10764:                 if (ref($stored_what) eq 'ARRAY') {
10765:                     $cmp2=join('',@{$stored_what});
10766:                 }
10767:                 if ($cmp1 eq $cmp2) {
10768:                     push(@readonly_files, $file_name);
10769:                     last;
10770:                 } elsif (!defined($what)) {
10771:                     push(@readonly_files, $file_name);
10772:                     last;
10773:                 }
10774:             }
10775:         }
10776:     }
10777:     return @readonly_files;
10778: }
10779: #-----------------------------------------------------------Get Marked as Read Only Hash
10780: 
10781: sub get_marked_as_readonly_hash {
10782:     my ($current_permissions,$group,$what) = @_;
10783:     my %readonly_files;
10784:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10785:         if (defined($group)) {
10786:             if ($file_name !~ m-^\Q$group\E/-) {
10787:                 next;
10788:             }
10789:         }
10790:         if (ref($value) eq "ARRAY"){
10791:             foreach my $stored_what (@{$value}) {
10792:                 if (ref($stored_what) eq 'ARRAY') {
10793:                     foreach my $lock_descriptor(@{$stored_what}) {
10794:                         if ($lock_descriptor eq 'graded') {
10795:                             $readonly_files{$file_name} = 'graded';
10796:                         } elsif ($lock_descriptor eq 'handback') {
10797:                             $readonly_files{$file_name} = 'handback';
10798:                         } else {
10799:                             if (!exists($readonly_files{$file_name})) {
10800:                                 $readonly_files{$file_name} = 'locked';
10801:                             }
10802:                         }
10803:                     }
10804:                 } 
10805:             }
10806:         } 
10807:     }
10808:     return %readonly_files;
10809: }
10810: # ------------------------------------------------------------ Unmark as Read Only
10811: 
10812: sub unmark_as_readonly {
10813:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10814:     # for portfolio submissions, $what contains [$symb,$crsid] 
10815:     my ($domain,$user,$what,$file_name,$group) = @_;
10816:     $file_name = &declutter_portfile($file_name);
10817:     my $symb_crs = $what;
10818:     if (ref($what)) { $symb_crs=join('',@$what); }
10819:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10820:     my ($tmp)=keys(%current_permissions);
10821:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10822:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10823:     foreach my $file (@readonly_files) {
10824: 	my $clean_file = &declutter_portfile($file);
10825: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10826: 	my $current_locks = $current_permissions{$file};
10827:         my @new_locks;
10828:         my @del_keys;
10829:         if (ref($current_locks) eq "ARRAY"){
10830:             foreach my $locker (@{$current_locks}) {
10831:                 my $compare=$locker;
10832:                 if (ref($locker) eq 'ARRAY') {
10833:                     $compare=join('',@{$locker});
10834:                     if ($compare ne $symb_crs) {
10835:                         push(@new_locks, $locker);
10836:                     }
10837:                 }
10838:             }
10839:             if (scalar(@new_locks) > 0) {
10840:                 $current_permissions{$file} = \@new_locks;
10841:             } else {
10842:                 push(@del_keys, $file);
10843:                 &del('file_permissions',\@del_keys, $domain, $user);
10844:                 delete($current_permissions{$file});
10845:             }
10846:         }
10847:     }
10848:     &put('file_permissions',\%current_permissions,$domain,$user);
10849:     return;
10850: }
10851: 
10852: # ------------------------------------------------------------ Directory lister
10853: 
10854: sub dirlist {
10855:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10856:     $uri=~s/^\///;
10857:     $uri=~s/\/$//;
10858:     my ($udom, $uname);
10859:     if ($getuserdir) {
10860:         $udom = $userdomain;
10861:         $uname = $username;
10862:     } else {
10863:         (undef,$udom,$uname)=split(/\//,$uri);
10864:         if(defined($userdomain)) {
10865:             $udom = $userdomain;
10866:         }
10867:         if(defined($username)) {
10868:             $uname = $username;
10869:         }
10870:     }
10871:     my ($dirRoot,$listing,@listing_results);
10872: 
10873:     $dirRoot = $perlvar{'lonDocRoot'};
10874:     if (defined($getpropath)) {
10875:         $dirRoot = &propath($udom,$uname);
10876:         $dirRoot =~ s/\/$//;
10877:     } elsif (defined($getuserdir)) {
10878:         my $subdir=$uname.'__';
10879:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10880:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10881:                    ."/$udom/$subdir/$uname";
10882:     } elsif (defined($alternateRoot)) {
10883:         $dirRoot = $alternateRoot;
10884:     }
10885: 
10886:     if($udom) {
10887:         if($uname) {
10888:             my $uhome = &homeserver($uname,$udom);
10889:             if ($uhome eq 'no_host') {
10890:                 return ([],'no_host');
10891:             }
10892:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10893:                               .$getuserdir.':'.&escape($dirRoot)
10894:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10895:             if ($listing eq 'unknown_cmd') {
10896:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10897:             } else {
10898:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10899:             }
10900:             if ($listing eq 'unknown_cmd') {
10901:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10902:                 @listing_results = split(/:/,$listing);
10903:             } else {
10904:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10905:             }
10906:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10907:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10908:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10909:                 return ([],$listing);
10910:             } else {
10911:                 return (\@listing_results);
10912:             }
10913:         } elsif(!$alternateRoot) {
10914:             my (%allusers,%listerror);
10915: 	    my %servers = &get_servers($udom,'library');
10916:  	    foreach my $tryserver (keys(%servers)) {
10917:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10918:                                   &escape($udom),$tryserver);
10919:                 if ($listing eq 'unknown_cmd') {
10920: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10921: 				      $udom, $tryserver);
10922:                 } else {
10923:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10924:                 }
10925: 		if ($listing eq 'unknown_cmd') {
10926: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10927: 				      $udom, $tryserver);
10928: 		    @listing_results = split(/:/,$listing);
10929: 		} else {
10930: 		    @listing_results =
10931: 			map { &unescape($_); } split(/:/,$listing);
10932: 		}
10933:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10934:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10935:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10936:                     $listerror{$tryserver} = $listing;
10937:                 } else {
10938: 		    foreach my $line (@listing_results) {
10939: 			my ($entry) = split(/&/,$line,2);
10940: 			$allusers{$entry} = 1;
10941: 		    }
10942: 		}
10943:             }
10944:             my @alluserslist=();
10945:             foreach my $user (sort(keys(%allusers))) {
10946:                 push(@alluserslist,$user.'&user');
10947:             }
10948: 
10949:             if (!%listerror) {
10950:                 # no errors
10951:                 return (\@alluserslist);
10952:             } elsif (scalar(keys(%servers)) == 1) {
10953:                 # one library server, one error 
10954:                 my ($key) = keys(%listerror);
10955:                 return (\@alluserslist, $listerror{$key});
10956:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10957:                 # con_lost indicates that we might miss data from at least one
10958:                 # library server
10959:                 return (\@alluserslist, 'con_lost');
10960:             } else {
10961:                 # multiple library servers and no con_lost -> data should be
10962:                 # complete. 
10963:                 return (\@alluserslist);
10964:             }
10965: 
10966:         } else {
10967:             return ([],'missing username');
10968:         }
10969:     } elsif(!defined($getpropath)) {
10970:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10971:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10972:         return (\@all_domains);
10973:     } else {
10974:         return ([],'missing domain');
10975:     }
10976: }
10977: 
10978: # --------------------------------------------- GetFileTimestamp
10979: # This function utilizes dirlist and returns the date stamp for
10980: # when it was last modified.  It will also return an error of -1
10981: # if an error occurs
10982: 
10983: sub GetFileTimestamp {
10984:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10985:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10986:     $studentName   = &LONCAPA::clean_username($studentName);
10987:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10988:                                     undef,$getuserdir);
10989:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10990:         return -1;
10991:     }
10992:     if (ref($fileref) eq 'ARRAY') {
10993:         my @stats = split('&',$fileref->[0]);
10994:         # @stats contains first the filename, then the stat output
10995:         return $stats[10]; # so this is 10 instead of 9.
10996:     } else {
10997:         return -1;
10998:     }
10999: }
11000: 
11001: sub stat_file {
11002:     my ($uri) = @_;
11003:     $uri = &clutter_with_no_wrapper($uri);
11004: 
11005:     my ($udom,$uname,$file);
11006:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11007: 	($udom,$uname,$file) =
11008: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11009: 	$file = 'userfiles/'.$file;
11010:     }
11011:     if ($uri =~ m-^/res/-) {
11012: 	($udom,$uname) = 
11013: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11014: 	$file = $uri;
11015:     }
11016: 
11017:     if (!$udom || !$uname || !$file) {
11018: 	# unable to handle the uri
11019: 	return ();
11020:     }
11021:     my $getpropath;
11022:     if ($file =~ /^userfiles\//) {
11023:         $getpropath = 1;
11024:     }
11025:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11026:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11027:         return ();
11028:     } else {
11029:         if (ref($listref) eq 'ARRAY') {
11030:             my @stats = split('&',$listref->[0]);
11031: 	    shift(@stats); #filename is first
11032: 	    return @stats;
11033:         }
11034:     }
11035:     return ();
11036: }
11037: 
11038: # --------------------------------------------------------- recursedirs
11039: # Recursive function to traverse either a specific user's Authoring Space
11040: # or corresponding Published Resource Space, and populate the hash ref:
11041: # $dirhashref with URLs of all directories, and if $filehashref hash
11042: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11043: # or .rights files in resource space, and .meta, .save, .log, and .bak
11044: # files in Authoring Space.
11045: #
11046: # Inputs:
11047: #
11048: # $is_home - true if current server is home server for user's space
11049: # $context - either: priv, or res respectively for Authoring or Resource Space.
11050: # $docroot - Document root (i.e., /home/httpd/html
11051: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11052: # $relpath - Current path (relative to top level).
11053: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11054: # $filehashref - reference to hash to populate with URLs of files (Optional)
11055: #
11056: # Returns: nothing
11057: #
11058: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11059: #
11060: # Currently used by interface/londocs.pm to create linked select boxes for
11061: # directory and filename to import a Course "Author" resource into a course, and
11062: # also to create linked select boxes for Authoring Space and Directory to choose
11063: # save location for creation of a new "standard" problem from the Course Editor.
11064: #
11065: 
11066: sub recursedirs {
11067:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11068:     return unless (ref($dirhashref) eq 'HASH');
11069:     my $currpath = $docroot.$toppath;
11070:     if ($relpath) {
11071:         $currpath .= "/$relpath";
11072:     }
11073:     my $savefile;
11074:     if (ref($filehashref)) {
11075:         $savefile = 1;
11076:     }
11077:     if ($is_home) {
11078:         if (opendir(my $dirh,$currpath)) {
11079:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11080:                 next if ($item eq '');
11081:                 if (-d "$currpath/$item") {
11082:                     my $newpath;
11083:                     if ($relpath) {
11084:                         $newpath = "$relpath/$item";
11085:                     } else {
11086:                         $newpath = $item;
11087:                     }
11088:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11089:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11090:                 } elsif ($savefile) {
11091:                     if ($context eq 'priv') {
11092:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11093:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11094:                         }
11095:                     } else {
11096:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11097:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11098:                         }
11099:                     }
11100:                 }
11101:             }
11102:             closedir($dirh);
11103:         }
11104:     } else {
11105:         my ($dirlistref,$listerror) =
11106:             &dirlist($toppath.$relpath);
11107:         my @dir_lines;
11108:         my $dirptr=16384;
11109:         if (ref($dirlistref) eq 'ARRAY') {
11110:             foreach my $dir_line (sort
11111:                               {
11112:                                   my ($afile)=split('&',$a,2);
11113:                                   my ($bfile)=split('&',$b,2);
11114:                                   return (lc($afile) cmp lc($bfile));
11115:                               } (@{$dirlistref})) {
11116:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11117:                     split(/\&/,$dir_line,16);
11118:                 $item =~ s/\s+$//;
11119:                 next if (($item =~ /^\.\.?$/) || ($obs));
11120:                 if ($dirptr&$testdir) {
11121:                     my $newpath;
11122:                     if ($relpath) {
11123:                         $newpath = "$relpath/$item";
11124:                     } else {
11125:                         $relpath = '/';
11126:                         $newpath = $item;
11127:                     }
11128:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11129:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11130:                 } elsif ($savefile) {
11131:                     if ($context eq 'priv') {
11132:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11133:                             $filehashref->{$relpath}{$item} = 1;
11134:                         }
11135:                     } else {
11136:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11137:                             $filehashref->{$relpath}{$item} = 1;
11138:                         }
11139:                     }
11140:                 }
11141:             }
11142:         }
11143:     }
11144:     return;
11145: }
11146: 
11147: # -------------------------------------------------------- Value of a Condition
11148: 
11149: # gets the value of a specific preevaluated condition
11150: #    stored in the string  $env{user.state.<cid>}
11151: # or looks up a condition reference in the bighash and if if hasn't
11152: # already been evaluated recurses into docondval to get the value of
11153: # the condition, then memoizing it to 
11154: #   $env{user.state.<cid>.<condition>}
11155: sub directcondval {
11156:     my $number=shift;
11157:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11158: 	&Apache::lonuserstate::evalstate();
11159:     }
11160:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11161: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11162:     } elsif ($number =~ /^_/) {
11163: 	my $sub_condition;
11164: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11165: 		&GDBM_READER(),0640)) {
11166: 	    $sub_condition=$bighash{'conditions'.$number};
11167: 	    untie(%bighash);
11168: 	}
11169: 	my $value = &docondval($sub_condition);
11170: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11171: 	return $value;
11172:     }
11173:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11174:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11175:     } else {
11176:        return 2;
11177:     }
11178: }
11179: 
11180: # get the collection of conditions for this resource
11181: sub condval {
11182:     my $condidx=shift;
11183:     my $allpathcond='';
11184:     foreach my $cond (split(/\|/,$condidx)) {
11185: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11186: 	    $allpathcond.=
11187: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11188: 	}
11189:     }
11190:     $allpathcond=~s/\|$//;
11191:     return &docondval($allpathcond);
11192: }
11193: 
11194: #evaluates an expression of conditions
11195: sub docondval {
11196:     my ($allpathcond) = @_;
11197:     my $result=0;
11198:     if ($env{'request.course.id'}
11199: 	&& defined($allpathcond)) {
11200: 	my $operand='|';
11201: 	my @stack;
11202: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11203: 	    if ($chunk eq '(') {
11204: 		push @stack,($operand,$result);
11205: 	    } elsif ($chunk eq ')') {
11206: 		my $before=pop @stack;
11207: 		if (pop @stack eq '&') {
11208: 		    $result=$result>$before?$before:$result;
11209: 		} else {
11210: 		    $result=$result>$before?$result:$before;
11211: 		}
11212: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11213: 		$operand=$chunk;
11214: 	    } else {
11215: 		my $new=directcondval($chunk);
11216: 		if ($operand eq '&') {
11217: 		    $result=$result>$new?$new:$result;
11218: 		} else {
11219: 		    $result=$result>$new?$result:$new;
11220: 		}
11221: 	    }
11222: 	}
11223:     }
11224:     return $result;
11225: }
11226: 
11227: # ---------------------------------------------------- Devalidate courseresdata
11228: 
11229: sub devalidatecourseresdata {
11230:     my ($coursenum,$coursedomain)=@_;
11231:     my $hashid=$coursenum.':'.$coursedomain;
11232:     &devalidate_cache_new('courseres',$hashid);
11233: }
11234: 
11235: 
11236: # --------------------------------------------------- Course Resourcedata Query
11237: #
11238: #  Parameters:
11239: #      $coursenum    - Number of the course.
11240: #      $coursedomain - Domain at which the course was created.
11241: #  Returns:
11242: #     A hash of the course parameters along (I think) with timestamps
11243: #     and version info.
11244: 
11245: sub get_courseresdata {
11246:     my ($coursenum,$coursedomain)=@_;
11247:     my $coursehom=&homeserver($coursenum,$coursedomain);
11248:     my $hashid=$coursenum.':'.$coursedomain;
11249:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11250:     my %dumpreply;
11251:     unless (defined($cached)) {
11252: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11253: 	$result=\%dumpreply;
11254: 	my ($tmp) = keys(%dumpreply);
11255: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11256: 	    &do_cache_new('courseres',$hashid,$result,600);
11257: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11258: 	    return $tmp;
11259: 	} elsif ($tmp =~ /^(error)/) {
11260: 	    $result=undef;
11261: 	    &do_cache_new('courseres',$hashid,$result,600);
11262: 	}
11263:     }
11264:     return $result;
11265: }
11266: 
11267: sub devalidateuserresdata {
11268:     my ($uname,$udom)=@_;
11269:     my $hashid="$udom:$uname";
11270:     &devalidate_cache_new('userres',$hashid);
11271: }
11272: 
11273: sub get_userresdata {
11274:     my ($uname,$udom)=@_;
11275:     #most student don\'t have any data set, check if there is some data
11276:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11277: 
11278:     my $hashid="$udom:$uname";
11279:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11280:     if (!defined($cached)) {
11281: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11282: 	$result=\%resourcedata;
11283: 	&do_cache_new('userres',$hashid,$result,600);
11284:     }
11285:     my ($tmp)=keys(%$result);
11286:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11287: 	return $result;
11288:     }
11289:     #error 2 occurs when the .db doesn't exist
11290:     if ($tmp!~/error: 2 /) {
11291:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11292: 	    &logthis("<font color=\"blue\">WARNING:".
11293: 		     " Trying to get resource data for ".
11294: 		     $uname." at ".$udom.": ".
11295: 		     $tmp."</font>");
11296:         }
11297:     } elsif ($tmp=~/error: 2 /) {
11298: 	#&EXT_cache_set($udom,$uname);
11299: 	&do_cache_new('userres',$hashid,undef,600);
11300: 	undef($tmp); # not really an error so don't send it back
11301:     }
11302:     return $tmp;
11303: }
11304: #----------------------------------------------- resdata - return resource data
11305: #  Purpose:
11306: #    Return resource data for either users or for a course.
11307: #  Parameters:
11308: #     $name      - Course/user name.
11309: #     $domain    - Name of the domain the user/course is registered on.
11310: #     $type      - Type of thing $name is (must be 'course' or 'user')
11311: #     $mapp      - decluttered URL of enclosing map  
11312: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11313: #     $recurseup - Ref to array of map URLs, starting with map containing
11314: #                  $mapp up through hierarchy of nested maps to top level map.  
11315: #     $courseid  - CourseID (first part of param identifier).
11316: #     $modifier  - Middle part of param identifier.
11317: #     $what      - Last part of param identifier.
11318: #     @which     - Array of names of resources desired.
11319: #  Returns:
11320: #     The value of the first reasource in @which that is found in the
11321: #     resource hash.
11322: #  Exceptional Conditions:
11323: #     If the $type passed in is not valid (not the string 'course' or 
11324: #     'user', an undefined  reference is returned.
11325: #     If none of the resources are found, an undef is returned
11326: sub resdata {
11327:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11328:         $modifier,$what,@which)=@_;
11329:     my $result;
11330:     if ($type eq 'course') {
11331: 	$result=&get_courseresdata($name,$domain);
11332:     } elsif ($type eq 'user') {
11333: 	$result=&get_userresdata($name,$domain);
11334:     }
11335:     if (!ref($result)) { return $result; }    
11336:     foreach my $item (@which) {
11337:         if ($item->[1] eq 'course') {
11338:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11339:                 unless ($$recursed) {
11340:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11341:                     $$recursed = 1;
11342:                 }
11343:                 foreach my $item (@${recurseup}) {
11344:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11345:                     last if (defined($result->{$norecursechk}));
11346:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11347:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11348:                 }
11349:             }
11350:         }
11351:         if (defined($result->{$item->[0]})) {
11352: 	    return [$result->{$item->[0]},$item->[1]];
11353: 	}
11354:     }
11355:     return undef;
11356: }
11357: 
11358: sub get_domain_lti {
11359:     my ($cdom,$context) = @_;
11360:     my ($name,%lti);
11361:     if ($context eq 'consumer') {
11362:         $name = 'ltitools';
11363:     } elsif ($context eq 'provider') {
11364:         $name = 'lti';
11365:     } else {
11366:         return %lti;
11367:     }
11368:     my ($result,$cached)=&is_cached_new($name,$cdom);
11369:     if (defined($cached)) {
11370:         if (ref($result) eq 'HASH') {
11371:             %lti = %{$result};
11372:         }
11373:     } else {
11374:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11375:         if (ref($domconfig{$name}) eq 'HASH') {
11376:             %lti = %{$domconfig{$name}};
11377:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11378:             if (ref($encdomconfig{$name}) eq 'HASH') {
11379:                 foreach my $id (keys(%lti)) {
11380:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11381:                         foreach my $item ('key','secret') {
11382:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11383:                         }
11384:                     }
11385:                 }
11386:             }
11387:         }
11388:         my $cachetime = 24*60*60;
11389:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11390:     }
11391:     return %lti;
11392: }
11393: 
11394: sub get_numsuppfiles {
11395:     my ($cnum,$cdom,$ignorecache)=@_;
11396:     my $hashid=$cnum.':'.$cdom;
11397:     my ($suppcount,$cached);
11398:     unless ($ignorecache) {
11399:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11400:     }
11401:     unless (defined($cached)) {
11402:         my $chome=&homeserver($cnum,$cdom);
11403:         unless ($chome eq 'no_host') {
11404:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11405:             my $suppmap = 'supplemental.sequence';
11406:             ($suppcount,$supptools,$errors) =
11407:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11408:                                                          $supptools,$errors);
11409:         }
11410:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11411:     }
11412:     return $suppcount;
11413: }
11414: 
11415: #
11416: # EXT resource caching routines
11417: #
11418: 
11419: {
11420: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11421: #
11422: # The course for which we cache
11423: my $cachedmapkey='';
11424: # The cached recursive maps for this course
11425: my %cachedmaps=();
11426: # When this was last done
11427: my $cachedmaptime='';
11428: 
11429: sub clear_EXT_cache_status {
11430:     &delenv('cache.EXT.');
11431: }
11432: 
11433: sub EXT_cache_status {
11434:     my ($target_domain,$target_user) = @_;
11435:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11436:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11437:         # We know already the user has no data
11438:         return 1;
11439:     } else {
11440:         return 0;
11441:     }
11442: }
11443: 
11444: sub EXT_cache_set {
11445:     my ($target_domain,$target_user) = @_;
11446:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11447:     #&appenv({$cachename => time});
11448: }
11449: 
11450: # --------------------------------------------------------- Value of a Variable
11451: sub EXT {
11452: 
11453:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11454:     unless ($varname) { return ''; }
11455:     #get real user name/domain, courseid and symb
11456:     my $courseid;
11457:     my $publicuser;
11458:     if ($symbparm) {
11459: 	$symbparm=&get_symb_from_alias($symbparm);
11460:     }
11461:     if (!($uname && $udom)) {
11462:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11463:       if (!$symbparm) {	$symbparm=$cursymb; }
11464:     } else {
11465: 	$courseid=$env{'request.course.id'};
11466:     }
11467:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11468:     my $rest;
11469:     if (defined($therest[0])) {
11470:        $rest=join('.',@therest);
11471:     } else {
11472:        $rest='';
11473:     }
11474: 
11475:     my $qualifierrest=$qualifier;
11476:     if ($rest) { $qualifierrest.='.'.$rest; }
11477:     my $spacequalifierrest=$space;
11478:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11479:     if ($realm eq 'user') {
11480: # --------------------------------------------------------------- user.resource
11481: 	if ($space eq 'resource') {
11482: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11483: 		  || defined($Apache::lonhomework::parsing_a_task))
11484: 		 &&
11485: 		 ($symbparm eq &symbread()) ) {	
11486: 		# if we are in the middle of processing the resource the
11487: 		# get the value we are planning on committing
11488:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11489:                     return $Apache::lonhomework::results{$qualifierrest};
11490:                 } else {
11491:                     return $Apache::lonhomework::history{$qualifierrest};
11492:                 }
11493: 	    } else {
11494: 		my %restored;
11495: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11496: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11497: 		} else {
11498: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11499: 		}
11500: 		return $restored{$qualifierrest};
11501: 	    }
11502: # ----------------------------------------------------------------- user.access
11503:         } elsif ($space eq 'access') {
11504: 	    # FIXME - not supporting calls for a specific user
11505:             return &allowed($qualifier,$rest);
11506: # ------------------------------------------ user.preferences, user.environment
11507:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11508: 	    if (($uname eq $env{'user.name'}) &&
11509: 		($udom eq $env{'user.domain'})) {
11510: 		return $env{join('.',('environment',$qualifierrest))};
11511: 	    } else {
11512: 		my %returnhash;
11513: 		if (!$publicuser) {
11514: 		    %returnhash=&userenvironment($udom,$uname,
11515: 						 $qualifierrest);
11516: 		}
11517: 		return $returnhash{$qualifierrest};
11518: 	    }
11519: # ----------------------------------------------------------------- user.course
11520:         } elsif ($space eq 'course') {
11521: 	    # FIXME - not supporting calls for a specific user
11522:             return $env{join('.',('request.course',$qualifier))};
11523: # ------------------------------------------------------------------- user.role
11524:         } elsif ($space eq 'role') {
11525: 	    # FIXME - not supporting calls for a specific user
11526:             my ($role,$where)=split(/\./,$env{'request.role'});
11527:             if ($qualifier eq 'value') {
11528: 		return $role;
11529:             } elsif ($qualifier eq 'extent') {
11530:                 return $where;
11531:             }
11532: # ----------------------------------------------------------------- user.domain
11533:         } elsif ($space eq 'domain') {
11534:             return $udom;
11535: # ------------------------------------------------------------------- user.name
11536:         } elsif ($space eq 'name') {
11537:             return $uname;
11538: # ---------------------------------------------------- Any other user namespace
11539:         } else {
11540: 	    my %reply;
11541: 	    if (!$publicuser) {
11542: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11543: 	    }
11544: 	    return $reply{$qualifierrest};
11545:         }
11546:     } elsif ($realm eq 'query') {
11547: # ---------------------------------------------- pull stuff out of query string
11548:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11549: 						[$spacequalifierrest]);
11550: 	return $env{'form.'.$spacequalifierrest}; 
11551:    } elsif ($realm eq 'request') {
11552: # ------------------------------------------------------------- request.browser
11553:         if ($space eq 'browser') {
11554:             return $env{'browser.'.$qualifier};
11555: # ------------------------------------------------------------ request.filename
11556:         } else {
11557:             return $env{'request.'.$spacequalifierrest};
11558:         }
11559:     } elsif ($realm eq 'course') {
11560: # ---------------------------------------------------------- course.description
11561:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11562:     } elsif ($realm eq 'resource') {
11563: 
11564: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11565: 	    if (!$symbparm) { $symbparm=&symbread(); }
11566: 	}
11567: 
11568:         if ($qualifier eq '') {
11569: 	    if ($space eq 'title') {
11570: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11571: 	        return &gettitle($symbparm);
11572: 	    }
11573: 	
11574: 	    if ($space eq 'map') {
11575: 	        my ($map) = &decode_symb($symbparm);
11576: 	        return &symbread($map);
11577: 	    }
11578:             if ($space eq 'maptitle') {
11579:                 my ($map) = &decode_symb($symbparm);
11580:                 return &gettitle($map);
11581:             }
11582: 	    if ($space eq 'filename') {
11583: 	        if ($symbparm) {
11584: 		    return &clutter((&decode_symb($symbparm))[2]);
11585: 	        }
11586: 	        return &hreflocation('',$env{'request.filename'});
11587: 	    }
11588: 
11589:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11590:                 if ($space eq 'visibleparts') {
11591:                     my $navmap = Apache::lonnavmaps::navmap->new();
11592:                     my $item;
11593:                     if (ref($navmap)) {
11594:                         my $res = $navmap->getBySymb($symbparm);
11595:                         my $parts = $res->parts();
11596:                         if (ref($parts) eq 'ARRAY') {
11597:                             $item = join(',',@{$parts});
11598:                         }
11599:                         undef($navmap);
11600:                     }
11601:                     return $item;
11602:                 }
11603:             }
11604:         }
11605: 
11606: 	my ($section, $group, @groups, @recurseup, $recursed);
11607: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11608:         if (($courseid eq '') && ($cid)) {
11609:             $courseid = $cid;
11610:         }
11611: 	if (($symbparm && $courseid) && 
11612: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11613: 
11614: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11615: 
11616: # ----------------------------------------------------- Cascading lookup scheme
11617: 	    my $symbp=$symbparm;
11618: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11619: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11620:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11621: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11622: 	    if (($env{'user.name'} eq $uname) &&
11623: 		($env{'user.domain'} eq $udom)) {
11624: 		$section=$env{'request.course.sec'};
11625:                 @groups = split(/:/,$env{'request.course.groups'});  
11626:                 @groups=&sort_course_groups($courseid,@groups); 
11627: 	    } else {
11628: 		if (! defined($usection)) {
11629: 		    $section=&getsection($udom,$uname,$courseid);
11630: 		} else {
11631: 		    $section = $usection;
11632: 		}
11633:                 @groups = &get_users_groups($udom,$uname,$courseid);
11634: 	    }
11635: 
11636: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11637: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11638:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11639: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11640: 
11641: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11642: 	    my $courselevelr=$courseid.'.'.$symbparm;
11643:             $courseleveli=$courseid.'.'.$recurseparm;
11644: 	    $courselevelm=$courseid.'.'.$mapparm;
11645: 
11646: # ----------------------------------------------------------- first, check user
11647: 
11648: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11649:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11650: 				       ([$courselevelr,'resource'],
11651: 					[$courselevelm,'map'     ],
11652:                                         [$courseleveli,'map'     ],
11653: 					[$courselevel, 'course'  ]));
11654: 	    if (defined($userreply)) { return &get_reply($userreply); }
11655: 
11656: # ------------------------------------------------ second, check some of course
11657:             my $coursereply;
11658:             if (@groups > 0) {
11659:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11660:                                        $recurseparm,$mapparm,$spacequalifierrest,
11661:                                        $mapp,\$recursed,\@recurseup);
11662:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11663:             }
11664: 
11665: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11666: 				  $env{'course.'.$courseid.'.domain'},
11667: 				  'course',$mapp,\$recursed,\@recurseup,
11668:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11669: 				  ([$seclevelr,   'resource'],
11670: 				   [$seclevelm,   'map'     ],
11671:                                    [$secleveli,   'map'     ],
11672: 				   [$seclevel,    'course'  ],
11673: 				   [$courselevelr,'resource']));
11674: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11675: 
11676: # ------------------------------------------------------ third, check map parms
11677: 	    my %parmhash=();
11678: 	    my $thisparm='';
11679: 	    if (tie(%parmhash,'GDBM_File',
11680: 		    $env{'request.course.fn'}.'_parms.db',
11681: 		    &GDBM_READER(),0640)) {
11682: 		$thisparm=$parmhash{$symbparm};
11683: 		untie(%parmhash);
11684: 	    }
11685: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11686: 	}
11687: # ------------------------------------------ fourth, look in resource metadata
11688:  
11689:         my $what = $spacequalifierrest;
11690: 	$what=~s/\./\_/;
11691: 	my $filename;
11692: 	if (!$symbparm) { $symbparm=&symbread(); }
11693: 	if ($symbparm) {
11694: 	    $filename=(&decode_symb($symbparm))[2];
11695: 	} else {
11696: 	    $filename=$env{'request.filename'};
11697: 	}
11698:         my $toolsymb;
11699:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11700:             $toolsymb = $symbparm;
11701:         }
11702: 	my $metadata=&metadata($filename,$what,$toolsymb);
11703: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11704: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11705: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11706: 
11707: # ----------------------------------------------- fifth, look in rest of course
11708: 	if ($symbparm && defined($courseid) && 
11709: 	    $courseid eq $env{'request.course.id'}) {
11710: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11711: 				     $env{'course.'.$courseid.'.domain'},
11712: 				     'course',$mapp,\$recursed,\@recurseup,
11713:                                      $courseid,'.',$spacequalifierrest,
11714: 				     ([$courselevelm,'map'   ],
11715:                                       [$courseleveli,'map'   ],
11716: 				      [$courselevel, 'course']));
11717: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11718: 	}
11719: # ------------------------------------------------------------------ Cascade up
11720: 	unless ($space eq '0') {
11721: 	    my @parts=split(/_/,$space);
11722: 	    my $id=pop(@parts);
11723: 	    my $part=join('_',@parts);
11724: 	    if ($part eq '') { $part='0'; }
11725: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11726: 				 $symbparm,$udom,$uname,$section,1);
11727: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11728: 	}
11729: 	if ($recurse) { return undef; }
11730: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11731: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11732: # ---------------------------------------------------- Any other user namespace
11733:     } elsif ($realm eq 'environment') {
11734: # ----------------------------------------------------------------- environment
11735: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11736: 	    return $env{'environment.'.$spacequalifierrest};
11737: 	} else {
11738: 	    if ($uname eq 'anonymous' && $udom eq '') {
11739: 		return '';
11740: 	    }
11741: 	    my %returnhash=&userenvironment($udom,$uname,
11742: 					    $spacequalifierrest);
11743: 	    return $returnhash{$spacequalifierrest};
11744: 	}
11745:     } elsif ($realm eq 'system') {
11746: # ----------------------------------------------------------------- system.time
11747: 	if ($space eq 'time') {
11748: 	    return time;
11749:         }
11750:     } elsif ($realm eq 'server') {
11751: # ----------------------------------------------------------------- system.time
11752: 	if ($space eq 'name') {
11753: 	    return $ENV{'SERVER_NAME'};
11754:         }
11755:     }
11756:     return '';
11757: }
11758: 
11759: sub get_reply {
11760:     my ($reply_value) = @_;
11761:     if (ref($reply_value) eq 'ARRAY') {
11762:         if (wantarray) {
11763: 	    return @$reply_value;
11764:         }
11765:         return $reply_value->[0];
11766:     } else {
11767:         return $reply_value;
11768:     }
11769: }
11770: 
11771: sub check_group_parms {
11772:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11773:         $recursed,$recurseupref) = @_;
11774:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11775:                   [$what,'course']);
11776:     my $coursereply;
11777:     foreach my $group (@{$groups}) {
11778:         my @groupitems = ();
11779:         foreach my $level (@levels) {
11780:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11781:              push(@groupitems,[$item,$level->[1]]);
11782:         }
11783:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11784:                                    $env{'course.'.$courseid.'.domain'},
11785:                                    'course',$mapp,$recursed,$recurseupref,
11786:                                    $courseid,'.['.$group.'].',$what,
11787:                                    @groupitems);
11788:         last if (defined($coursereply));
11789:     }
11790:     return $coursereply;
11791: }
11792: 
11793: sub get_map_hierarchy {
11794:     my ($mapname,$courseid) = @_;
11795:     my @recurseup = ();
11796:     if ($mapname) {
11797:         if (($cachedmapkey eq $courseid) &&
11798:             (abs($cachedmaptime-time)<5)) {
11799:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11800:                 return @{$cachedmaps{$mapname}};
11801:             }
11802:         }
11803:         my $navmap = Apache::lonnavmaps::navmap->new();
11804:         if (ref($navmap)) {
11805:             @recurseup = $navmap->recurseup_maps($mapname);
11806:             undef($navmap);
11807:             $cachedmaps{$mapname} = \@recurseup;
11808:             $cachedmaptime=time;
11809:             $cachedmapkey=$courseid;
11810:         }
11811:     }
11812:     return @recurseup;
11813: }
11814: 
11815: }
11816: 
11817: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11818:     my ($courseid,@groups) = @_;
11819:     @groups = sort(@groups);
11820:     return @groups;
11821: }
11822: 
11823: sub packages_tab_default {
11824:     my ($uri,$varname,$toolsymb)=@_;
11825:     my (undef,$part,$name)=split(/\./,$varname);
11826: 
11827:     my (@extension,@specifics,$do_default);
11828:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11829: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11830: 	if ($pack_type eq 'default') {
11831: 	    $do_default=1;
11832: 	} elsif ($pack_type eq 'extension') {
11833: 	    push(@extension,[$package,$pack_type,$pack_part]);
11834: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11835: 	    # only look at packages defaults for packages that this id is
11836: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11837: 	}
11838:     }
11839:     # first look for a package that matches the requested part id
11840:     foreach my $package (@specifics) {
11841: 	my (undef,$pack_type,$pack_part)=@{$package};
11842: 	next if ($pack_part ne $part);
11843: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11844: 	    return $packagetab{"$pack_type&$name&default"};
11845: 	}
11846:     }
11847:     # look for any possible matching non extension_ package
11848:     foreach my $package (@specifics) {
11849: 	my (undef,$pack_type,$pack_part)=@{$package};
11850: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11851: 	    return $packagetab{"$pack_type&$name&default"};
11852: 	}
11853: 	if ($pack_type eq 'part') { $pack_part='0'; }
11854: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11855: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11856: 	}
11857:     }
11858:     # look for any posible extension_ match
11859:     foreach my $package (@extension) {
11860: 	my ($package,$pack_type)=@{$package};
11861: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11862: 	    return $packagetab{"$pack_type&$name&default"};
11863: 	}
11864: 	if (defined($packagetab{$package."&$name&default"})) {
11865: 	    return $packagetab{$package."&$name&default"};
11866: 	}
11867:     }
11868:     # look for a global default setting
11869:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11870: 	return $packagetab{"default&$name&default"};
11871:     }
11872:     return undef;
11873: }
11874: 
11875: sub add_prefix_and_part {
11876:     my ($prefix,$part)=@_;
11877:     my $keyroot;
11878:     if (defined($prefix) && $prefix !~ /^__/) {
11879: 	# prefix that has a part already
11880: 	$keyroot=$prefix;
11881:     } elsif (defined($prefix)) {
11882: 	# prefix that is missing a part
11883: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11884:     } else {
11885: 	# no prefix at all
11886: 	if (defined($part)) { $keyroot='_'.$part; }
11887:     }
11888:     return $keyroot;
11889: }
11890: 
11891: # ---------------------------------------------------------------- Get metadata
11892: 
11893: my %metaentry;
11894: my %importedpartids;
11895: my %importedrespids;
11896: sub metadata {
11897:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11898:     $uri=&declutter($uri);
11899:     # if it is a non metadata possible uri return quickly
11900:     if (($uri eq '') || 
11901: 	(($uri =~ m|^/*adm/|) && 
11902: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11903:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11904: 	return undef;
11905:     }
11906:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11907: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11908: 	return undef;
11909:     }
11910:     my $filename=$uri;
11911:     $uri=~s/\.meta$//;
11912: #
11913: # Is the metadata already cached?
11914: # Look at timestamp of caching
11915: # Everything is cached by the main uri, libraries are never directly cached
11916: #
11917:     if (!defined($liburi)) {
11918: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11919: 	if (defined($cached)) { return $result->{':'.$what}; }
11920:     }
11921: 
11922: #
11923: # If the uri is for an external tool the file from
11924: # which metadata should be retrieved depends on whether
11925: # the tool had been configured to be gradable (set in the Course
11926: # Editor or Resource Editor).
11927: #
11928: # If a valid symb has been included as the third arg in the call
11929: # to &metadata() that can be used to retrieve the value of
11930: # parameter_0_gradable set for the resource, and included in the
11931: # uploaded map containing the tool. The value is retrieved via
11932: # &EXT(), if a valid symb is available.  Otherwise the value of
11933: # gradable in the exttool_$marker.db file for the tool instance
11934: # is retrieved via &get().
11935: #
11936: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11937: # hiddenresource and encrypturl (during course initialization)
11938: # the map-level parameter for resource.0.gradable included in the 
11939: # uploaded map containing the tool will not yet have been stored
11940: # in the user_course_parms.db file for the user's session, so in 
11941: # this case fall back to retrieving gradable status from the
11942: # exttool_$marker.db file.
11943: #
11944: # In order to avoid an infinite loop, &metadata() will return
11945: # before a call to &EXT(), if the uri is for an external tool
11946: # and the $what for which metadata is being requested is
11947: # parameter_0_gradable or 0_gradable.
11948: #
11949: 
11950:     if ($uri =~ /ext\.tool$/) {
11951:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11952:             return;
11953:         } else {
11954:             my ($checked,$use_passback);
11955:             if ($toolsymb ne '') {
11956:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11957:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11958:                     $checked = 1;
11959:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11960:                         $use_passback = 1;
11961:                     }
11962:                 }
11963:             }
11964:             unless ($checked) {
11965:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11966:                 $marker=~s/\D//g;
11967:                 if ($marker) {
11968:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11969:                     $use_passback = $toolsettings{'gradable'};
11970:                 }
11971:             }
11972:             if ($use_passback) {
11973:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11974:             } else {
11975:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11976:             }
11977:         }
11978:     }
11979: 
11980:     {
11981: # Imported parts would go here
11982:         my @origfiletagids=();
11983:         my $importedparts=0;
11984: 
11985: # Imported responseids would go here
11986:         my $importedresponses=0;
11987: #
11988: # Is this a recursive call for a library?
11989: #
11990: #	if (! exists($metacache{$uri})) {
11991: #	    $metacache{$uri}={};
11992: #	}
11993: 	my $cachetime = 60*60;
11994:         if ($liburi) {
11995: 	    $liburi=&declutter($liburi);
11996:             $filename=$liburi;
11997:         } else {
11998: 	    &devalidate_cache_new('meta',$uri);
11999: 	    undef(%metaentry);
12000: 	}
12001:         my %metathesekeys=();
12002:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12003: 	my $metastring;
12004: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12005: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12006: 	    $metastring = 
12007: 		&Apache::lonnet::ssi_body($which,
12008: 					  ('grade_target' => 'meta'));
12009: 	    $cachetime = 1; # only want this cached in the child not long term
12010: 	} elsif (($uri !~ m -^(editupload)/-) && 
12011:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12012: 	    my $file=&filelocation('',&clutter($filename));
12013: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12014: 	    $metastring=&getfile($file);
12015: 	}
12016:         my $parser=HTML::LCParser->new(\$metastring);
12017:         my $token;
12018:         undef %metathesekeys;
12019:         while ($token=$parser->get_token) {
12020: 	    if ($token->[0] eq 'S') {
12021: 		if (defined($token->[2]->{'package'})) {
12022: #
12023: # This is a package - get package info
12024: #
12025: 		    my $package=$token->[2]->{'package'};
12026: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12027: 		    if (defined($token->[2]->{'id'})) { 
12028: 			$keyroot.='_'.$token->[2]->{'id'}; 
12029: 		    }
12030: 		    if ($metaentry{':packages'}) {
12031: 			$metaentry{':packages'}.=','.$package.$keyroot;
12032: 		    } else {
12033: 			$metaentry{':packages'}=$package.$keyroot;
12034: 		    }
12035: 		    foreach my $pack_entry (keys(%packagetab)) {
12036: 			my $part=$keyroot;
12037: 			$part=~s/^\_//;
12038: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12039: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12040: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12041: 			    # ignore package.tab specified default values
12042:                             # here &package_tab_default() will fetch those
12043: 			    if ($subp eq 'default') { next; }
12044: 			    my $value=$packagetab{$pack_entry};
12045: 			    my $unikey;
12046: 			    if ($pack =~ /_0$/) {
12047: 				$unikey='parameter_0_'.$name;
12048: 				$part=0;
12049: 			    } else {
12050: 				$unikey='parameter'.$keyroot.'_'.$name;
12051: 			    }
12052: 			    if ($subp eq 'display') {
12053: 				$value.=' [Part: '.$part.']';
12054: 			    }
12055: 			    $metaentry{':'.$unikey.'.part'}=$part;
12056: 			    $metathesekeys{$unikey}=1;
12057: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12058: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12059: 			    }
12060: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12061: 				$metaentry{':'.$unikey}=
12062: 				    $metaentry{':'.$unikey.'.default'};
12063: 			    }
12064: 			}
12065: 		    }
12066: 		} else {
12067: #
12068: # This is not a package - some other kind of start tag
12069: #
12070: 		    my $entry=$token->[1];
12071: 		    my $unikey='';
12072: 
12073: 		    if ($entry eq 'import') {
12074: #
12075: # Importing a library here
12076: #
12077:                         my $location=$parser->get_text('/import');
12078:                         my $dir=$filename;
12079:                         $dir=~s|[^/]*$||;
12080:                         $location=&filelocation($dir,$location);
12081: 
12082:                         my $importid=$token->[2]->{'id'};
12083:                         my $importmode=$token->[2]->{'importmode'};
12084: #
12085: # Check metadata for imported file to
12086: # see if it contained response items
12087: #
12088:                         my ($origfile,@libfilekeys);
12089:                         my %currmetaentry = %metaentry;
12090:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12091:                                                            $depthcount+1));
12092:                         if (grep(/^responseorder$/,@libfilekeys)) {
12093:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12094:                                                              undef,$depthcount+1);
12095:                             if ($libresponseorder ne '') {
12096:                                 if ($#origfiletagids<0) {
12097:                                     undef(%importedrespids);
12098:                                     undef(%importedpartids);
12099:                                 }
12100:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12101:                                 if (@respids) {
12102:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12103:                                 }
12104:                                 if ($importedrespids{$importid} ne '') {
12105:                                     $importedresponses = 1;
12106: # We need to get the original file and the imported file to get the response order correct
12107: # Load and inspect original file
12108:                                     if ($#origfiletagids<0) {
12109:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12110:                                         $origfile=&getfile($origfilelocation);
12111:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12112:                                     }
12113:                                 }
12114:                             }
12115:                         }
12116: # Do not overwrite contents of %metaentry hash for resource itself with 
12117: # hash populated for imported library file
12118:                         %metaentry = %currmetaentry;
12119:                         undef(%currmetaentry);
12120:                         if ($importmode eq 'part') {
12121: # Import as part(s)
12122:                            $importedparts=1;
12123: # We need to get the original file and the imported file to get the part order correct
12124: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12125: # Load and inspect original file if we didn't do that already
12126:                            if ($#origfiletagids<0) {
12127:                                undef(%importedrespids);
12128:                                undef(%importedpartids);
12129:                                if ($origfile eq '') {
12130:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12131:                                    $origfile=&getfile($origfilelocation);
12132:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12133:                                }
12134:                            }
12135:                            my @impfilepartids;
12136: # If <partorder> tag is included in metadata for the imported file
12137: # get the parts in the imported file from that.
12138:                            if (grep(/^partorder$/,@libfilekeys)) {
12139:                                %currmetaentry = %metaentry;
12140:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12141:                                                             $depthcount+1);
12142:                                %metaentry = %currmetaentry;
12143:                                undef(%currmetaentry);
12144:                                if ($libpartorder ne '') {
12145:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12146:                                }
12147:                            } else {
12148: # If no <partorder> tag available, load and inspect imported file
12149:                                my $impfile=&getfile($location);
12150:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12151:                            }
12152:                            if ($#impfilepartids>=0) {
12153: # This problem had parts
12154:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12155:                            } else {
12156: # Importing by turning a single problem into a problem part
12157: # It gets the import-tags ID as part-ID
12158:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12159:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12160:                            }
12161:                         } else {
12162: # Import as problem or as normal import
12163:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12164:                             unless ($importmode eq 'problem') {
12165: # Normal import
12166:                                 if (defined($token->[2]->{'id'})) {
12167:                                     $unikey.='_'.$token->[2]->{'id'};
12168:                                 }
12169:                             }
12170: # Check metadata for imported file to
12171: # see if it contained parts
12172:                             if (grep(/^partorder$/,@libfilekeys)) {
12173:                                 %currmetaentry = %metaentry;
12174:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12175:                                                              $depthcount+1);
12176:                                 %metaentry = %currmetaentry;
12177:                                 undef(%currmetaentry);
12178:                                 if ($libpartorder ne '') {
12179:                                     $importedparts = 1;
12180:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12181:                                 }
12182:                             }
12183:                         }
12184: 			if ($depthcount<20) {
12185: 			    my $metadata = 
12186: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12187: 					  $depthcount+1);
12188: 			    foreach my $meta (split(',',$metadata)) {
12189: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12190: 				$metathesekeys{$meta}=1;
12191: 			    }
12192:                         }
12193: 		    } else {
12194: #
12195: # Not importing, some other kind of non-package, non-library start tag
12196: # 
12197:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12198:                         if (defined($token->[2]->{'id'})) {
12199:                             $unikey.='_'.$token->[2]->{'id'};
12200:                         }
12201: 			if (defined($token->[2]->{'name'})) { 
12202: 			    $unikey.='_'.$token->[2]->{'name'}; 
12203: 			}
12204: 			$metathesekeys{$unikey}=1;
12205: 			foreach my $param (@{$token->[3]}) {
12206: 			    $metaentry{':'.$unikey.'.'.$param} =
12207: 				$token->[2]->{$param};
12208: 			}
12209: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12210: 			my $default=$metaentry{':'.$unikey.'.default'};
12211: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12212: 		 # only ws inside the tag, and not in default, so use default
12213: 		 # as value
12214: 			    $metaentry{':'.$unikey}=$default;
12215: 			} elsif ( $internaltext =~ /\S/ ) {
12216: 		  # something interesting inside the tag
12217: 			    $metaentry{':'.$unikey}=$internaltext;
12218: 			} else {
12219: 		  # no interesting values, don't set a default
12220: 			}
12221: # end of not-a-package not-a-library import
12222: 		    }
12223: # end of not-a-package start tag
12224: 		}
12225: # the next is the end of "start tag"
12226: 	    }
12227: 	}
12228: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12229: 	$extension = lc($extension);
12230: 	if ($extension eq 'htm') { $extension='html'; }
12231: 
12232: 	foreach my $key (keys(%packagetab)) {
12233: 	    #no specific packages #how's our extension
12234: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12235: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12236: 					 \%metathesekeys);
12237: 	}
12238: 
12239: 	if (!exists($metaentry{':packages'})
12240: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12241: 	    foreach my $key (keys(%packagetab)) {
12242: 		#no specific packages well let's get default then
12243: 		if ($key!~/^default&/) { next; }
12244: 		&metadata_create_package_def($uri,$key,'default',
12245: 					     \%metathesekeys);
12246: 	    }
12247: 	}
12248: # are there custom rights to evaluate
12249: 	if ($metaentry{':copyright'} eq 'custom') {
12250: 
12251:     #
12252:     # Importing a rights file here
12253:     #
12254: 	    unless ($depthcount) {
12255: 		my $location=$metaentry{':customdistributionfile'};
12256: 		my $dir=$filename;
12257: 		$dir=~s|[^/]*$||;
12258: 		$location=&filelocation($dir,$location);
12259: 		my $rights_metadata =
12260: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12261: 			      $depthcount+1);
12262: 		foreach my $rights (split(',',$rights_metadata)) {
12263: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12264: 		    $metathesekeys{$rights}=1;
12265: 		}
12266: 	    }
12267: 	}
12268: 	# uniqifiy package listing
12269: 	my %seen;
12270: 	my @uniq_packages =
12271: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12272: 	$metaentry{':packages'} = join(',',@uniq_packages);
12273: 
12274:         if (($importedresponses) || ($importedparts)) {
12275:             if ($importedparts) {
12276: # We had imported parts and need to rebuild partorder
12277:                 $metaentry{':partorder'}='';
12278:                 $metathesekeys{'partorder'}=1;
12279:             }
12280:             if ($importedresponses) {
12281: # We had imported responses and need to rebuil responseorder
12282:                 $metaentry{':responseorder'}='';
12283:                 $metathesekeys{'responseorder'}=1;
12284:             }
12285:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12286:                 my $origid = $origfiletagids[$index+1];
12287:                 if ($origfiletagids[$index] eq 'part') {
12288: # Original part, part of the problem
12289:                     if ($importedparts) {
12290:                         $metaentry{':partorder'}.=','.$origid;
12291:                     }
12292:                 } elsif ($origfiletagids[$index] eq 'import') {
12293:                     if ($importedparts) {
12294: # We have imported parts at this position
12295:                         if ($importedpartids{$origid} ne '') {
12296:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12297:                         }
12298:                     }
12299:                     if ($importedresponses) {
12300: # We have imported responses at this position
12301:                         if ($importedrespids{$origid} ne '') {
12302:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12303:                         }
12304:                     }
12305:                 } else {
12306: # Original response item, part of the problem
12307:                     if ($importedresponses) {
12308:                         $metaentry{':responseorder'}.=','.$origid;
12309:                     }
12310:                 }
12311:             }
12312:             if ($importedparts) {
12313:                 $metaentry{':partorder'}=~s/^\,//;
12314:             }
12315:             if ($importedresponses) {
12316:                 $metaentry{':responseorder'}=~s/^\,//;
12317:             }
12318:         }
12319: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12320: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12321: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12322:         unless ($liburi) {
12323: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12324:         }
12325: # this is the end of "was not already recently cached
12326:     }
12327:     return $metaentry{':'.$what};
12328: }
12329: 
12330: sub metadata_create_package_def {
12331:     my ($uri,$key,$package,$metathesekeys)=@_;
12332:     my ($pack,$name,$subp)=split(/\&/,$key);
12333:     if ($subp eq 'default') { next; }
12334:     
12335:     if (defined($metaentry{':packages'})) {
12336: 	$metaentry{':packages'}.=','.$package;
12337:     } else {
12338: 	$metaentry{':packages'}=$package;
12339:     }
12340:     my $value=$packagetab{$key};
12341:     my $unikey;
12342:     $unikey='parameter_0_'.$name;
12343:     $metaentry{':'.$unikey.'.part'}=0;
12344:     $$metathesekeys{$unikey}=1;
12345:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12346: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12347:     }
12348:     if (defined($metaentry{':'.$unikey.'.default'})) {
12349: 	$metaentry{':'.$unikey}=
12350: 	    $metaentry{':'.$unikey.'.default'};
12351:     }
12352: }
12353: 
12354: sub metadata_generate_part0 {
12355:     my ($metadata,$metacache,$uri) = @_;
12356:     my %allnames;
12357:     foreach my $metakey (keys(%$metadata)) {
12358: 	if ($metakey=~/^parameter\_(.*)/) {
12359: 	  my $part=$$metacache{':'.$metakey.'.part'};
12360: 	  my $name=$$metacache{':'.$metakey.'.name'};
12361: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12362: 	    $allnames{$name}=$part;
12363: 	  }
12364: 	}
12365:     }
12366:     foreach my $name (keys(%allnames)) {
12367:       $$metadata{"parameter_0_$name"}=1;
12368:       my $key=":parameter_0_$name";
12369:       $$metacache{"$key.part"}='0';
12370:       $$metacache{"$key.name"}=$name;
12371:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12372: 					   $allnames{$name}.'_'.$name.
12373: 					   '.type'};
12374:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12375: 			     '.display'};
12376:       my $expr='[Part: '.$allnames{$name}.']';
12377:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12378:       $$metacache{"$key.display"}=$olddis;
12379:     }
12380: }
12381: 
12382: # ------------------------------------------------------ Devalidate title cache
12383: 
12384: sub devalidate_title_cache {
12385:     my ($url)=@_;
12386:     if (!$env{'request.course.id'}) { return; }
12387:     my $symb=&symbread($url);
12388:     if (!$symb) { return; }
12389:     my $key=$env{'request.course.id'}."\0".$symb;
12390:     &devalidate_cache_new('title',$key);
12391: }
12392: 
12393: # ------------------------------------------------- Get the title of a course
12394: 
12395: sub current_course_title {
12396:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12397: }
12398: # ------------------------------------------------- Get the title of a resource
12399: 
12400: sub gettitle {
12401:     my $urlsymb=shift;
12402:     my $symb=&symbread($urlsymb);
12403:     if ($symb) {
12404: 	my $key=$env{'request.course.id'}."\0".$symb;
12405: 	my ($result,$cached)=&is_cached_new('title',$key);
12406: 	if (defined($cached)) { 
12407: 	    return $result;
12408: 	}
12409: 	my ($map,$resid,$url)=&decode_symb($symb);
12410: 	my $title='';
12411: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12412: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12413: 	} else {
12414: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12415: 		    &GDBM_READER(),0640)) {
12416: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12417: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12418: 		untie(%bighash);
12419: 	    }
12420: 	}
12421: 	$title=~s/\&colon\;/\:/gs;
12422: 	if ($title) {
12423: # Remember both $symb and $title for dynamic metadata
12424:             $accesshash{$symb.'___crstitle'}=$title;
12425:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12426: # Cache this title and then return it
12427: 	    return &do_cache_new('title',$key,$title,600);
12428: 	}
12429: 	$urlsymb=$url;
12430:     }
12431:     my $title=&metadata($urlsymb,'title');
12432:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12433:     return $title;
12434: }
12435: 
12436: sub get_slot {
12437:     my ($which,$cnum,$cdom)=@_;
12438:     if (!$cnum || !$cdom) {
12439: 	(undef,my $courseid)=&whichuser();
12440: 	$cdom=$env{'course.'.$courseid.'.domain'};
12441: 	$cnum=$env{'course.'.$courseid.'.num'};
12442:     }
12443:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12444:     my %slotinfo;
12445:     if (exists($remembered{$key})) {
12446: 	$slotinfo{$which} = $remembered{$key};
12447:     } else {
12448: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12449: 	&Apache::lonhomework::showhash(%slotinfo);
12450: 	my ($tmp)=keys(%slotinfo);
12451: 	if ($tmp=~/^error:/) { return (); }
12452: 	$remembered{$key} = $slotinfo{$which};
12453:     }
12454:     if (ref($slotinfo{$which}) eq 'HASH') {
12455: 	return %{$slotinfo{$which}};
12456:     }
12457:     return $slotinfo{$which};
12458: }
12459: 
12460: sub get_reservable_slots {
12461:     my ($cnum,$cdom,$uname,$udom) = @_;
12462:     my $now = time;
12463:     my $reservable_info;
12464:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12465:     if (exists($remembered{$key})) {
12466:         $reservable_info = $remembered{$key};
12467:     } else {
12468:         my %resv;
12469:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12470:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12471:         $reservable_info = \%resv;
12472:         $remembered{$key} = $reservable_info;
12473:     }
12474:     return $reservable_info;
12475: }
12476: 
12477: sub get_course_slots {
12478:     my ($cnum,$cdom) = @_;
12479:     my $hashid=$cnum.':'.$cdom;
12480:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12481:     if (defined($cached)) {
12482:         if (ref($result) eq 'HASH') {
12483:             return %{$result};
12484:         }
12485:     } else {
12486:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12487:         my ($tmp) = keys(%slots);
12488:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12489:             &do_cache_new('allslots',$hashid,\%slots,600);
12490:             return %slots;
12491:         }
12492:     }
12493:     return;
12494: }
12495: 
12496: sub devalidate_slots_cache {
12497:     my ($cnum,$cdom)=@_;
12498:     my $hashid=$cnum.':'.$cdom;
12499:     &devalidate_cache_new('allslots',$hashid);
12500: }
12501: 
12502: sub get_coursechange {
12503:     my ($cdom,$cnum) = @_;
12504:     if ($cdom eq '' || $cnum eq '') {
12505:         return unless ($env{'request.course.id'});
12506:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12507:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12508:     }
12509:     my $hashid=$cdom.'_'.$cnum;
12510:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12511:     if ((defined($cached)) && ($change ne '')) {
12512:         return $change;
12513:     } else {
12514:         my %crshash;
12515:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12516:         if ($crshash{'internal.contentchange'} eq '') {
12517:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12518:             if ($change eq '') {
12519:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12520:                 $change = $crshash{'internal.created'};
12521:             }
12522:         } else {
12523:             $change = $crshash{'internal.contentchange'};
12524:         }
12525:         my $cachetime = 600;
12526:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12527:     }
12528:     return $change;
12529: }
12530: 
12531: sub devalidate_coursechange_cache {
12532:     my ($cnum,$cdom)=@_;
12533:     my $hashid=$cnum.':'.$cdom;
12534:     &devalidate_cache_new('crschange',$hashid);
12535: }
12536: 
12537: # ------------------------------------------------- Update symbolic store links
12538: 
12539: sub symblist {
12540:     my ($mapname,%newhash)=@_;
12541:     $mapname=&deversion(&declutter($mapname));
12542:     my %hash;
12543:     if (($env{'request.course.fn'}) && (%newhash)) {
12544:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12545:                       &GDBM_WRCREAT(),0640)) {
12546: 	    foreach my $url (keys(%newhash)) {
12547: 		next if ($url eq 'last_known'
12548: 			 && $env{'form.no_update_last_known'});
12549: 		$hash{declutter($url)}=&encode_symb($mapname,
12550: 						    $newhash{$url}->[1],
12551: 						    $newhash{$url}->[0]);
12552:             }
12553:             if (untie(%hash)) {
12554: 		return 'ok';
12555:             }
12556:         }
12557:     }
12558:     return 'error';
12559: }
12560: 
12561: # --------------------------------------------------------------- Verify a symb
12562: 
12563: sub symbverify {
12564:     my ($symb,$thisurl,$encstate)=@_;
12565:     my $thisfn=$thisurl;
12566:     $thisfn=&declutter($thisfn);
12567: # direct jump to resource in page or to a sequence - will construct own symbs
12568:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12569: # check URL part
12570:     my ($map,$resid,$url)=&decode_symb($symb);
12571: 
12572:     unless ($url eq $thisfn) { return 0; }
12573: 
12574:     $symb=&symbclean($symb);
12575:     $thisurl=&deversion($thisurl);
12576:     $thisfn=&deversion($thisfn);
12577: 
12578:     my %bighash;
12579:     my $okay=0;
12580: 
12581:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12582:                             &GDBM_READER(),0640)) {
12583:         my $noclutter;
12584:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12585:             $thisurl =~ s/\?.+$//;
12586:             if ($map =~ m{^uploaded/.+\.page$}) {
12587:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12588:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12589:                 $noclutter = 1;
12590:             }
12591:         }
12592:         my $ids;
12593:         if ($noclutter) {
12594:             $ids=$bighash{'ids_'.$thisurl};
12595:         } else {
12596:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12597:         }
12598:         unless ($ids) {
12599:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12600:             $ids=$bighash{$idkey};
12601:         }
12602:         if ($ids) {
12603: # ------------------------------------------------------------------- Has ID(s)
12604:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12605:                 $symb =~ s/\?.+$//;
12606:             }
12607: 	    foreach my $id (split(/\,/,$ids)) {
12608: 	       my ($mapid,$resid)=split(/\./,$id);
12609:                if (
12610:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12611:    eq $symb) {
12612:                    if (ref($encstate)) {
12613:                        $$encstate = $bighash{'encrypted_'.$id};
12614:                    }
12615: 		   if (($env{'request.role.adv'}) ||
12616: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12617:                        ($thisurl eq '/adm/navmaps')) {
12618: 		       $okay=1;
12619:                        last;
12620: 		   }
12621: 	       }
12622: 	   }
12623:         }
12624: 	untie(%bighash);
12625:     }
12626:     return $okay;
12627: }
12628: 
12629: # --------------------------------------------------------------- Clean-up symb
12630: 
12631: sub symbclean {
12632:     my $symb=shift;
12633:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12634: # remove version from map
12635:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12636: 
12637: # remove version from URL
12638:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12639: 
12640: # remove wrapper
12641: 
12642:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12643:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12644:     return $symb;
12645: }
12646: 
12647: # ---------------------------------------------- Split symb to find map and url
12648: 
12649: sub encode_symb {
12650:     my ($map,$resid,$url)=@_;
12651:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12652: }
12653: 
12654: sub decode_symb {
12655:     my $symb=shift;
12656:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12657:     my ($map,$resid,$url)=split(/___/,$symb);
12658:     return (&fixversion($map),$resid,&fixversion($url));
12659: }
12660: 
12661: sub fixversion {
12662:     my $fn=shift;
12663:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12664:     my %bighash;
12665:     my $uri=&clutter($fn);
12666:     my $key=$env{'request.course.id'}.'_'.$uri;
12667: # is this cached?
12668:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12669:     if (defined($cached)) { return $result; }
12670: # unfortunately not cached, or expired
12671:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12672: 	    &GDBM_READER(),0640)) {
12673:  	if ($bighash{'version_'.$uri}) {
12674:  	    my $version=$bighash{'version_'.$uri};
12675:  	    unless (($version eq 'mostrecent') || 
12676: 		    ($version==&getversion($uri))) {
12677:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12678:  	    }
12679:  	}
12680:  	untie %bighash;
12681:     }
12682:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12683: }
12684: 
12685: sub deversion {
12686:     my $url=shift;
12687:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12688:     return $url;
12689: }
12690: 
12691: # ------------------------------------------------------ Return symb list entry
12692: 
12693: sub symbread {
12694:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12695:     my $cache_str='request.symbread.cached.'.$thisfn;
12696:     if (defined($env{$cache_str})) {
12697:         if ($ignorecachednull) {
12698:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12699:         } else {
12700:             return $env{$cache_str};
12701:         }
12702:     }
12703: # no filename provided? try from environment
12704:     unless ($thisfn) {
12705:         if ($env{'request.symb'}) {
12706: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12707: 	}
12708: 	$thisfn=$env{'request.filename'};
12709:     }
12710:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12711: # is that filename actually a symb? Verify, clean, and return
12712:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12713: 	if (&symbverify($thisfn,$1)) {
12714: 	    return $env{$cache_str}=&symbclean($thisfn);
12715: 	}
12716:     }
12717:     $thisfn=declutter($thisfn);
12718:     my %hash;
12719:     my %bighash;
12720:     my $syval='';
12721:     if (($env{'request.course.fn'}) && ($thisfn)) {
12722:         my $targetfn = $thisfn;
12723:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12724:             $targetfn = 'adm/wrapper/'.$thisfn;
12725:         }
12726: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12727: 	    $targetfn=$1;
12728: 	}
12729:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12730:                       &GDBM_READER(),0640)) {
12731: 	    $syval=$hash{$targetfn};
12732:             untie(%hash);
12733:         }
12734: # ---------------------------------------------------------- There was an entry
12735:         if ($syval) {
12736: 	    #unless ($syval=~/\_\d+$/) {
12737: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12738: 		    #&appenv({'request.ambiguous' => $thisfn});
12739: 		    #return $env{$cache_str}='';
12740: 		#}    
12741: 		#$syval.=$1;
12742: 	    #}
12743:         } else {
12744: # ------------------------------------------------------- Was not in symb table
12745:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12746:                             &GDBM_READER(),0640)) {
12747: # ---------------------------------------------- Get ID(s) for current resource
12748:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12749:               unless ($ids) { 
12750:                  $ids=$bighash{'ids_/'.$thisfn};
12751:               }
12752:               unless ($ids) {
12753: # alias?
12754: 		  $ids=$bighash{'mapalias_'.$thisfn};
12755:               }
12756:               if ($ids) {
12757: # ------------------------------------------------------------------- Has ID(s)
12758:                  my @possibilities=split(/\,/,$ids);
12759:                  if ($#possibilities==0) {
12760: # ----------------------------------------------- There is only one possibility
12761: 		     my ($mapid,$resid)=split(/\./,$ids);
12762: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12763: 						    $resid,$thisfn);
12764:                      if (ref($possibles) eq 'HASH') {
12765:                          $possibles->{$syval} = 1;    
12766:                      }
12767:                      if ($checkforblock) {
12768:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12769:                          if (@blockers) {
12770:                              $syval = '';
12771:                              return;
12772:                          }
12773:                      }
12774:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12775: # ------------------------------------------ There is more than one possibility
12776:                      my $realpossible=0;
12777:                      foreach my $id (@possibilities) {
12778: 			 my $file=$bighash{'src_'.$id};
12779:                          my $canaccess;
12780:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12781:                              $canaccess = 1;
12782:                          } else { 
12783:                              $canaccess = &allowed('bre',$file);
12784:                          }
12785:                          if ($canaccess) {
12786:          		     my ($mapid,$resid)=split(/\./,$id);
12787:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12788:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12789: 						             $resid,$thisfn);
12790:                                  if (ref($possibles) eq 'HASH') {
12791:                                      $possibles->{$syval} = 1;
12792:                                  }
12793:                                  if ($checkforblock) {
12794:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12795:                                      unless (@blockers > 0) {
12796:                                          $syval = $poss_syval;
12797:                                          $realpossible++;
12798:                                      }
12799:                                  } else {
12800:                                      $syval = $poss_syval;
12801:                                      $realpossible++;
12802:                                  }
12803:                              }
12804: 			 }
12805:                      }
12806: 		     if ($realpossible!=1) { $syval=''; }
12807:                  } else {
12808:                      $syval='';
12809:                  }
12810: 	      }
12811:               untie(%bighash);
12812:            }
12813:         }
12814:         if ($syval) {
12815: 	    return $env{$cache_str}=$syval;
12816:         }
12817:     }
12818:     &appenv({'request.ambiguous' => $thisfn});
12819:     return $env{$cache_str}='';
12820: }
12821: 
12822: # ---------------------------------------------------------- Return random seed
12823: 
12824: sub numval {
12825:     my $txt=shift;
12826:     $txt=~tr/A-J/0-9/;
12827:     $txt=~tr/a-j/0-9/;
12828:     $txt=~tr/K-T/0-9/;
12829:     $txt=~tr/k-t/0-9/;
12830:     $txt=~tr/U-Z/0-5/;
12831:     $txt=~tr/u-z/0-5/;
12832:     $txt=~s/\D//g;
12833:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12834:     return int($txt);
12835: }
12836: 
12837: sub numval2 {
12838:     my $txt=shift;
12839:     $txt=~tr/A-J/0-9/;
12840:     $txt=~tr/a-j/0-9/;
12841:     $txt=~tr/K-T/0-9/;
12842:     $txt=~tr/k-t/0-9/;
12843:     $txt=~tr/U-Z/0-5/;
12844:     $txt=~tr/u-z/0-5/;
12845:     $txt=~s/\D//g;
12846:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12847:     my $total;
12848:     foreach my $val (@txts) { $total+=$val; }
12849:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12850:     return int($total);
12851: }
12852: 
12853: sub numval3 {
12854:     use integer;
12855:     my $txt=shift;
12856:     $txt=~tr/A-J/0-9/;
12857:     $txt=~tr/a-j/0-9/;
12858:     $txt=~tr/K-T/0-9/;
12859:     $txt=~tr/k-t/0-9/;
12860:     $txt=~tr/U-Z/0-5/;
12861:     $txt=~tr/u-z/0-5/;
12862:     $txt=~s/\D//g;
12863:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12864:     my $total;
12865:     foreach my $val (@txts) { $total+=$val; }
12866:     if ($_64bit) { $total=(($total<<32)>>32); }
12867:     return $total;
12868: }
12869: 
12870: sub digest {
12871:     my ($data)=@_;
12872:     my $digest=&Digest::MD5::md5($data);
12873:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12874:     my ($e,$f);
12875:     {
12876:         use integer;
12877:         $e=($a+$b);
12878:         $f=($c+$d);
12879:         if ($_64bit) {
12880:             $e=(($e<<32)>>32);
12881:             $f=(($f<<32)>>32);
12882:         }
12883:     }
12884:     if (wantarray) {
12885: 	return ($e,$f);
12886:     } else {
12887: 	my $g;
12888: 	{
12889: 	    use integer;
12890: 	    $g=($e+$f);
12891: 	    if ($_64bit) {
12892: 		$g=(($g<<32)>>32);
12893: 	    }
12894: 	}
12895: 	return $g;
12896:     }
12897: }
12898: 
12899: sub latest_rnd_algorithm_id {
12900:     return '64bit5';
12901: }
12902: 
12903: sub get_rand_alg {
12904:     my ($courseid)=@_;
12905:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12906:     if ($courseid) {
12907: 	return $env{"course.$courseid.rndseed"};
12908:     }
12909:     return &latest_rnd_algorithm_id();
12910: }
12911: 
12912: sub validCODE {
12913:     my ($CODE)=@_;
12914:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12915:     return 0;
12916: }
12917: 
12918: sub getCODE {
12919:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12920:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12921: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12922: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12923: 	return $Apache::lonhomework::history{'resource.CODE'};
12924:     }
12925:     return undef;
12926: }
12927: #
12928: #  Determines the random seed for a specific context:
12929: #
12930: # parameters:
12931: #   symb      - in course context the symb for the seed.
12932: #   course_id - The course id of the form domain_coursenum.
12933: #   domain    - Domain for the user.
12934: #   course    - Course for the user.
12935: #   cenv      - environment of the course.
12936: #
12937: # NOTE:
12938: #   All parameters are picked out of the environment if missing
12939: #   or not defined.
12940: #   If a symb cannot be determined the current time is used instead.
12941: #
12942: #  For a given well defined symb, courside, domain, username,
12943: #  and course environment, the seed is reproducible.
12944: #
12945: sub rndseed {
12946:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12947:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12948:     if (!defined($symb)) {
12949: 	unless ($symb=$wsymb) { return time; }
12950:     }
12951:     if (!defined $courseid) { 
12952: 	$courseid=$wcourseid; 
12953:     }
12954:     if (!defined $domain) { $domain=$wdomain; }
12955:     if (!defined $username) { $username=$wusername }
12956: 
12957:     my $which;
12958:     if (defined($cenv->{'rndseed'})) {
12959: 	$which = $cenv->{'rndseed'};
12960:     } else {
12961: 	$which =&get_rand_alg($courseid);
12962:     }
12963:     if (defined(&getCODE())) {
12964: 
12965: 	if ($which eq '64bit5') {
12966: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12967: 	} elsif ($which eq '64bit4') {
12968: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12969: 	} else {
12970: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12971: 	}
12972:     } elsif ($which eq '64bit5') {
12973: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12974:     } elsif ($which eq '64bit4') {
12975: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12976:     } elsif ($which eq '64bit3') {
12977: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12978:     } elsif ($which eq '64bit2') {
12979: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12980:     } elsif ($which eq '64bit') {
12981: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12982:     }
12983:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12984: }
12985: 
12986: sub rndseed_32bit {
12987:     my ($symb,$courseid,$domain,$username)=@_;
12988:     {
12989: 	use integer;
12990: 	my $symbchck=unpack("%32C*",$symb) << 27;
12991: 	my $symbseed=numval($symb) << 22;
12992: 	my $namechck=unpack("%32C*",$username) << 17;
12993: 	my $nameseed=numval($username) << 12;
12994: 	my $domainseed=unpack("%32C*",$domain) << 7;
12995: 	my $courseseed=unpack("%32C*",$courseid);
12996: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12997: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12998: 	#&logthis("rndseed :$num:$symb");
12999: 	if ($_64bit) { $num=(($num<<32)>>32); }
13000: 	return $num;
13001:     }
13002: }
13003: 
13004: sub rndseed_64bit {
13005:     my ($symb,$courseid,$domain,$username)=@_;
13006:     {
13007: 	use integer;
13008: 	my $symbchck=unpack("%32S*",$symb) << 21;
13009: 	my $symbseed=numval($symb) << 10;
13010: 	my $namechck=unpack("%32S*",$username);
13011: 	
13012: 	my $nameseed=numval($username) << 21;
13013: 	my $domainseed=unpack("%32S*",$domain) << 10;
13014: 	my $courseseed=unpack("%32S*",$courseid);
13015: 	
13016: 	my $num1=$symbchck+$symbseed+$namechck;
13017: 	my $num2=$nameseed+$domainseed+$courseseed;
13018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13019: 	#&logthis("rndseed :$num:$symb");
13020: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13021: 	return "$num1,$num2";
13022:     }
13023: }
13024: 
13025: sub rndseed_64bit2 {
13026:     my ($symb,$courseid,$domain,$username)=@_;
13027:     {
13028: 	use integer;
13029: 	# strings need to be an even # of cahracters long, it it is odd the
13030:         # last characters gets thrown away
13031: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13032: 	my $symbseed=numval($symb) << 10;
13033: 	my $namechck=unpack("%32S*",$username.' ');
13034: 	
13035: 	my $nameseed=numval($username) << 21;
13036: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13037: 	my $courseseed=unpack("%32S*",$courseid.' ');
13038: 	
13039: 	my $num1=$symbchck+$symbseed+$namechck;
13040: 	my $num2=$nameseed+$domainseed+$courseseed;
13041: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13042: 	#&logthis("rndseed :$num:$symb");
13043: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13044: 	return "$num1,$num2";
13045:     }
13046: }
13047: 
13048: sub rndseed_64bit3 {
13049:     my ($symb,$courseid,$domain,$username)=@_;
13050:     {
13051: 	use integer;
13052: 	# strings need to be an even # of cahracters long, it it is odd the
13053:         # last characters gets thrown away
13054: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13055: 	my $symbseed=numval2($symb) << 10;
13056: 	my $namechck=unpack("%32S*",$username.' ');
13057: 	
13058: 	my $nameseed=numval2($username) << 21;
13059: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13060: 	my $courseseed=unpack("%32S*",$courseid.' ');
13061: 	
13062: 	my $num1=$symbchck+$symbseed+$namechck;
13063: 	my $num2=$nameseed+$domainseed+$courseseed;
13064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13065: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13066: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13067: 	
13068: 	return "$num1:$num2";
13069:     }
13070: }
13071: 
13072: sub rndseed_64bit4 {
13073:     my ($symb,$courseid,$domain,$username)=@_;
13074:     {
13075: 	use integer;
13076: 	# strings need to be an even # of cahracters long, it it is odd the
13077:         # last characters gets thrown away
13078: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13079: 	my $symbseed=numval3($symb) << 10;
13080: 	my $namechck=unpack("%32S*",$username.' ');
13081: 	
13082: 	my $nameseed=numval3($username) << 21;
13083: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13084: 	my $courseseed=unpack("%32S*",$courseid.' ');
13085: 	
13086: 	my $num1=$symbchck+$symbseed+$namechck;
13087: 	my $num2=$nameseed+$domainseed+$courseseed;
13088: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13089: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13090: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13091: 	
13092: 	return "$num1:$num2";
13093:     }
13094: }
13095: 
13096: sub rndseed_64bit5 {
13097:     my ($symb,$courseid,$domain,$username)=@_;
13098:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13099:     return "$num1:$num2";
13100: }
13101: 
13102: sub rndseed_CODE_64bit {
13103:     my ($symb,$courseid,$domain,$username)=@_;
13104:     {
13105: 	use integer;
13106: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13107: 	my $symbseed=numval2($symb);
13108: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13109: 	my $CODEseed=numval(&getCODE());
13110: 	my $courseseed=unpack("%32S*",$courseid.' ');
13111: 	my $num1=$symbseed+$CODEchck;
13112: 	my $num2=$CODEseed+$courseseed+$symbchck;
13113: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13114: 	#&logthis("rndseed :$num1:$num2:$symb");
13115: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13116: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13117: 	return "$num1:$num2";
13118:     }
13119: }
13120: 
13121: sub rndseed_CODE_64bit4 {
13122:     my ($symb,$courseid,$domain,$username)=@_;
13123:     {
13124: 	use integer;
13125: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13126: 	my $symbseed=numval3($symb);
13127: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13128: 	my $CODEseed=numval3(&getCODE());
13129: 	my $courseseed=unpack("%32S*",$courseid.' ');
13130: 	my $num1=$symbseed+$CODEchck;
13131: 	my $num2=$CODEseed+$courseseed+$symbchck;
13132: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13133: 	#&logthis("rndseed :$num1:$num2:$symb");
13134: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13135: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13136: 	return "$num1:$num2";
13137:     }
13138: }
13139: 
13140: sub rndseed_CODE_64bit5 {
13141:     my ($symb,$courseid,$domain,$username)=@_;
13142:     my $code = &getCODE();
13143:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13144:     return "$num1:$num2";
13145: }
13146: 
13147: sub setup_random_from_rndseed {
13148:     my ($rndseed)=@_;
13149:     if ($rndseed =~/([,:])/) {
13150:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13151:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13152:             &Math::Random::random_set_seed_from_phrase($rndseed);
13153:         } else {
13154:             &Math::Random::random_set_seed($num1,$num2);
13155:         }
13156:     } else {
13157: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13158:     }
13159: }
13160: 
13161: sub latest_receipt_algorithm_id {
13162:     return 'receipt3';
13163: }
13164: 
13165: sub recunique {
13166:     my $fucourseid=shift;
13167:     my $unique;
13168:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13169: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13170: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13171:     } else {
13172: 	$unique=$perlvar{'lonReceipt'};
13173:     }
13174:     return unpack("%32C*",$unique);
13175: }
13176: 
13177: sub recprefix {
13178:     my $fucourseid=shift;
13179:     my $prefix;
13180:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13181: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13182: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13183:     } else {
13184: 	$prefix=$perlvar{'lonHostID'};
13185:     }
13186:     return unpack("%32C*",$prefix);
13187: }
13188: 
13189: sub ireceipt {
13190:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13191: 
13192:     my $return =&recprefix($fucourseid).'-';
13193: 
13194:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13195: 	$env{'request.state'} eq 'construct') {
13196: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13197: 	return $return;
13198:     }
13199: 
13200:     my $cuname=unpack("%32C*",$funame);
13201:     my $cudom=unpack("%32C*",$fudom);
13202:     my $cucourseid=unpack("%32C*",$fucourseid);
13203:     my $cusymb=unpack("%32C*",$fusymb);
13204:     my $cunique=&recunique($fucourseid);
13205:     my $cpart=unpack("%32S*",$part);
13206:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13207: 
13208: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13209: 			       
13210: 	$return.= ($cunique%$cuname+
13211: 		   $cunique%$cudom+
13212: 		   $cusymb%$cuname+
13213: 		   $cusymb%$cudom+
13214: 		   $cucourseid%$cuname+
13215: 		   $cucourseid%$cudom+
13216: 		   $cpart%$cuname+
13217: 		   $cpart%$cudom);
13218:     } else {
13219: 	$return.= ($cunique%$cuname+
13220: 		   $cunique%$cudom+
13221: 		   $cusymb%$cuname+
13222: 		   $cusymb%$cudom+
13223: 		   $cucourseid%$cuname+
13224: 		   $cucourseid%$cudom);
13225:     }
13226:     return $return;
13227: }
13228: 
13229: sub receipt {
13230:     my ($part)=@_;
13231:     my ($symb,$courseid,$domain,$name) = &whichuser();
13232:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13233: }
13234: 
13235: sub whichuser {
13236:     my ($passedsymb)=@_;
13237:     my ($symb,$courseid,$domain,$name,$publicuser);
13238:     if (defined($env{'form.grade_symb'})) {
13239: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13240: 	my $allowed=&allowed('vgr',$tmp_courseid);
13241: 	if (!$allowed &&
13242: 	    exists($env{'request.course.sec'}) &&
13243: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13244: 	    $allowed=&allowed('vgr',$tmp_courseid.
13245: 			      '/'.$env{'request.course.sec'});
13246: 	}
13247: 	if ($allowed) {
13248: 	    ($symb)=&get_env_multiple('form.grade_symb');
13249: 	    $courseid=$tmp_courseid;
13250: 	    ($domain)=&get_env_multiple('form.grade_domain');
13251: 	    ($name)=&get_env_multiple('form.grade_username');
13252: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13253: 	}
13254:     }
13255:     if (!$passedsymb) {
13256: 	$symb=&symbread();
13257:     } else {
13258: 	$symb=$passedsymb;
13259:     }
13260:     $courseid=$env{'request.course.id'};
13261:     $domain=$env{'user.domain'};
13262:     $name=$env{'user.name'};
13263:     if ($name eq 'public' && $domain eq 'public') {
13264: 	if (!defined($env{'form.username'})) {
13265: 	    $env{'form.username'}.=time.rand(10000000);
13266: 	}
13267: 	$name.=$env{'form.username'};
13268:     }
13269:     return ($symb,$courseid,$domain,$name,$publicuser);
13270: 
13271: }
13272: 
13273: # ------------------------------------------------------------ Serves up a file
13274: # returns either the contents of the file or 
13275: # -1 if the file doesn't exist
13276: #
13277: # if the target is a file that was uploaded via DOCS, 
13278: # a check will be made to see if a current copy exists on the local server,
13279: # if it does this will be served, otherwise a copy will be retrieved from
13280: # the home server for the course and stored in /home/httpd/html/userfiles on
13281: # the local server.   
13282: 
13283: sub getfile {
13284:     my ($file) = @_;
13285:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13286:     &repcopy($file);
13287:     return &readfile($file);
13288: }
13289: 
13290: sub repcopy_userfile {
13291:     my ($file)=@_;
13292:     my $londocroot = $perlvar{'lonDocRoot'};
13293:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13294:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13295:     my ($cdom,$cnum,$filename) = 
13296: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13297:     my $uri="/uploaded/$cdom/$cnum/$filename";
13298:     if (-e "$file") {
13299: # we already have a local copy, check it out
13300: 	my @fileinfo = stat($file);
13301: 	my $rtncode;
13302: 	my $info;
13303: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13304: 	if ($lwpresp ne 'ok') {
13305: # there is no such file anymore, even though we had a local copy
13306: 	    if ($rtncode eq '404') {
13307: 		unlink($file);
13308: 	    }
13309: 	    return -1;
13310: 	}
13311: 	if ($info < $fileinfo[9]) {
13312: # nice, the file we have is up-to-date, just say okay
13313: 	    return 'ok';
13314: 	} else {
13315: # the file is outdated, get rid of it
13316: 	    unlink($file);
13317: 	}
13318:     }
13319: # one way or the other, at this point, we don't have the file
13320: # construct the correct path for the file
13321:     my @parts = ($cdom,$cnum); 
13322:     if ($filename =~ m|^(.+)/[^/]+$|) {
13323: 	push @parts, split(/\//,$1);
13324:     }
13325:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13326:     foreach my $part (@parts) {
13327: 	$path .= '/'.$part;
13328: 	if (!-e $path) {
13329: 	    mkdir($path,0770);
13330: 	}
13331:     }
13332: # now the path exists for sure
13333: # get a user agent
13334:     my $transferfile=$file.'.in.transfer';
13335: # FIXME: this should flock
13336:     if (-e $transferfile) { return 'ok'; }
13337:     my $request;
13338:     $uri=~s/^\///;
13339:     my $homeserver = &homeserver($cnum,$cdom);
13340:     my $protocol = $protocol{$homeserver};
13341:     $protocol = 'http' if ($protocol ne 'https');
13342:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13343:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13344: # did it work?
13345:     if ($response->is_error()) {
13346: 	unlink($transferfile);
13347: 	&logthis("Userfile repcopy failed for $uri");
13348: 	return -1;
13349:     }
13350: # worked, rename the transfer file
13351:     rename($transferfile,$file);
13352:     return 'ok';
13353: }
13354: 
13355: sub tokenwrapper {
13356:     my $uri=shift;
13357:     $uri=~s|^https?\://([^/]+)||;
13358:     $uri=~s|^/||;
13359:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13360:     my $token=$1;
13361:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13362:     if ($udom && $uname && $file) {
13363: 	$file=~s|(\?\.*)*$||;
13364:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13365:         my $homeserver = &homeserver($uname,$udom);
13366:         my $protocol = $protocol{$homeserver};
13367:         $protocol = 'http' if ($protocol ne 'https');
13368:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13369:                (($uri=~/\?/)?'&':'?').'token='.$token.
13370:                                '&tokenissued='.$perlvar{'lonHostID'};
13371:     } else {
13372:         return '/adm/notfound.html';
13373:     }
13374: }
13375: 
13376: # call with reqtype HEAD: get last modification time
13377: # call with reqtype GET: get the file contents
13378: # Do not call this with reqtype GET for large files! It loads everything into memory
13379: #
13380: sub getuploaded {
13381:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13382:     $uri=~s/^\///;
13383:     my $homeserver = &homeserver($cnum,$cdom);
13384:     my $protocol = $protocol{$homeserver};
13385:     $protocol = 'http' if ($protocol ne 'https');
13386:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13387:     my $request=new HTTP::Request($reqtype,$uri);
13388:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13389:     $$rtncode = $response->code;
13390:     if (! $response->is_success()) {
13391: 	return 'failed';
13392:     }      
13393:     if ($reqtype eq 'HEAD') {
13394: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13395:     } elsif ($reqtype eq 'GET') {
13396: 	$$info = $response->content;
13397:     }
13398:     return 'ok';
13399: }
13400: 
13401: sub readfile {
13402:     my $file = shift;
13403:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13404:     my $fh;
13405:     open($fh,"<",$file);
13406:     my $a='';
13407:     while (my $line = <$fh>) { $a .= $line; }
13408:     return $a;
13409: }
13410: 
13411: sub filelocation {
13412:     my ($dir,$file) = @_;
13413:     my $location;
13414:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13415: 
13416:     if ($file =~ m-^/adm/-) {
13417: 	$file=~s-^/adm/wrapper/-/-;
13418: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13419:     }
13420: 
13421:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13422:         $location = $file;
13423:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13424:         my ($udom,$uname,$filename)=
13425:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13426:         my $home=&homeserver($uname,$udom);
13427:         my $is_me=0;
13428:         my @ids=&current_machine_ids();
13429:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13430:         if ($is_me) {
13431:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13432:         } else {
13433:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13434:   	      $udom.'/'.$uname.'/'.$filename;
13435:         }
13436:     } elsif ($file =~ m-^/adm/-) {
13437: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13438:     } else {
13439:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13440:         $file=~s:^/(res|priv)/:/:;
13441:         my $space=$1;
13442:         if ( !( $file =~ m:^/:) ) {
13443:             $location = $dir. '/'.$file;
13444:         } else {
13445:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13446:         }
13447:     }
13448:     $location=~s://+:/:g; # remove duplicate /
13449:     while ($location=~m{/\.\./}) {
13450: 	if ($location =~ m{/[^/]+/\.\./}) {
13451: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13452: 	} else {
13453: 	    $location=~ s{/\.\./}{/}g;
13454: 	}
13455:     } #remove dir/..
13456:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13457:     return $location;
13458: }
13459: 
13460: sub hreflocation {
13461:     my ($dir,$file)=@_;
13462:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13463: 	$file=filelocation($dir,$file);
13464:     } elsif ($file=~m-^/adm/-) {
13465: 	$file=~s-^/adm/wrapper/-/-;
13466: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13467:     }
13468:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13469: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13470:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13471: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13472: 	        {/uploaded/$1/$2/}x;
13473:     }
13474:     if ($file=~ m{^/userfiles/}) {
13475: 	$file =~ s{^/userfiles/}{/uploaded/};
13476:     }
13477:     return $file;
13478: }
13479: 
13480: 
13481: 
13482: 
13483: 
13484: sub current_machine_domains {
13485:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13486: }
13487: 
13488: sub machine_domains {
13489:     my ($hostname) = @_;
13490:     my @domains;
13491:     my %hostname = &all_hostnames();
13492:     while( my($id, $name) = each(%hostname)) {
13493: #	&logthis("-$id-$name-$hostname-");
13494: 	if ($hostname eq $name) {
13495: 	    push(@domains,&host_domain($id));
13496: 	}
13497:     }
13498:     return @domains;
13499: }
13500: 
13501: sub current_machine_ids {
13502:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13503: }
13504: 
13505: sub machine_ids {
13506:     my ($hostname) = @_;
13507:     $hostname ||= &hostname($perlvar{'lonHostID'});
13508:     my @ids;
13509:     my %name_to_host = &all_names();
13510:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13511: 	return @{ $name_to_host{$hostname} };
13512:     }
13513:     return;
13514: }
13515: 
13516: sub additional_machine_domains {
13517:     my @domains;
13518:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13519:     while( my $line = <$fh>) {
13520:         $line =~ s/\s//g;
13521:         push(@domains,$line);
13522:     }
13523:     return @domains;
13524: }
13525: 
13526: sub default_login_domain {
13527:     my $domain = $perlvar{'lonDefDomain'};
13528:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13529:     foreach my $posdom (&current_machine_domains(),
13530:                         &additional_machine_domains()) {
13531:         if (lc($posdom) eq lc($testdomain)) {
13532:             $domain=$posdom;
13533:             last;
13534:         }
13535:     }
13536:     return $domain;
13537: }
13538: 
13539: # ------------------------------------------------------------- Declutters URLs
13540: 
13541: sub declutter {
13542:     my $thisfn=shift;
13543:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13544:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13545:         $thisfn=~s{^/home/httpd/html}{};
13546:     }
13547:     $thisfn=~s/^\///;
13548:     $thisfn=~s|^adm/wrapper/||;
13549:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13550:     $thisfn=~s/^res\///;
13551:     $thisfn=~s/^priv\///;
13552:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13553:         $thisfn=~s/\?.+$//;
13554:     }
13555:     return $thisfn;
13556: }
13557: 
13558: # ------------------------------------------------------------- Clutter up URLs
13559: 
13560: sub clutter {
13561:     my $thisfn='/'.&declutter(shift);
13562:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13563: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13564:        $thisfn='/res'.$thisfn; 
13565:     }
13566:     if ($thisfn !~m|^/adm|) {
13567: 	if ($thisfn =~ m|^/ext/|) {
13568: 	    $thisfn='/adm/wrapper'.$thisfn;
13569: 	} else {
13570: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13571: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13572: 	    if ($embstyle eq 'ssi'
13573: 		|| ($embstyle eq 'hdn')
13574: 		|| ($embstyle eq 'rat')
13575: 		|| ($embstyle eq 'prv')
13576: 		|| ($embstyle eq 'ign')) {
13577: 		#do nothing with these
13578: 	    } elsif (($embstyle eq 'img') 
13579: 		|| ($embstyle eq 'emb')
13580: 		|| ($embstyle eq 'wrp')) {
13581: 		$thisfn='/adm/wrapper'.$thisfn;
13582: 	    } elsif ($embstyle eq 'unk'
13583: 		     && $thisfn!~/\.(sequence|page)$/) {
13584: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13585: 	    } else {
13586: #		&logthis("Got a blank emb style");
13587: 	    }
13588: 	}
13589:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13590:         $thisfn='/adm/wrapper'.$thisfn;
13591:     }
13592:     return $thisfn;
13593: }
13594: 
13595: sub clutter_with_no_wrapper {
13596:     my $uri = &clutter(shift);
13597:     if ($uri =~ m-^/adm/-) {
13598: 	$uri =~ s-^/adm/wrapper/-/-;
13599: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13600:     }
13601:     return $uri;
13602: }
13603: 
13604: sub freeze_escape {
13605:     my ($value)=@_;
13606:     if (ref($value)) {
13607: 	$value=&nfreeze($value);
13608: 	return '__FROZEN__'.&escape($value);
13609:     }
13610:     return &escape($value);
13611: }
13612: 
13613: 
13614: sub thaw_unescape {
13615:     my ($value)=@_;
13616:     if ($value =~ /^__FROZEN__/) {
13617: 	substr($value,0,10,undef);
13618: 	$value=&unescape($value);
13619: 	return &thaw($value);
13620:     }
13621:     return &unescape($value);
13622: }
13623: 
13624: sub correct_line_ends {
13625:     my ($result)=@_;
13626:     $$result =~s/\r\n/\n/mg;
13627:     $$result =~s/\r/\n/mg;
13628: }
13629: # ================================================================ Main Program
13630: 
13631: sub goodbye {
13632:    &logthis("Starting Shut down");
13633: #not converted to using infrastruture and probably shouldn't be
13634:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13635: #converted
13636: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13637:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13638: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13639: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13640: #1.1 only
13641: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13642: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13643: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13644: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13645:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13646:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13647:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13648:    &flushcourselogs();
13649:    &logthis("Shutting down");
13650: }
13651: 
13652: sub get_dns {
13653:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13654:     if (!$ignore_cache) {
13655: 	my ($content,$cached)=
13656: 	    &Apache::lonnet::is_cached_new('dns',$url);
13657: 	if ($cached) {
13658: 	    &$func($content,$hashref);
13659: 	    return;
13660: 	}
13661:     }
13662: 
13663:     my %alldns;
13664:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13665:         foreach my $dns (<$config>) {
13666: 	    next if ($dns !~ /^\^(\S*)/x);
13667:             my $line = $1;
13668:             my ($host,$protocol) = split(/:/,$line);
13669:             if ($protocol ne 'https') {
13670:                 $protocol = 'http';
13671:             }
13672: 	    $alldns{$host} = $protocol;
13673:         }
13674:         close($config);
13675:     }
13676:     while (%alldns) {
13677: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13678: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13679:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13680:         delete($alldns{$dns});
13681: 	next if ($response->is_error());
13682:         if ($url eq '/adm/dns/loncapaCRL') {
13683:             return &$func($response);
13684:         } else {
13685: 	    my @content = split("\n",$response->content);
13686: 	    unless ($nocache) {
13687: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13688: 	    }
13689: 	    &$func(\@content,$hashref);
13690:             return;
13691:         }
13692:     }
13693:     my $which = (split('/',$url,4))[3];
13694:     if ($which eq 'loncapaCRL') {
13695:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13696:         if (-e $diskfile) {
13697:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13698:         } else {
13699:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13700:         }
13701:     } else {
13702:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13703:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13704:             my @content = <$config>;
13705:             close($config);
13706:             &$func(\@content,$hashref);
13707:         }
13708:     }
13709:     return;
13710: }
13711: 
13712: # ------------------------------------------------------Get DNS checksums file
13713: sub parse_dns_checksums_tab {
13714:     my ($lines,$hashref) = @_;
13715:     my $lonhost = $perlvar{'lonHostID'};
13716:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13717:     my $loncaparev = &get_server_loncaparev($machine_dom);
13718:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13719:     my $webconfdir = '/etc/httpd/conf';
13720:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13721:         $webconfdir = '/etc/apache2';
13722:     } elsif ($distro =~ /^sles(\d+)$/) {
13723:         if ($1 >= 10) {
13724:             $webconfdir = '/etc/apache2';
13725:         }
13726:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13727:         if ($1 >= 10.0) {
13728:             $webconfdir = '/etc/apache2';
13729:         }
13730:     }
13731:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13732:     my (%chksum,%revnum);
13733:     if (ref($lines) eq 'ARRAY') {
13734:         chomp(@{$lines});
13735:         my $version = shift(@{$lines});
13736:         if ($version eq $release) {  
13737:             foreach my $line (@{$lines}) {
13738:                 my ($file,$version,$shasum) = split(/,/,$line);
13739:                 if ($file =~ m{^/etc/httpd/conf}) {
13740:                     if ($webconfdir eq '/etc/apache2') {
13741:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13742:                     }
13743:                 }
13744:                 $chksum{$file} = $shasum;
13745:                 $revnum{$file} = $version;
13746:             }
13747:             if (ref($hashref) eq 'HASH') {
13748:                 %{$hashref} = (
13749:                                 sums     => \%chksum,
13750:                                 versions => \%revnum,
13751:                               );
13752:             }
13753:         }
13754:     }
13755:     return;
13756: }
13757: 
13758: sub fetch_dns_checksums {
13759:     my %checksums;
13760:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13761:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13762:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13763:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13764:              \%checksums);
13765:     return \%checksums;
13766: }
13767: 
13768: sub fetch_crl_pemfile {
13769:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13770: }
13771: 
13772: sub save_crl_pem {
13773:     my ($response) = @_;
13774:     my ($msg,$hadchanges);
13775:     if (ref($response)) {
13776:         my $now = time;
13777:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13778:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13779:         if (open(my $fh,'>',"$tmpcrl")) {
13780:             print $fh $response->content;
13781:             close($fh);
13782:             if (-e $lonca) {
13783:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13784:                     my $check = <PIPE>;
13785:                     close(PIPE);
13786:                     chomp($check);
13787:                     if ($check eq 'verify OK') {
13788:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13789:                         my $backup;
13790:                         if (-e $dest) {
13791:                             if (&File::Copy::move($dest,"$dest.bak")) {
13792:                                 $backup = 'ok';
13793:                             }
13794:                         }
13795:                         if (&File::Copy::move($tmpcrl,$dest)) {
13796:                             $msg = 'ok';
13797:                             if ($backup) {
13798:                                 my (%oldnums,%newnums);
13799:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13800:                                     while (<PIPE>) {
13801:                                         $oldnums{(split(/:/))[1]} = 1;
13802:                                     }
13803:                                     close(PIPE);
13804:                                 }
13805:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13806:                                     while(<PIPE>) {
13807:                                         $newnums{(split(/:/))[1]} = 1;
13808:                                     }
13809:                                     close(PIPE);
13810:                                 }
13811:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13812:                                     unless (exists($oldnums{$key})) {
13813:                                         $hadchanges = 1;
13814:                                         last;
13815:                                     }
13816:                                 }
13817:                                 unless ($hadchanges) {
13818:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13819:                                         unless (exists($newnums{$key})) {
13820:                                             $hadchanges = 1;
13821:                                             last;
13822:                                         }
13823:                                     }
13824:                                 }
13825:                             }
13826:                         }
13827:                     } else {
13828:                         unlink($tmpcrl);
13829:                     }
13830:                 } else {
13831:                     unlink($tmpcrl);
13832:                 }
13833:             } else {
13834:                 unlink($tmpcrl);
13835:             }
13836:         }
13837:     }
13838:     return ($msg,$hadchanges);
13839: }
13840: 
13841: # ------------------------------------------------------------ Read domain file
13842: {
13843:     my $loaded;
13844:     my %domain;
13845: 
13846:     sub parse_domain_tab {
13847: 	my ($lines) = @_;
13848: 	foreach my $line (@$lines) {
13849: 	    next if ($line =~ /^(\#|\s*$ )/x);
13850: 
13851: 	    chomp($line);
13852: 	    my ($name,@elements) = split(/:/,$line,9);
13853: 	    my %this_domain;
13854: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13855: 			       'lang_def', 'city', 'longi', 'lati',
13856: 			       'primary') {
13857: 		$this_domain{$field} = shift(@elements);
13858: 	    }
13859: 	    $domain{$name} = \%this_domain;
13860: 	}
13861:     }
13862: 
13863:     sub reset_domain_info {
13864: 	undef($loaded);
13865: 	undef(%domain);
13866:     }
13867: 
13868:     sub load_domain_tab {
13869: 	my ($ignore_cache,$nocache) = @_;
13870: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13871: 	my $fh;
13872: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13873: 	    my @lines = <$fh>;
13874: 	    &parse_domain_tab(\@lines);
13875: 	}
13876: 	close($fh);
13877: 	$loaded = 1;
13878:     }
13879: 
13880:     sub domain {
13881: 	&load_domain_tab() if (!$loaded);
13882: 
13883: 	my ($name,$what) = @_;
13884: 	return if ( !exists($domain{$name}) );
13885: 
13886: 	if (!$what) {
13887: 	    return $domain{$name}{'description'};
13888: 	}
13889: 	return $domain{$name}{$what};
13890:     }
13891: 
13892:     sub domain_info {
13893:         &load_domain_tab() if (!$loaded);
13894:         return %domain;
13895:     }
13896: 
13897: }
13898: 
13899: 
13900: # ------------------------------------------------------------- Read hosts file
13901: {
13902:     my %hostname;
13903:     my %hostdom;
13904:     my %libserv;
13905:     my $loaded;
13906:     my %name_to_host;
13907:     my %internetdom;
13908:     my %LC_dns_serv;
13909: 
13910:     sub parse_hosts_tab {
13911: 	my ($file) = @_;
13912: 	foreach my $configline (@$file) {
13913: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13914:             chomp($configline);
13915: 	    if ($configline =~ /^\^/) {
13916:                 if ($configline =~ /^\^([\w.\-]+)/) {
13917:                     $LC_dns_serv{$1} = 1;
13918:                 }
13919:                 next;
13920:             }
13921: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13922: 	    $name=~s/\s//g;
13923: 	    if ($id && $domain && $role && $name) {
13924:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13925:                     my $curr = $hostname{$id};
13926:                     my $skip;
13927:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13928:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13929:                             $skip = 1;
13930:                         } else {
13931:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13932:                         }
13933:                     }
13934:                     unless ($skip) {
13935:                         push(@{$name_to_host{$name}},$id);
13936:                     }
13937:                 } else {
13938:                     push(@{$name_to_host{$name}},$id);
13939:                 }
13940: 		$hostname{$id}=$name;
13941: 		$hostdom{$id}=$domain;
13942: 		if ($role eq 'library') { $libserv{$id}=$name; }
13943:                 if (defined($protocol)) {
13944:                     if ($protocol eq 'https') {
13945:                         $protocol{$id} = $protocol;
13946:                     } else {
13947:                         $protocol{$id} = 'http'; 
13948:                     }
13949:                 } else {
13950:                     $protocol{$id} = 'http';
13951:                 }
13952:                 if (defined($intdom)) {
13953:                     $internetdom{$id} = $intdom;
13954:                 }
13955: 	    }
13956: 	}
13957:     }
13958:     
13959:     sub reset_hosts_info {
13960: 	&purge_remembered();
13961: 	&reset_domain_info();
13962: 	&reset_hosts_ip_info();
13963:         undef(%internetdom);
13964: 	undef(%name_to_host);
13965: 	undef(%hostname);
13966: 	undef(%hostdom);
13967: 	undef(%libserv);
13968: 	undef($loaded);
13969:     }
13970: 
13971:     sub load_hosts_tab {
13972: 	my ($ignore_cache,$nocache) = @_;
13973: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13974: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13975: 	my @config = <$config>;
13976: 	&parse_hosts_tab(\@config);
13977: 	close($config);
13978: 	$loaded=1;
13979:     }
13980: 
13981:     sub hostname {
13982: 	&load_hosts_tab() if (!$loaded);
13983: 
13984: 	my ($lonid) = @_;
13985: 	return $hostname{$lonid};
13986:     }
13987: 
13988:     sub all_hostnames {
13989: 	&load_hosts_tab() if (!$loaded);
13990: 
13991: 	return %hostname;
13992:     }
13993: 
13994:     sub all_names {
13995:         my ($ignore_cache,$nocache) = @_;
13996: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13997: 
13998: 	return %name_to_host;
13999:     }
14000: 
14001:     sub all_host_domain {
14002:         &load_hosts_tab() if (!$loaded);
14003:         return %hostdom;
14004:     }
14005: 
14006:     sub all_host_intdom {
14007:         &load_hosts_tab() if (!$loaded);
14008:         return %internetdom;
14009:     }
14010: 
14011:     sub is_library {
14012: 	&load_hosts_tab() if (!$loaded);
14013: 
14014: 	return exists($libserv{$_[0]});
14015:     }
14016: 
14017:     sub all_library {
14018: 	&load_hosts_tab() if (!$loaded);
14019: 
14020: 	return %libserv;
14021:     }
14022: 
14023:     sub unique_library {
14024: 	#2x reverse removes all hostnames that appear more than once
14025:         my %unique = reverse &all_library();
14026:         return reverse %unique;
14027:     }
14028: 
14029:     sub get_servers {
14030: 	&load_hosts_tab() if (!$loaded);
14031: 
14032: 	my ($domain,$type) = @_;
14033: 	my %possible_hosts = ($type eq 'library') ? %libserv
14034: 	                                          : %hostname;
14035: 	my %result;
14036: 	if (ref($domain) eq 'ARRAY') {
14037: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14038: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14039: 		    $result{$host} = $hostname;
14040: 		}
14041: 	    }
14042: 	} else {
14043: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14044: 		if ($hostdom{$host} eq $domain) {
14045: 		    $result{$host} = $hostname;
14046: 		}
14047: 	    }
14048: 	}
14049: 	return %result;
14050:     }
14051: 
14052:     sub get_unique_servers {
14053:         my %unique = reverse &get_servers(@_);
14054: 	return reverse %unique;
14055:     }
14056: 
14057:     sub host_domain {
14058: 	&load_hosts_tab() if (!$loaded);
14059: 
14060: 	my ($lonid) = @_;
14061: 	return $hostdom{$lonid};
14062:     }
14063: 
14064:     sub all_domains {
14065: 	&load_hosts_tab() if (!$loaded);
14066: 
14067: 	my %seen;
14068: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14069: 	return @uniq;
14070:     }
14071: 
14072:     sub internet_dom {
14073:         &load_hosts_tab() if (!$loaded);
14074: 
14075:         my ($lonid) = @_;
14076:         return $internetdom{$lonid};
14077:     }
14078: 
14079:     sub is_LC_dns {
14080:         &load_hosts_tab() if (!$loaded);
14081: 
14082:         my ($hostname) = @_;
14083:         return exists($LC_dns_serv{$hostname});
14084:     }
14085: 
14086: }
14087: 
14088: { 
14089:     my %iphost;
14090:     my %name_to_ip;
14091:     my %lonid_to_ip;
14092: 
14093:     sub get_hosts_from_ip {
14094: 	my ($ip) = @_;
14095: 	my %iphosts = &get_iphost();
14096: 	if (ref($iphosts{$ip})) {
14097: 	    return @{$iphosts{$ip}};
14098: 	}
14099: 	return;
14100:     }
14101:     
14102:     sub reset_hosts_ip_info {
14103: 	undef(%iphost);
14104: 	undef(%name_to_ip);
14105: 	undef(%lonid_to_ip);
14106:     }
14107: 
14108:     sub get_host_ip {
14109: 	my ($lonid) = @_;
14110: 	if (exists($lonid_to_ip{$lonid})) {
14111: 	    return $lonid_to_ip{$lonid};
14112: 	}
14113: 	my $name=&hostname($lonid);
14114:    	my $ip = gethostbyname($name);
14115: 	return if (!$ip || length($ip) ne 4);
14116: 	$ip=inet_ntoa($ip);
14117: 	$name_to_ip{$name}   = $ip;
14118: 	$lonid_to_ip{$lonid} = $ip;
14119: 	return $ip;
14120:     }
14121:     
14122:     sub get_iphost {
14123: 	my ($ignore_cache,$nocache) = @_;
14124: 
14125: 	if (!$ignore_cache) {
14126: 	    if (%iphost) {
14127: 		return %iphost;
14128: 	    }
14129: 	    my ($ip_info,$cached)=
14130: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14131: 	    if ($cached) {
14132: 		%iphost      = %{$ip_info->[0]};
14133: 		%name_to_ip  = %{$ip_info->[1]};
14134: 		%lonid_to_ip = %{$ip_info->[2]};
14135: 		return %iphost;
14136: 	    }
14137: 	}
14138: 
14139: 	# get yesterday's info for fallback
14140: 	my %old_name_to_ip;
14141: 	my ($ip_info,$cached)=
14142: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14143: 	if ($cached) {
14144: 	    %old_name_to_ip = %{$ip_info->[1]};
14145: 	}
14146: 
14147: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14148: 	foreach my $name (keys(%name_to_host)) {
14149: 	    my $ip;
14150: 	    if (!exists($name_to_ip{$name})) {
14151: 		$ip = gethostbyname($name);
14152: 		if (!$ip || length($ip) ne 4) {
14153: 		    if (defined($old_name_to_ip{$name})) {
14154: 			$ip = $old_name_to_ip{$name};
14155: 			&logthis("Can't find $name defaulting to old $ip");
14156: 		    } else {
14157: 			&logthis("Name $name no IP found");
14158: 			next;
14159: 		    }
14160: 		} else {
14161: 		    $ip=inet_ntoa($ip);
14162: 		}
14163: 		$name_to_ip{$name} = $ip;
14164: 	    } else {
14165: 		$ip = $name_to_ip{$name};
14166: 	    }
14167: 	    foreach my $id (@{ $name_to_host{$name} }) {
14168: 		$lonid_to_ip{$id} = $ip;
14169: 	    }
14170: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14171: 	}
14172:         unless ($nocache) {
14173: 	    &do_cache_new('iphost','iphost',
14174: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14175: 		          48*60*60);
14176:         }
14177: 
14178: 	return %iphost;
14179:     }
14180: 
14181:     #
14182:     #  Given a DNS returns the loncapa host name for that DNS 
14183:     # 
14184:     sub host_from_dns {
14185:         my ($dns) = @_;
14186:         my @hosts;
14187:         my $ip;
14188: 
14189:         if (exists($name_to_ip{$dns})) {
14190:             $ip = $name_to_ip{$dns};
14191:         }
14192:         if (!$ip) {
14193:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14194:             if (length($ip) == 4) { 
14195: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14196:             }
14197:         }
14198:         if ($ip) {
14199: 	    @hosts = get_hosts_from_ip($ip);
14200: 	    return $hosts[0];
14201:         }
14202:         return undef;
14203:     }
14204: 
14205:     sub get_internet_names {
14206:         my ($lonid) = @_;
14207:         return if ($lonid eq '');
14208:         my ($idnref,$cached)=
14209:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14210:         if ($cached) {
14211:             return $idnref;
14212:         }
14213:         my $ip = &get_host_ip($lonid);
14214:         my @hosts = &get_hosts_from_ip($ip);
14215:         my %iphost = &get_iphost();
14216:         my (@idns,%seen);
14217:         foreach my $id (@hosts) {
14218:             my $dom = &host_domain($id);
14219:             my $prim_id = &domain($dom,'primary');
14220:             my $prim_ip = &get_host_ip($prim_id);
14221:             next if ($seen{$prim_ip});
14222:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14223:                 foreach my $id (@{$iphost{$prim_ip}}) {
14224:                     my $intdom = &internet_dom($id);
14225:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14226:                         push(@idns,$intdom);
14227:                     }
14228:                 }
14229:             }
14230:             $seen{$prim_ip} = 1;
14231:         }
14232:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14233:     }
14234: 
14235: }
14236: 
14237: sub all_loncaparevs {
14238:     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 2.11);
14239: }
14240: 
14241: # ---------------------------------------------------------- Read loncaparev table
14242: {
14243:     sub load_loncaparevs { 
14244:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14245:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14246:                 while (my $configline=<$config>) {
14247:                     chomp($configline);
14248:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14249:                     $loncaparevs{$hostid}=$loncaparev;
14250:                 }
14251:                 close($config);
14252:             }
14253:         }
14254:     }
14255: }
14256: 
14257: # ---------------------------------------------------------- Read serverhostID table
14258: {
14259:     sub load_serverhomeIDs {
14260:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14261:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14262:                 while (my $configline=<$config>) {
14263:                     chomp($configline);
14264:                     my ($name,$id)=split(/:/,$configline);
14265:                     $serverhomeIDs{$name}=$id;
14266:                 }
14267:                 close($config);
14268:             }
14269:         }
14270:     }
14271: }
14272: 
14273: 
14274: BEGIN {
14275: 
14276: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14277:     unless ($readit) {
14278: {
14279:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14280:     %perlvar = (%perlvar,%{$configvars});
14281: }
14282: 
14283: 
14284: # ------------------------------------------------------ Read spare server file
14285: {
14286:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14287: 
14288:     while (my $configline=<$config>) {
14289:        chomp($configline);
14290:        if ($configline) {
14291: 	   my ($host,$type) = split(':',$configline,2);
14292: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14293: 	   push(@{ $spareid{$type} }, $host);
14294:        }
14295:     }
14296:     close($config);
14297: }
14298: # ------------------------------------------------------------ Read permissions
14299: {
14300:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14301: 
14302:     while (my $configline=<$config>) {
14303: 	chomp($configline);
14304: 	if ($configline) {
14305: 	    my ($role,$perm)=split(/ /,$configline);
14306: 	    if ($perm ne '') { $pr{$role}=$perm; }
14307: 	}
14308:     }
14309:     close($config);
14310: }
14311: 
14312: # -------------------------------------------- Read plain texts for permissions
14313: {
14314:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14315: 
14316:     while (my $configline=<$config>) {
14317: 	chomp($configline);
14318: 	if ($configline) {
14319: 	    my ($short,@plain)=split(/:/,$configline);
14320:             %{$prp{$short}} = ();
14321: 	    if (@plain > 0) {
14322:                 $prp{$short}{'std'} = $plain[0];
14323:                 for (my $i=1; $i<@plain; $i++) {
14324:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14325:                 }
14326:             }
14327: 	}
14328:     }
14329:     close($config);
14330: }
14331: 
14332: # ---------------------------------------------------------- Read package table
14333: {
14334:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14335: 
14336:     while (my $configline=<$config>) {
14337: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14338: 	chomp($configline);
14339: 	my ($short,$plain)=split(/:/,$configline);
14340: 	my ($pack,$name)=split(/\&/,$short);
14341: 	if ($plain ne '') {
14342: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14343: 	    $packagetab{$short}=$plain; 
14344: 	}
14345:     }
14346:     close($config);
14347: }
14348: 
14349: # ---------------------------------------------------------- Read loncaparev table
14350: 
14351: &load_loncaparevs();
14352: 
14353: # ---------------------------------------------------------- Read serverhostID table
14354: 
14355: &load_serverhomeIDs();
14356: 
14357: # ---------------------------------------------------------- Read releaseslist XML
14358: {
14359:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14360:     if (-e $file) {
14361:         my $parser = HTML::LCParser->new($file);
14362:         while (my $token = $parser->get_token()) {
14363:             if ($token->[0] eq 'S') {
14364:                 my $item = $token->[1];
14365:                 my $name = $token->[2]{'name'};
14366:                 my $value = $token->[2]{'value'};
14367:                 my $valuematch = $token->[2]{'valuematch'};
14368:                 my $namematch = $token->[2]{'namematch'};
14369:                 if ($item eq 'parameter') {
14370:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14371:                         my $release = $parser->get_text();
14372:                         $release =~ s/(^\s*|\s*$ )//gx;
14373:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14374:                     }
14375:                 } elsif ($item ne '' && $name ne '') {
14376:                     my $release = $parser->get_text();
14377:                     $release =~ s/(^\s*|\s*$ )//gx;
14378:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14379:                 }
14380:             }
14381:         }
14382:     }
14383: }
14384: 
14385: # ---------------------------------------------------------- Read managers table
14386: {
14387:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14388:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14389:             while (my $configline=<$config>) {
14390:                 chomp($configline);
14391:                 next if ($configline =~ /^\#/);
14392:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14393:                     $managerstab{$configline} = 1;
14394:                 }
14395:             }
14396:             close($config);
14397:         }
14398:     }
14399: }
14400: 
14401: # ------------- set up temporary directory
14402: {
14403:     $tmpdir = LONCAPA::tempdir();
14404: 
14405: }
14406: 
14407: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14408: 				'compress_threshold'=> 20_000,
14409:  			        });
14410: 
14411: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14412: $dumpcount=0;
14413: $locknum=0;
14414: 
14415: &logtouch();
14416: &logthis('<font color="yellow">INFO: Read configuration</font>');
14417: $readit=1;
14418:     {
14419: 	use integer;
14420: 	my $test=(2**32)+1;
14421: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14422: 	&logthis(" Detected 64bit platform ($_64bit)");
14423:     }
14424: }
14425: }
14426: 
14427: 1;
14428: __END__
14429: 
14430: =pod
14431: 
14432: =head1 NAME
14433: 
14434: Apache::lonnet - Subroutines to ask questions about things in the network.
14435: 
14436: =head1 SYNOPSIS
14437: 
14438: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14439: 
14440:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14441: 
14442: Common parameters:
14443: 
14444: =over 4
14445: 
14446: =item *
14447: 
14448: $uname : an internal username (if $cname expecting a course Id specifically)
14449: 
14450: =item *
14451: 
14452: $udom : a domain (if $cdom expecting a course's domain specifically)
14453: 
14454: =item *
14455: 
14456: $symb : a resource instance identifier
14457: 
14458: =item *
14459: 
14460: $namespace : the name of a .db file that contains the data needed or
14461: being set.
14462: 
14463: =back
14464: 
14465: =head1 OVERVIEW
14466: 
14467: lonnet provides subroutines which interact with the
14468: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14469: about classes, users, and resources.
14470: 
14471: For many of these objects you can also use this to store data about
14472: them or modify them in various ways.
14473: 
14474: =head2 Symbs
14475: 
14476: To identify a specific instance of a resource, LON-CAPA uses symbols
14477: or "symbs"X<symb>. These identifiers are built from the URL of the
14478: map, the resource number of the resource in the map, and the URL of
14479: the resource itself. The latter is somewhat redundant, but might help
14480: if maps change.
14481: 
14482: An example is
14483: 
14484:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14485: 
14486: The respective map entry is
14487: 
14488:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14489:   title="Problem 2">
14490:  </resource>
14491: 
14492: Symbs are used by the random number generator, as well as to store and
14493: restore data specific to a certain instance of for example a problem.
14494: 
14495: =head2 Storing And Retrieving Data
14496: 
14497: X<store()>X<cstore()>X<restore()>Three of the most important functions
14498: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14499: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14500: is is the non-critical message twin of cstore. These functions are for
14501: handlers to store a perl hash to a user's permanent data space in an
14502: easy manner, and to retrieve it again on another call. It is expected
14503: that a handler would use this once at the beginning to retrieve data,
14504: and then again once at the end to send only the new data back.
14505: 
14506: The data is stored in the user's data directory on the user's
14507: homeserver under the ID of the course.
14508: 
14509: The hash that is returned by restore will have all of the previous
14510: value for all of the elements of the hash.
14511: 
14512: Example:
14513: 
14514:  #creating a hash
14515:  my %hash;
14516:  $hash{'foo'}='bar';
14517: 
14518:  #storing it
14519:  &Apache::lonnet::cstore(\%hash);
14520: 
14521:  #changing a value
14522:  $hash{'foo'}='notbar';
14523: 
14524:  #adding a new value
14525:  $hash{'bar'}='foo';
14526:  &Apache::lonnet::cstore(\%hash);
14527: 
14528:  #retrieving the hash
14529:  my %history=&Apache::lonnet::restore();
14530: 
14531:  #print the hash
14532:  foreach my $key (sort(keys(%history))) {
14533:    print("\%history{$key} = $history{$key}");
14534:  }
14535: 
14536: Will print out:
14537: 
14538:  %history{1:foo} = bar
14539:  %history{1:keys} = foo:timestamp
14540:  %history{1:timestamp} = 990455579
14541:  %history{2:bar} = foo
14542:  %history{2:foo} = notbar
14543:  %history{2:keys} = foo:bar:timestamp
14544:  %history{2:timestamp} = 990455580
14545:  %history{bar} = foo
14546:  %history{foo} = notbar
14547:  %history{timestamp} = 990455580
14548:  %history{version} = 2
14549: 
14550: Note that the special hash entries C<keys>, C<version> and
14551: C<timestamp> were added to the hash. C<version> will be equal to the
14552: total number of versions of the data that have been stored. The
14553: C<timestamp> attribute will be the UNIX time the hash was
14554: stored. C<keys> is available in every historical section to list which
14555: keys were added or changed at a specific historical revision of a
14556: hash.
14557: 
14558: B<Warning>: do not store the hash that restore returns directly. This
14559: will cause a mess since it will restore the historical keys as if the
14560: were new keys. I.E. 1:foo will become 1:1:foo etc.
14561: 
14562: Calling convention:
14563: 
14564:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14565:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14566: 
14567: For more detailed information, see lonnet specific documentation.
14568: 
14569: =head1 RETURN MESSAGES
14570: 
14571: =over 4
14572: 
14573: =item * B<con_lost>: unable to contact remote host
14574: 
14575: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14576: when the connection is brought back up
14577: 
14578: =item * B<con_failed>: unable to contact remote host and unable to save message
14579: for later delivery
14580: 
14581: =item * B<error:>: an error a occurred, a description of the error follows the :
14582: 
14583: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14584: that was requested
14585: 
14586: =back
14587: 
14588: =head1 PUBLIC SUBROUTINES
14589: 
14590: =head2 Session Environment Functions
14591: 
14592: =over 4
14593: 
14594: =item * 
14595: X<appenv()>
14596: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14597: the user envirnoment file, and will be restored for each access this
14598: user makes during this session, also modifies the %env for the current
14599: process. Optional rolesarrayref - if defined contains a reference to an array
14600: of roles which are exempt from the restriction on modifying user.role entries 
14601: in the user's environment.db and in %env.    
14602: 
14603: =item *
14604: X<delenv()>
14605: B<delenv($delthis,$regexp)>: removes all items from the session
14606: environment file that begin with $delthis. If the 
14607: optional second arg - $regexp - is true, $delthis is treated as a 
14608: regular expression, otherwise \Q$delthis\E is used. 
14609: The values are also deleted from the current processes %env.
14610: 
14611: =item * get_env_multiple($name) 
14612: 
14613: gets $name from the %env hash, it seemlessly handles the cases where multiple
14614: values may be defined and end up as an array ref.
14615: 
14616: returns an array of values
14617: 
14618: =back
14619: 
14620: =head2 User Information
14621: 
14622: =over 4
14623: 
14624: =item *
14625: X<queryauthenticate()>
14626: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14627: authentication scheme
14628: 
14629: =item *
14630: X<authenticate()>
14631: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14632: authenticate user from domain's lib servers (first use the current
14633: one). C<$upass> should be the users password.
14634: $checkdefauth is optional (value is 1 if a check should be made to
14635:    authenticate user using default authentication method, and allow
14636:    account creation if username does not have account in the domain).
14637: $clientcancheckhost is optional (value is 1 if checking whether the
14638:    server can host will occur on the client side in lonauth.pm).   
14639: 
14640: =item *
14641: X<homeserver()>
14642: B<homeserver($uname,$udom)>: find the server which has
14643: the user's directory and files (there must be only one), this caches
14644: the answer, and also caches if there is a borken connection.
14645: 
14646: =item *
14647: X<idget()>
14648: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14649: a list of student/employee IDs or clicker IDs
14650: (student/employee IDs are a unique resource in a domain, there must be 
14651: only 1 ID per username, and only 1 username per ID in a specific domain).
14652: clickerIDs are not necessarily unique, as students might share clickers.
14653: (returns hash: id=>name,id=>name)
14654: 
14655: =item *
14656: X<idrget()>
14657: B<idrget($udom,@unames)>: find the IDs behind a list of
14658: usernames (returns hash: name=>id,name=>id)
14659: 
14660: =item *
14661: X<idput()>
14662: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14663: names and associated student/employee IDs or clicker IDs.
14664: 
14665: =item *
14666: X<iddel()>
14667: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14668: student/employee ID or clicker ID username look-ups from domain.
14669: The homeserver ($uhome) and namespace ($namespace) are optional.
14670: If no $uhome is provided, it will be determined usig &homeserver()
14671: for each user.  If no $namespace is provided, the default is ids.
14672: 
14673: =item *
14674: X<updateclickers()>
14675: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14676: clicker ID-to-username look-ups in clickers.db on library server.
14677: Permitted actions are add or del (i.e., add or delete). The 
14678: clickers.db contains clickerID as keys (escaped), and each corresponding
14679: value is an escaped comma-separated list of usernames (for whom the
14680: library server is the homeserver), who registered that particular ID.
14681: If $critical is true, the update will be sent via &critical, otherwise
14682: &reply() will be used.
14683: 
14684: =item *
14685: X<rolesinit()>
14686: B<rolesinit($udom,$username)>: get user privileges.
14687: returns user role, first access and timer interval hashes
14688: 
14689: =item *
14690: X<privileged()>
14691: B<privileged($username,$domain)>: returns a true if user has a
14692: privileged and active role (i.e. su or dc), false otherwise.
14693: 
14694: =item *
14695: X<getsection()>
14696: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14697: course $cname, return section name/number or '' for "not in course"
14698: and '-1' for "no section"
14699: 
14700: =item *
14701: X<userenvironment()>
14702: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14703: passed in @what from the requested user's environment, returns a hash
14704: 
14705: =item * 
14706: X<userlog_query()>
14707: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14708: activity.log file. %filters defines filters applied when parsing the
14709: log file. These can be start or end timestamps, or the type of action
14710: - log to look for Login or Logout events, check for Checkin or
14711: Checkout, role for role selection. The response is in the form
14712: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14713: escaped strings of the action recorded in the activity.log file.
14714: 
14715: =back
14716: 
14717: =head2 User Roles
14718: 
14719: =over 4
14720: 
14721: =item *
14722: 
14723: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14724: returns codes for allowed actions.
14725: 
14726: The first argument is required, all others are optional.
14727: 
14728: $priv is the privilege being checked.
14729: $uri contains additional information about what is being checked for access (e.g.,
14730: URL, course ID etc.). 
14731: $symb is the unique resource instance identifier in a course; if needed,
14732: but not provided, it will be retrieved via a call to &symbread(). 
14733: $role is the role for which a priv is being checked (only used if priv is evb). 
14734: $clientip is the user's IP address (only used when checking for access to portfolio 
14735: files).
14736: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14737: prevents recursive calls to &allowed.
14738: 
14739:  F: full access
14740:  U,I,K: authentication modes (cxx only)
14741:  '': forbidden
14742:  1: user needs to choose course
14743:  2: browse allowed
14744:  A: passphrase authentication needed
14745:  B: access temporarily blocked because of a blocking event in a course.
14746: 
14747: =item *
14748: 
14749: constructaccess($url,$setpriv) : check for access to construction space URL
14750: 
14751: See if the owner domain and name in the URL match those in the
14752: expected environment.  If so, return three element list
14753: ($ownername,$ownerdomain,$ownerhome).
14754: 
14755: Otherwise return the null string.
14756: 
14757: If second argument 'setpriv' is true, it assigns the privileges,
14758: and returns the same three element list, unless the owner has
14759: blocked "ad hoc" Domain Coordinator access to the Author Space,
14760: in which case the null string is returned.
14761: 
14762: =item *
14763: 
14764: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14765: define a custom role rolename set privileges in format of lonTabs/roles.tab
14766: for system, domain, and course level. $uname and $udom are optional (current
14767: user's username and domain will be used when either of $uname or $udom are absent.
14768: 
14769: =item *
14770: 
14771: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14772: (rolesplain.tab); plain text explanation of a user role term.
14773: $type is Course (default) or Community.
14774: If $forcedefault evaluates to true, text returned will be default 
14775: text for $type. Otherwise, if this is a course, the text returned 
14776: will be a custom name for the role (if defined in the course's 
14777: environment).  If no custom name is defined the default is returned.
14778:    
14779: =item *
14780: 
14781: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14782: All arguments are optional. Returns a hash of a roles, either for
14783: co-author/assistant author roles for a user's Construction Space
14784: (default), or if $context is 'userroles', roles for the user himself,
14785: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14786: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14787: For each key, value is set to colon-separated start and end times for
14788: the role.  If no username and domain are specified, will default to
14789: current user/domain. Types, roles, and roledoms are references to arrays
14790: of role statuses (active, future or previous), roles 
14791: (e.g., cc,in, st etc.) and domains of the roles which can be used
14792: to restrict the list of roles reported. If no array ref is 
14793: provided for types, will default to return only active roles.
14794: 
14795: =item *
14796: 
14797: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14798: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14799: 
14800: Additional optional arguments are: $type (if role checking is to be restricted 
14801: to certain user status types -- previous (expired roles), active (currently
14802: available roles) or future (roles available in the future), and
14803: $hideprivileged -- if true will not report course roles for users who
14804: have active Domain Coordinator role in course's domain or in additional
14805: domains (specified in 'Domains to check for privileged users' in course
14806: environment -- set via:  Course Settings -> Classlists and staff listing).
14807: 
14808: =item *
14809: 
14810: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14811: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14812: $possdomains and $possroles are optional array refs -- to domains to check and
14813: roles to check.  If $possdomains is not specified, a dump will be done of the
14814: users' roles.db to check for a dc or su role in any domain. This can be
14815: time consuming if &privileged is called repeatedly (e.g., when displaying a
14816: classlist), so in such cases, supplying a $possdomains array is preferred, as
14817: this then allows &privileged_by_domain() to be used, which caches the identity
14818: of privileged users, eliminating the need for repeated calls to &dump().
14819: 
14820: =item *
14821: 
14822: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14823: where the outer hash keys are domains specified in the $possdomains array ref,
14824: next inner hash keys are privileged roles specified in the $roles array ref,
14825: and the innermost hash contains key = value pairs for username:domain = end:start
14826: for active or future "privileged" users with that role in that domain. To avoid
14827: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14828: innerhash are cached using priv_$role and $dom as the identifiers.
14829: 
14830: =back
14831: 
14832: =head2 User Modification
14833: 
14834: =over 4
14835: 
14836: =item *
14837: 
14838: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14839: user for the level given by URL.  Optional start and end dates (leave empty
14840: string or zero for "no date")
14841: 
14842: =item *
14843: 
14844: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14845: change a users, password, possible return values are: ok,
14846: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14847: refused
14848: 
14849: =item *
14850: 
14851: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14852: 
14853: =item *
14854: 
14855: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14856:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14857: 
14858: will update user information (firstname,middlename,lastname,generation,
14859: permanentemail), and if forceid is true, student/employee ID also.
14860: A user's institutional affiliation(s) can also be updated.
14861: User information fields will not be overwritten with empty entries 
14862: unless the field is included in the $candelete array reference.
14863: This array is included when a single user is modified via "Manage Users",
14864: or when Autoupdate.pl is run by cron in a domain.
14865: 
14866: =item *
14867: 
14868: modifystudent
14869: 
14870: modify a student's enrollment and identification information.
14871: The course id is resolved based on the current user's environment.  
14872: This means the invoking user must be a course coordinator or otherwise
14873: associated with a course.
14874: 
14875: This call is essentially a wrapper for lonnet::modifyuser and
14876: lonnet::modify_student_enrollment
14877: 
14878: Inputs: 
14879: 
14880: =over 4
14881: 
14882: =item B<$udom> Student's loncapa domain
14883: 
14884: =item B<$uname> Student's loncapa login name
14885: 
14886: =item B<$uid> Student/Employee ID
14887: 
14888: =item B<$umode> Student's authentication mode
14889: 
14890: =item B<$upass> Student's password
14891: 
14892: =item B<$first> Student's first name
14893: 
14894: =item B<$middle> Student's middle name
14895: 
14896: =item B<$last> Student's last name
14897: 
14898: =item B<$gene> Student's generation
14899: 
14900: =item B<$usec> Student's section in course
14901: 
14902: =item B<$end> Unix time of the roles expiration
14903: 
14904: =item B<$start> Unix time of the roles start date
14905: 
14906: =item B<$forceid> If defined, allow $uid to be changed
14907: 
14908: =item B<$desiredhome> server to use as home server for student
14909: 
14910: =item B<$email> Student's permanent e-mail address
14911: 
14912: =item B<$type> Type of enrollment (auto or manual)
14913: 
14914: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14915: 
14916: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14917: 
14918: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14919: 
14920: =item B<$context> role change context (shown in User Management Logs display in a course)
14921: 
14922: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14923: 
14924: =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.
14925: 
14926: =back
14927: 
14928: =item *
14929: 
14930: modify_student_enrollment
14931: 
14932: Change a student's enrollment status in a class.  The environment variable
14933: 'role.request.course' must be defined for this function to proceed.
14934: 
14935: Inputs:
14936: 
14937: =over 4
14938: 
14939: =item $udom, student's domain
14940: 
14941: =item $uname, student's name
14942: 
14943: =item $uid, student's user id
14944: 
14945: =item $first, student's first name
14946: 
14947: =item $middle
14948: 
14949: =item $last
14950: 
14951: =item $gene
14952: 
14953: =item $usec
14954: 
14955: =item $end
14956: 
14957: =item $start
14958: 
14959: =item $type
14960: 
14961: =item $locktype
14962: 
14963: =item $cid
14964: 
14965: =item $selfenroll
14966: 
14967: =item $context
14968: 
14969: =item $credits, number of credits student will earn from this class
14970: 
14971: =item $instsec, institutional course section code for student
14972: 
14973: =back
14974: 
14975: 
14976: =item *
14977: 
14978: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14979: custom role; give a custom role to a user for the level given by URL.  Specify
14980: name and domain of role author, and role name
14981: 
14982: =item *
14983: 
14984: revokerole($udom,$uname,$url,$role) : revoke a role for url
14985: 
14986: =item *
14987: 
14988: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14989: 
14990: =back
14991: 
14992: =head2 Course Infomation
14993: 
14994: =over 4
14995: 
14996: =item *
14997: 
14998: coursedescription($courseid,$options) : returns a hash of information about the
14999: specified course id, including all environment settings for the
15000: course, the description of the course will be in the hash under the
15001: key 'description'
15002: 
15003: $options is an optional parameter that if supplied is a hash reference that controls
15004: what how this function works.  It has the following key/values:
15005: 
15006: =over 4
15007: 
15008: =item freshen_cache
15009: 
15010: If defined, and the environment cache for the course is valid, it is 
15011: returned in the returned hash.
15012: 
15013: =item one_time
15014: 
15015: If defined, the last cache time is set to _now_
15016: 
15017: =item user
15018: 
15019: If defined, the supplied username is used instead of the current user.
15020: 
15021: 
15022: =back
15023: 
15024: =item *
15025: 
15026: resdata($name,$domain,$type,@which) : request for current parameter
15027: setting for a specific $type, where $type is either 'course' or 'user',
15028: @what should be a list of parameters to ask about. This routine caches
15029: answers for 10 minutes.
15030: 
15031: =item *
15032: 
15033: get_courseresdata($courseid, $domain) : dump the entire course resource
15034: data base, returning a hash that is keyed by the resource name and has
15035: values that are the resource value.  I believe that the timestamps and
15036: versions are also returned.
15037: 
15038: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15039: supplemental content area. This routine caches the number of files for 
15040: 10 minutes.
15041: 
15042: =back
15043: 
15044: =head2 Course Modification
15045: 
15046: =over 4
15047: 
15048: =item *
15049: 
15050: writecoursepref($courseid,%prefs) : write preferences (environment
15051: database) for a course
15052: 
15053: =item *
15054: 
15055: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15056: 
15057: =item *
15058: 
15059: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15060: 
15061: =item *
15062: 
15063: is_course($courseid), is_course($cdom, $cnum)
15064: 
15065: Accepts either a combined $courseid (in the form of domain_courseid) or the
15066: two component version $cdom, $cnum. It checks if the specified course exists.
15067: 
15068: Returns:
15069:     undef if the course doesn't exist, otherwise
15070:     in scalar context the combined courseid.
15071:     in list context the two components of the course identifier, domain and 
15072:     courseid.    
15073: 
15074: =back
15075: 
15076: =head2 Resource Subroutines
15077: 
15078: =over 4
15079: 
15080: =item *
15081: 
15082: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15083: 
15084: =item *
15085: 
15086: repcopy($filename) : subscribes to the requested file, and attempts to
15087: replicate from the owning library server, Might return
15088: 'unavailable', 'not_found', 'forbidden', 'ok', or
15089: 'bad_request', also attempts to grab the metadata for the
15090: resource. Expects the local filesystem pathname
15091: (/home/httpd/html/res/....)
15092: 
15093: =back
15094: 
15095: =head2 Resource Information
15096: 
15097: =over 4
15098: 
15099: =item *
15100: 
15101: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15102: and returns the value of a variety of different possible values,
15103: $varname should be a request string, and the other parameters can be
15104: used to specify who and what one is asking about. Ordinarily, $cid 
15105: does not need to be specified, as it is retrived from 
15106: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15107: within lonuserstate::loadmap() when initializing a course, before
15108: $env{'request.course.id'} has been set, so it needs to be provided
15109: in that one case.
15110: 
15111: Possible values for $varname are environment.lastname (or other item
15112: from the envirnment hash), user.name (or someother aspect about the
15113: user), resource.0.maxtries (or some other part and parameter of a
15114: resource)
15115: 
15116: =item *
15117: 
15118: directcondval($number) : get current value of a condition; reads from a state
15119: string
15120: 
15121: =item *
15122: 
15123: condval($condidx) : value of condition index based on state
15124: 
15125: =item *
15126: 
15127: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15128: resource's metadata, $what should be either a specific key, or either
15129: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15130: packages that this resource currently uses, the last 3 arguments are 
15131: only used internally for recursive metadata.
15132: 
15133: the toolsymb is only used where the uri is for an external tool (for which
15134: the uri as well as the symb are guaranteed to be unique).
15135: 
15136: this function automatically caches all requests except any made recursively
15137: to retrieve a list of metadata keys for an imported library file ($liburi is 
15138: defined).
15139: 
15140: =item *
15141: 
15142: metadata_query($query,$custom,$customshow) : make a metadata query against the
15143: network of library servers; returns file handle of where SQL and regex results
15144: will be stored for query
15145: 
15146: =item *
15147: 
15148: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15149: return symbolic list entry (all arguments optional). 
15150: 
15151: Args: filename is the filename (including path) for the file for which a symb 
15152: is required; donotrecurse, if true will prevent calls to allowed() being made 
15153: to check access status if more than one resource was found in the bighash 
15154: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15155: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15156: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15157: cause possible symbs to be checked to determine if they are subject to content
15158: blocking, if so they will not be included as possible symbs; possibles is a
15159: ref to a hash, which, as a side effect, will be populated with all possible 
15160: symbs (content blocking not tested).
15161:  
15162: returns the data handle
15163: 
15164: =item *
15165: 
15166: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15167: and is a possible symb for the URL in $thisfn, and if is an encrypted
15168: resource that the user accessed using /enc/ returns a 1 on success, 0
15169: on failure, user must be in a course, as it assumes the existence of
15170: the course initial hash, and uses $env('request.course.id'}.  The third
15171: arg is an optional reference to a scalar.  If this arg is passed in the 
15172: call to symbverify, it will be set to 1 if the symb has been set to be 
15173: encrypted; otherwise it will be null.  
15174: 
15175: =item *
15176: 
15177: symbclean($symb) : removes versions numbers from a symb, returns the
15178: cleaned symb
15179: 
15180: =item *
15181: 
15182: is_on_map($uri) : checks if the $uri is somewhere on the current
15183: course map, user must be in a course for it to work.
15184: 
15185: =item *
15186: 
15187: numval($salt) : return random seed value (addend for rndseed)
15188: 
15189: =item *
15190: 
15191: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15192: a random seed, all arguments are optional, if they aren't sent it uses the
15193: environment to derive them. Note: if symb isn't sent and it can't get one
15194: from &symbread it will use the current time as its return value
15195: 
15196: =item *
15197: 
15198: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15199: unfakeable, receipt
15200: 
15201: =item *
15202: 
15203: receipt() : API to ireceipt working off of env values; given out to users
15204: 
15205: =item *
15206: 
15207: countacc($url) : count the number of accesses to a given URL
15208: 
15209: =item *
15210: 
15211: 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
15212: 
15213: =item *
15214: 
15215: 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)
15216: 
15217: =item *
15218: 
15219: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15220: 
15221: =item *
15222: 
15223: devalidate($symb) : devalidate temporary spreadsheet calculations,
15224: forcing spreadsheet to reevaluate the resource scores next time.
15225: 
15226: =item * 
15227: 
15228: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15229: when viewing in course context.
15230: 
15231:  input: six args -- filename (decluttered), course number, course domain,
15232:                     url, symb (if registered) and group (if this is a 
15233:                     group item -- e.g., bulletin board, group page etc.).
15234: 
15235:  output: array of five scalars --
15236:          $cfile -- url for file editing if editable on current server
15237:          $home -- homeserver of resource (i.e., for author if published,
15238:                                           or course if uploaded.).
15239:          $switchserver --  1 if server switch will be needed.
15240:          $forceedit -- 1 if icon/link should be to go to edit mode 
15241:          $forceview -- 1 if icon/link should be to go to view mode
15242: 
15243: =item *
15244: 
15245: is_course_upload($file,$cnum,$cdom)
15246: 
15247: Used in course context to determine if current file was uploaded to 
15248: the course (i.e., would be found in /userfiles/docs on the course's 
15249: homeserver.
15250: 
15251:   input: 3 args -- filename (decluttered), course number and course domain.
15252:   output: boolean -- 1 if file was uploaded.
15253: 
15254: =back
15255: 
15256: =head2 Storing/Retreiving Data
15257: 
15258: =over 4
15259: 
15260: =item *
15261: 
15262: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15263: permanently for this url; hashref needs to be given and should be a \%hashname;
15264: the remaining args aren't required and if they aren't passed or are '' they will
15265: be derived from the env (with the exception of $laststore, which is an 
15266: optional arg used when a user's submission is stored in grading).
15267: $laststore is $version=$timestamp, where $version is the most recent version
15268: number retrieved for the corresponding $symb in the $namespace db file, and
15269: $timestamp is the timestamp for that transaction (UNIX time).
15270: $laststore is currently only passed when cstore() is called by 
15271: structuretags::finalize_storage().
15272: 
15273: =item *
15274: 
15275: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15276: but uses critical subroutine
15277: 
15278: =item *
15279: 
15280: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15281: all args are optional
15282: 
15283: =item *
15284: 
15285: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15286: dumps the complete (or key matching regexp) namespace into a hash
15287: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15288: normally &store()ed into
15289: 
15290: $range should be either an integer '100' (give me the first 100
15291:                                            matching records)
15292:               or be  two integers sperated by a - with no spaces
15293:                  '30-50' (give me the 30th through the 50th matching
15294:                           records)
15295: 
15296: 
15297: =item *
15298: 
15299: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15300: replaces a &store() version of data with a replacement set of data
15301: for a particular resource in a namespace passed in the $storehash hash 
15302: reference. If $tolog is true, the transaction is logged in the courselog
15303: with an action=PUTSTORE.
15304: 
15305: =item *
15306: 
15307: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15308: works very similar to store/cstore, but all data is stored in a
15309: temporary location and can be reset using tmpreset, $storehash should
15310: be a hash reference, returns nothing on success
15311: 
15312: =item *
15313: 
15314: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15315: similar to restore, but all data is stored in a temporary location and
15316: can be reset using tmpreset. Returns a hash of values on success,
15317: error string otherwise.
15318: 
15319: =item *
15320: 
15321: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15322: deltes all keys for $symb form the temporary storage hash.
15323: 
15324: =item *
15325: 
15326: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15327: reference filled in from namesp ($udom and $uname are optional)
15328: 
15329: =item *
15330: 
15331: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15332: namesp ($udom and $uname are optional)
15333: 
15334: =item *
15335: 
15336: dump($namespace,$udom,$uname,$regexp,$range) : 
15337: dumps the complete (or key matching regexp) namespace into a hash
15338: ($udom, $uname, $regexp, $range are optional)
15339: 
15340: $range should be either an integer '100' (give me the first 100
15341:                                            matching records)
15342:               or be  two integers sperated by a - with no spaces
15343:                  '30-50' (give me the 30th through the 50th matching
15344:                           records)
15345: =item *
15346: 
15347: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15348: $store can be a scalar, an array reference, or if the amount to be 
15349: incremented is > 1, a hash reference.
15350: 
15351: ($udom and $uname are optional)
15352: 
15353: =item *
15354: 
15355: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15356: ($udom and $uname are optional)
15357: 
15358: =item *
15359: 
15360: cput($namespace,$storehash,$udom,$uname) : critical put
15361: ($udom and $uname are optional)
15362: 
15363: =item *
15364: 
15365: newput($namespace,$storehash,$udom,$uname) :
15366: 
15367: Attempts to store the items in the $storehash, but only if they don't
15368: currently exist, if this succeeds you can be certain that you have 
15369: successfully created a new key value pair in the $namespace db.
15370: 
15371: 
15372: Args:
15373:  $namespace: name of database to store values to
15374:  $storehash: hashref to store to the db
15375:  $udom: (optional) domain of user containing the db
15376:  $uname: (optional) name of user caontaining the db
15377: 
15378: Returns:
15379:  'ok' -> succeeded in storing all keys of $storehash
15380:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15381:                         least <key> already existed in the db (other
15382:                         requested keys may also already exist)
15383:  'error: <msg>' -> unable to tie the DB or other error occurred
15384:  'con_lost' -> unable to contact request server
15385:  'refused' -> action was not allowed by remote machine
15386: 
15387: 
15388: =item *
15389: 
15390: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15391: reference filled in from namesp (encrypts the return communication)
15392: ($udom and $uname are optional)
15393: 
15394: =item *
15395: 
15396: log($udom,$name,$home,$message) : write to permanent log for user; use
15397: critical subroutine
15398: 
15399: =item *
15400: 
15401: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15402: array reference filled in from namespace found in domain level on either
15403: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15404: 
15405: =item *
15406: 
15407: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15408: domain level either on specified domain server ($uhome) or primary domain 
15409: server ($udom and $uhome are optional)
15410: 
15411: =item * 
15412: 
15413: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15414: for: authentication, language, quotas, timezone, date locale, and portal URL in
15415: the target domain.
15416: 
15417: May also include additional key => value pairs for the following groups:
15418: 
15419: =over
15420: 
15421: =item
15422: disk quotas (MB allocated by default to portfolios and authoring spaces).
15423: 
15424: =over
15425: 
15426: =item defaultquota, authorquota
15427: 
15428: =back
15429: 
15430: =item
15431: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15432: portfolio for users).
15433: 
15434: =over
15435: 
15436: =item
15437: aboutme, blog, webdav, portfolio
15438: 
15439: =back
15440: 
15441: =item
15442: requestcourses: ability to request courses, and how requests are processed.
15443: 
15444: =over
15445: 
15446: =item
15447: official, unofficial, community, textbook, placement
15448: 
15449: =back
15450: 
15451: =item
15452: inststatus: types of institutional affiliation, and order in which they are displayed.
15453: 
15454: =over
15455: 
15456: =item
15457: inststatustypes, inststatusorder, inststatusguest
15458: 
15459: =back
15460: 
15461: =item
15462: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15463: for course's uploaded content.
15464: 
15465: =over
15466: 
15467: =item
15468: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15469: communityquota, textbookquota, placementquota
15470: 
15471: =back
15472: 
15473: =item
15474: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15475: on your servers.
15476: 
15477: =over
15478: 
15479: =item 
15480: remotesessions, hostedsessions
15481: 
15482: =back
15483: 
15484: =back
15485: 
15486: In cases where a domain coordinator has never used the "Set Domain Configuration"
15487: utility to create a configuration.db file on a domain's primary library server 
15488: only the following domain defaults: auth_def, auth_arg_def, lang_def
15489: -- corresponding values are authentication type (internal, krb4, krb5,
15490: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15491: will be available. Values are retrieved from cache (if current), unless the
15492: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15493: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15494: 
15495: Typical usage:
15496: 
15497: %domdefaults = &get_domain_defaults($target_domain);
15498: 
15499: =back
15500: 
15501: =head2 Network Status Functions
15502: 
15503: =over 4
15504: 
15505: =item *
15506: 
15507: dirlist() : return directory list based on URI (first arg).
15508: 
15509: Inputs: 1 required, 5 optional.
15510: 
15511: =over
15512: 
15513: =item 
15514: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15515: 
15516: =item
15517: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15518: 
15519: =item
15520: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15521: 
15522: =item
15523: $getpropath - boolean: 1 if prepend path using &propath(). 
15524: 
15525: =item
15526: $getuserdir - boolean: 1 if prepend path for "userfiles".
15527: 
15528: =item 
15529: $alternateRoot - path to prepend in place of path from $uri.
15530: 
15531: =back
15532: 
15533: Returns: Array of up to two items.
15534: 
15535: =over
15536: 
15537: a reference to an array of files/subdirectories
15538: 
15539: =over
15540: 
15541: Each element in the array of files/subdirectories is a & separated list of
15542: item name and the result of running stat on the item.  If dirlist was requested
15543: for a file instead of a directory, the item name will be ''. For a directory 
15544: listing, if the item is a metadata file, the element will end &N&M 
15545: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15546: default copyright set (1).  
15547: 
15548: =back
15549: 
15550: a scalar containing error condition (if encountered).
15551: 
15552: =over
15553: 
15554: =item 
15555: no_host (no homeserver identified for $username:$domain).
15556: 
15557: =item 
15558: no_such_host (server contacted for listing not identified as valid host).
15559: 
15560: =item 
15561: con_lost (connection to remote server failed).
15562: 
15563: =item 
15564: refused (invalid $username:$domain received on lond side).
15565: 
15566: =item 
15567: no_such_dir (directory at specified path on lond side does not exist). 
15568: 
15569: =item 
15570: empty (directory at specified path on lond side is empty).
15571: 
15572: =over
15573: 
15574: This is currently not encountered because the &ls3, &ls2, 
15575: &ls (_handler) routines on the lond side do not filter out
15576: . and .. from a directory listing. 
15577: 
15578: =back
15579: 
15580: =back
15581: 
15582: =back
15583: 
15584: =item *
15585: 
15586: spareserver() : find server with least workload from spare.tab
15587: 
15588: 
15589: =item *
15590: 
15591: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15592: if there is no corresponding loncapa host.
15593: 
15594: =back
15595: 
15596: 
15597: =head2 Apache Request
15598: 
15599: =over 4
15600: 
15601: =item *
15602: 
15603: ssi($url,%hash) : server side include, does a complete request cycle on url to
15604: localhost, posts hash
15605: 
15606: =back
15607: 
15608: =head2 Data to String to Data
15609: 
15610: =over 4
15611: 
15612: =item *
15613: 
15614: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15615: and '&' separators, supports elements that are arrayrefs and hashrefs
15616: 
15617: =item *
15618: 
15619: hashref2str($hashref) : convert a hashref into a string complete with
15620: escaping and '=' and '&' separators, supports elements that are
15621: arrayrefs and hashrefs
15622: 
15623: =item *
15624: 
15625: arrayref2str($arrayref) : convert an arrayref into a string complete
15626: with escaping and '&' separators, supports elements that are arrayrefs
15627: and hashrefs
15628: 
15629: =item *
15630: 
15631: str2hash($string) : convert string to hash using unescaping and
15632: splitting on '=' and '&', supports elements that are arrayrefs and
15633: hashrefs
15634: 
15635: =item *
15636: 
15637: str2array($string) : convert string to hash using unescaping and
15638: splitting on '&', supports elements that are arrayrefs and hashrefs
15639: 
15640: =back
15641: 
15642: =head2 Logging Routines
15643: 
15644: 
15645: These routines allow one to make log messages in the lonnet.log and
15646: lonnet.perm logfiles.
15647: 
15648: =over 4
15649: 
15650: =item *
15651: 
15652: logtouch() : make sure the logfile, lonnet.log, exists
15653: 
15654: =item *
15655: 
15656: logthis() : append message to the normal lonnet.log file, it gets
15657: preiodically rolled over and deleted.
15658: 
15659: =item *
15660: 
15661: logperm() : append a permanent message to lonnet.perm.log, this log
15662: file never gets deleted by any automated portion of the system, only
15663: messages of critical importance should go in here.
15664: 
15665: 
15666: =back
15667: 
15668: =head2 General File Helper Routines
15669: 
15670: =over 4
15671: 
15672: =item *
15673: 
15674: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15675: (a) files in /uploaded
15676:   (i) If a local copy of the file exists - 
15677:       compares modification date of local copy with last-modified date for 
15678:       definitive version stored on home server for course. If local copy is 
15679:       stale, requests a new version from the home server and stores it. 
15680:       If the original has been removed from the home server, then local copy 
15681:       is unlinked.
15682:   (ii) If local copy does not exist -
15683:       requests the file from the home server and stores it. 
15684:   
15685:   If $caller is 'uploadrep':  
15686:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15687:     for request for files originally uploaded via DOCS. 
15688:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15689:   
15690:   Otherwise:
15691:      This indicates a call from the content generation phase of the request.
15692:      -  returns the entire contents of the file or -1.
15693:      
15694: (b) files in /res
15695:    - returns the entire contents of a file or -1; 
15696:    it properly subscribes to and replicates the file if neccessary.
15697: 
15698: 
15699: =item *
15700: 
15701: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15702:                   reference
15703: 
15704: returns either a stat() list of data about the file or an empty list
15705: if the file doesn't exist or couldn't find out about it (connection
15706: problems or user unknown)
15707: 
15708: =item *
15709: 
15710: filelocation($dir,$file) : returns file system location of a file
15711: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15712: directory that relative $file lookups are to looked in ($dir of /a/dir
15713: and a file of ../bob will become /a/bob)
15714: 
15715: =item *
15716: 
15717: hreflocation($dir,$file) : returns file system location or a URL; same as
15718: filelocation except for hrefs
15719: 
15720: =item *
15721: 
15722: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15723: also removes beginning /home/httpd/html unless /priv/ follows it.
15724: 
15725: =back
15726: 
15727: =head2 Usererfile file routines (/uploaded*)
15728: 
15729: =over 4
15730: 
15731: =item *
15732: 
15733: userfileupload(): main rotine for putting a file in a user or course's
15734:                   filespace, arguments are,
15735: 
15736:  formname - required - this is the name of the element in $env where the
15737:            filename, and the contents of the file to create/modifed exist
15738:            the filename is in $env{'form.'.$formname.'.filename'} and the
15739:            contents of the file is located in $env{'form.'.$formname}
15740:  context - if coursedoc, store the file in the course of the active role
15741:              of the current user; 
15742:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15743:            if 'canceloverwrite': delete file in tmp/overwrites directory
15744:  subdir - required - subdirectory to put the file in under ../userfiles/
15745:          if undefined, it will be placed in "unknown"
15746: 
15747:  (This routine calls clean_filename() to remove any dangerous
15748:  characters from the filename, and then calls finuserfileupload() to
15749:  complete the transaction)
15750: 
15751:  returns either the url of the uploaded file (/uploaded/....) if successful
15752:  and /adm/notfound.html if unsuccessful
15753: 
15754: =item *
15755: 
15756: clean_filename(): routine for cleaing a filename up for storage in
15757:                  userfile space, argument is:
15758: 
15759:  filename - proposed filename
15760: 
15761: returns: the new clean filename
15762: 
15763: =item *
15764: 
15765: finishuserfileupload(): routine that creates and sends the file to
15766: userspace, probably shouldn't be called directly
15767: 
15768:   docuname: username or courseid of destination for the file
15769:   docudom: domain of user/course of destination for the file
15770:   formname: same as for userfileupload()
15771:   fname: filename (including subdirectories) for the file
15772:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15773:   allfiles: reference to hash used to store objects found by parser
15774:   codebase: reference to hash used for codebases of java objects found by parser
15775:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15776:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15777:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15778:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15779:   context: if 'overwrite', will move the uploaded file from its temporary location to
15780:             userfiles to facilitate overwriting a previously uploaded file with same name.
15781:   mimetype: reference to scalar to accommodate mime type determined
15782:             from File::MMagic if $parser = parse.
15783: 
15784:  returns either the url of the uploaded file (/uploaded/....) if successful
15785:  and /adm/notfound.html if unsuccessful (or an error message if context 
15786:  was 'overwrite').
15787:  
15788: 
15789: =item *
15790: 
15791: renameuserfile(): renames an existing userfile to a new name
15792: 
15793:   Args:
15794:    docuname: username or courseid of destination for the file
15795:    docudom: domain of user/course of destination for the file
15796:    old: current file name (including any subdirs under userfiles)
15797:    new: desired file name (including any subdirs under userfiles)
15798: 
15799: =item *
15800: 
15801: mkdiruserfile(): creates a directory is a userfiles dir
15802: 
15803:   Args:
15804:    docuname: username or courseid of destination for the file
15805:    docudom: domain of user/course of destination for the file
15806:    dir: dir to create (including any subdirs under userfiles)
15807: 
15808: =item *
15809: 
15810: removeuserfile(): removes a file that exists in userfiles
15811: 
15812:   Args:
15813:    docuname: username or courseid of destination for the file
15814:    docudom: domain of user/course of destination for the file
15815:    fname: filname to delete (including any subdirs under userfiles)
15816: 
15817: =item *
15818: 
15819: removeuploadedurl(): convience function for removeuserfile()
15820: 
15821:   Args:
15822:    url:  a full /uploaded/... url to delete
15823: 
15824: =item * 
15825: 
15826: get_portfile_permissions():
15827:   Args:
15828:     domain: domain of user or course contain the portfolio files
15829:     user: name of user or num of course contain the portfolio files
15830:   Returns:
15831:     hashref of a dump of the proper file_permissions.db
15832:    
15833: 
15834: =item * 
15835: 
15836: get_access_controls():
15837: 
15838: Args:
15839:   current_permissions: the hash ref returned from get_portfile_permissions()
15840:   group: (optional) the group you want the files associated with
15841:   file: (optional) the file you want access info on
15842: 
15843: Returns:
15844:     a hash (keys are file names) of hashes containing
15845:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15846:         values are XML containing access control settings (see below) 
15847: 
15848: Internal notes:
15849: 
15850:  access controls are stored in file_permissions.db as key=value pairs.
15851:     key -> path to file/file_name\0uniqueID:scope_end_start
15852:         where scope -> public,guest,course,group,domains or users.
15853:               end -> UNIX time for end of access (0 -> no end date)
15854:               start -> UNIX time for start of access
15855: 
15856:     value -> XML description of access control
15857:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15858:             <start></start>
15859:             <end></end>
15860: 
15861:             <password></password>  for scope type = guest
15862: 
15863:             <domain></domain>     for scope type = course or group
15864:             <number></number>
15865:             <roles id="">
15866:              <role></role>
15867:              <access></access>
15868:              <section></section>
15869:              <group></group>
15870:             </roles>
15871: 
15872:             <dom></dom>         for scope type = domains
15873: 
15874:             <users>             for scope type = users
15875:              <user>
15876:               <uname></uname>
15877:               <udom></udom>
15878:              </user>
15879:             </users>
15880:            </scope> 
15881:               
15882:  Access data is also aggregated for each file in an additional key=value pair:
15883:  key -> path to file/file_name\0accesscontrol 
15884:  value -> reference to hash
15885:           hash contains key = value pairs
15886:           where key = uniqueID:scope_end_start
15887:                 value = UNIX time record was last updated
15888: 
15889:           Used to improve speed of look-ups of access controls for each file.  
15890:  
15891:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15892: 
15893: =item *
15894: 
15895: modify_access_controls():
15896: 
15897: Modifies access controls for a portfolio file
15898: Args
15899: 1. file name
15900: 2. reference to hash of required changes,
15901: 3. domain
15902: 4. username
15903:   where domain,username are the domain of the portfolio owner 
15904:   (either a user or a course) 
15905: 
15906: Returns:
15907: 1. result of additions or updates ('ok' or 'error', with error message). 
15908: 2. result of deletions ('ok' or 'error', with error message).
15909: 3. reference to hash of any new or updated access controls.
15910: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15911:    key = integer (inbound ID)
15912:    value = uniqueID
15913: 
15914: =item *
15915: 
15916: get_timebased_id():
15917: 
15918: Attempts to get a unique timestamp-based suffix for use with items added to a 
15919: course via the Course Editor (e.g., folders, composite pages, 
15920: group bulletin boards).
15921: 
15922: Args: (first three required; six others optional)
15923: 
15924: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15925:    docssequence, or name of group
15926: 
15927: 2. keyid (alphanumeric): name of temporary locking key in hash,
15928:    e.g., num, boardids
15929: 
15930: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15931:    file will be named nohist_namespace.db
15932: 
15933: 4. cdom: domain of course; default is current course domain from %env
15934: 
15935: 5. cnum: course number; default is current course number from %env
15936: 
15937: 6. idtype: set to concat if an additional digit is to be appended to the 
15938:    unix timestamp to form the suffix, if the plain timestamp is already
15939:    in use.  Default is to not do this, but simply increment the unix 
15940:    timestamp by 1 until a unique key is obtained.
15941: 
15942: 7. who: holder of locking key; defaults to user:domain for user.
15943: 
15944: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15945:    retrying); default is 3.
15946: 
15947: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15948: 
15949: Returns:
15950: 
15951: 1. suffix obtained (numeric)
15952: 
15953: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15954: 
15955: 3. error: contains (localized) error message if an error occurred.
15956: 
15957: 
15958: =back
15959: 
15960: =head2 HTTP Helper Routines
15961: 
15962: =over 4
15963: 
15964: =item *
15965: 
15966: escape() : unpack non-word characters into CGI-compatible hex codes
15967: 
15968: =item *
15969: 
15970: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15971: 
15972: =back
15973: 
15974: =head1 PRIVATE SUBROUTINES
15975: 
15976: =head2 Underlying communication routines (Shouldn't call)
15977: 
15978: =over 4
15979: 
15980: =item *
15981: 
15982: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15983: 
15984: =item *
15985: 
15986: reply() : uses subreply to send a message to remote machine, logs all failures
15987: 
15988: =item *
15989: 
15990: critical() : passes a critical message to another server; if cannot
15991: get through then place message in connection buffer directory and
15992: returns con_delayed, if incapable of saving message, returns
15993: con_failed
15994: 
15995: =item *
15996: 
15997: reconlonc() : tries to reconnect lonc client processes.
15998: 
15999: =back
16000: 
16001: =head2 Resource Access Logging
16002: 
16003: =over 4
16004: 
16005: =item *
16006: 
16007: flushcourselogs() : flush (save) buffer logs and access logs
16008: 
16009: =item *
16010: 
16011: courselog($what) : save message for course in hash
16012: 
16013: =item *
16014: 
16015: courseacclog($what) : save message for course using &courselog().  Perform
16016: special processing for specific resource types (problems, exams, quizzes, etc).
16017: 
16018: =item *
16019: 
16020: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16021: as a PerlChildExitHandler
16022: 
16023: =back
16024: 
16025: =head2 Other
16026: 
16027: =over 4
16028: 
16029: =item *
16030: 
16031: symblist($mapname,%newhash) : update symbolic storage links
16032: 
16033: =back
16034: 
16035: =cut
16036: 

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