File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1516: download - view: text, annotated - select for diffs
Fri Oct 6 01:22:06 2023 UTC (9 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6979
  Fix typos in rev. 1.1515
  Remove some trailing whitespace

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1516 2023/10/06 01:22:06 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 $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   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 Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: sub sign_lti {
  419:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
  420:     my $chome;
  421:     if (&domain($cdom) ne '') {
  422:         if ($crsdef) {
  423:             $chome = &homeserver($cnum,$cdom);
  424:         } else {
  425:             $chome = &domain($cdom,'primary');
  426:         }
  427:     }
  428:     if ($cdom && $chome && ($chome ne 'no_host')) {
  429:         if ((ref($paramsref) eq 'HASH') &&
  430:             (ref($inforef) eq 'HASH')) {
  431:             my $rep;
  432:             if (grep { $_ eq $chome } &current_machine_ids()) {
  433:                 # domain information is hosted on this machine
  434:                 $rep =
  435:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
  436:                                                      $context,$url,$ltinum,$keynum,
  437:                                                      $perlvar{'lonVersion'},
  438:                                                      $paramsref,$inforef);
  439:                 if (ref($rep) eq 'HASH') {
  440:                     return ('ok',$rep);
  441:                 }
  442:             } else {
  443:                 my ($escurl,$params,$info);
  444:                 $escurl = &escape($url);
  445:                 if (ref($paramsref) eq 'HASH') {
  446:                     $params = &freeze_escape($paramsref);
  447:                 }
  448:                 if (ref($inforef) eq 'HASH') {
  449:                     $info = &freeze_escape($inforef);
  450:                 }
  451:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
  452:             }
  453:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
  454:                 return ();
  455:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
  456:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
  457:                 return ('ok',$rep);
  458:             } else {
  459:                 my %returnhash;
  460:                 foreach my $item (split(/\&/,$rep)) {
  461:                     my ($name,$value)=split(/\=/,$item);
  462:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
  463:                 }
  464:                 return('ok',\%returnhash);
  465:             }
  466:         } else {
  467:             return ();
  468:         }
  469:     } else {
  470:         return ();
  471:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
  472:     }
  473: }
  474: 
  475: # -------------------------------------------------- Non-critical communication
  476: sub subreply {
  477:     my ($cmd,$server)=@_;
  478:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  479:     #
  480:     #  With loncnew process trimming, there's a timing hole between lonc server
  481:     #  process exit and the master server picking up the listen on the AF_UNIX
  482:     #  socket.  In that time interval, a lock file will exist:
  483: 
  484:     my $lockfile=$peerfile.".lock";
  485:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  486: 	sleep(0.1);
  487:     }
  488:     # At this point, either a loncnew parent is listening or an old lonc
  489:     # or loncnew child is listening so we can connect or everything's dead.
  490:     #
  491:     #   We'll give the connection a few tries before abandoning it.  If
  492:     #   connection is not possible, we'll con_lost back to the client.
  493:     #   
  494:     my $client;
  495:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  496: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  497: 				      Type    => SOCK_STREAM,
  498: 				      Timeout => 10);
  499: 	if ($client) {
  500: 	    last;		# Connected!
  501: 	} else {
  502: 	    &create_connection(&hostname($server),$server);
  503: 	}
  504:         sleep(0.1);	# Try again later if failed connection.
  505:     }
  506:     my $answer;
  507:     if ($client) {
  508: 	print $client "sethost:$server:$cmd\n";
  509: 	$answer=<$client>;
  510: 	if (!$answer) { $answer="con_lost"; }
  511: 	chomp($answer);
  512:     } else {
  513: 	$answer = 'con_lost';	# Failed connection.
  514:     }
  515:     return $answer;
  516: }
  517: 
  518: sub reply {
  519:     my ($cmd,$server)=@_;
  520:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  521:     my $answer=subreply($cmd,$server);
  522:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  523:         my $logged = $cmd;
  524:         if ($cmd =~ /^encrypt:([^:]+):/) {
  525:             my $subcmd = $1;
  526:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  527:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  528:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  529:                 ($subcmd eq 'put')) {
  530:                 (undef,undef,my @rest) = split(/:/,$cmd);
  531:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  532:                     splice(@rest,2,1,'Hidden');
  533:                 } elsif ($subcmd eq 'passwd') {
  534:                     splice(@rest,2,2,('Hidden','Hidden'));
  535:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  536:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  537:                     splice(@rest,3,1,'Hidden');
  538:                 }
  539:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  540:             }
  541:         }
  542:         &logthis("<font color=\"blue\">WARNING:".
  543:                  " $logged to $server returned $answer</font>");
  544:     }
  545:     return $answer;
  546: }
  547: 
  548: # ----------------------------------------------------------- Send USR1 to lonc
  549: 
  550: sub reconlonc {
  551:     my ($lonid) = @_;
  552:     if ($lonid) {
  553:         my $hostname = &hostname($lonid);
  554: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  555: 	if ($hostname && -e $peerfile) {
  556: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  557: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  558: 					     Type    => SOCK_STREAM,
  559: 					     Timeout => 10);
  560: 	    if ($client) {
  561: 		print $client ("reset_retries\n");
  562: 		my $answer=<$client>;
  563: 		#reset just this one.
  564: 	    }
  565: 	}
  566: 	return;
  567:     }
  568: 
  569:     &logthis("Trying to reconnect lonc");
  570:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  571:     if (open(my $fh,"<",$loncfile)) {
  572: 	my $loncpid=<$fh>;
  573:         chomp($loncpid);
  574:         if (kill 0 => $loncpid) {
  575: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  576:             kill USR1 => $loncpid;
  577:             sleep 1;
  578:         } else {
  579: 	    &logthis(
  580:                "<font color=\"blue\">WARNING:".
  581:                " lonc at pid $loncpid not responding, giving up</font>");
  582:         }
  583:     } else {
  584: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  585:     }
  586: }
  587: 
  588: # ------------------------------------------------------ Critical communication
  589: 
  590: sub critical {
  591:     my ($cmd,$server)=@_;
  592:     unless (&hostname($server)) {
  593:         &logthis("<font color=\"blue\">WARNING:".
  594:                " Critical message to unknown server ($server)</font>");
  595:         return 'no_such_host';
  596:     }
  597:     my $answer=reply($cmd,$server);
  598:     if ($answer eq 'con_lost') {
  599: 	&reconlonc($server);
  600: 	my $answer=reply($cmd,$server);
  601:         if ($answer eq 'con_lost') {
  602:             my $now=time;
  603:             my $middlename=$cmd;
  604:             $middlename=substr($middlename,0,16);
  605:             $middlename=~s/\W//g;
  606:             my $dfilename=
  607:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  608:             $dumpcount++;
  609:             {
  610: 		my $dfh;
  611: 		if (open($dfh,">",$dfilename)) {
  612: 		    print $dfh "$cmd\n"; 
  613: 		    close($dfh);
  614: 		}
  615:             }
  616:             sleep 1;
  617:             my $wcmd='';
  618:             {
  619: 		my $dfh;
  620: 		if (open($dfh,"<",$dfilename)) {
  621: 		    $wcmd=<$dfh>; 
  622: 		    close($dfh);
  623: 		}
  624:             }
  625:             chomp($wcmd);
  626:             if ($wcmd eq $cmd) {
  627: 		&logthis("<font color=\"blue\">WARNING: ".
  628:                          "Connection buffer $dfilename: $cmd</font>");
  629:                 &logperm("D:$server:$cmd");
  630: 	        return 'con_delayed';
  631:             } else {
  632:                 &logthis("<font color=\"red\">CRITICAL:"
  633:                         ." Critical connection failed: $server $cmd</font>");
  634:                 &logperm("F:$server:$cmd");
  635:                 return 'con_failed';
  636:             }
  637:         }
  638:     }
  639:     return $answer;
  640: }
  641: 
  642: # ------------------------------------------- check if return value is an error
  643: 
  644: sub error {
  645:     my ($result) = @_;
  646:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  647: 	if ($2 == 2) { return undef; }
  648: 	return $1;
  649:     }
  650:     return undef;
  651: }
  652: 
  653: sub convert_and_load_session_env {
  654:     my ($lonidsdir,$handle)=@_;
  655:     my @profile;
  656:     {
  657: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  658: 	if (!$opened) {
  659: 	    return 0;
  660: 	}
  661: 	flock($idf,LOCK_SH);
  662: 	@profile=<$idf>;
  663: 	close($idf);
  664:     }
  665:     my %temp_env;
  666:     foreach my $line (@profile) {
  667: 	if ($line !~ m/=/) {
  668: 	    return 0;
  669: 	}
  670: 	chomp($line);
  671: 	my ($envname,$envvalue)=split(/=/,$line,2);
  672: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  673:     }
  674:     unlink("$lonidsdir/$handle.id");
  675:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  676: 	    0640)) {
  677: 	%disk_env = %temp_env;
  678: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  679: 	untie(%disk_env);
  680:     }
  681:     return 1;
  682: }
  683: 
  684: # ------------------------------------------- Transfer profile into environment
  685: my $env_loaded;
  686: sub transfer_profile_to_env {
  687:     my ($lonidsdir,$handle,$force_transfer) = @_;
  688:     if (!$force_transfer && $env_loaded) { return; } 
  689: 
  690:     if (!defined($lonidsdir)) {
  691: 	$lonidsdir = $perlvar{'lonIDsDir'};
  692:     }
  693:     if (!defined($handle)) {
  694:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  695:     }
  696: 
  697:     my $convert;
  698:     {
  699:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  700: 	if (!$opened) {
  701: 	    return;
  702: 	}
  703: 	flock($idf,LOCK_SH);
  704: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  705: 		&GDBM_READER(),0640)) {
  706: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  707: 	    untie(%disk_env);
  708: 	} else {
  709: 	    $convert = 1;
  710: 	}
  711:     }
  712:     if ($convert) {
  713: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  714: 	    &logthis("Failed to load session, or convert session.");
  715: 	}
  716:     }
  717: 
  718:     my %remove;
  719:     while ( my $envname = each(%env) ) {
  720:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  721:             if ($time < time-300) {
  722:                 $remove{$key}++;
  723:             }
  724:         }
  725:     }
  726: 
  727:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  728:     $env_loaded=1;
  729:     foreach my $expired_key (keys(%remove)) {
  730:         &delenv($expired_key);
  731:     }
  732: }
  733: 
  734: # ---------------------------------------------------- Check for valid session 
  735: sub check_for_valid_session {
  736:     my ($r,$name,$userhashref,$domref) = @_;
  737:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  738:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  739:     if ($name eq 'lonDAV') {
  740:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  741:     } else {
  742:         $lonidsdir=$r->dir_config('lonIDsDir');
  743:         if ($name eq '') {
  744:             $name = 'lonID';
  745:         }
  746:     }
  747:     if ($name eq 'lonID') {
  748:         $secure = 'lonSID';
  749:         $linkname = 'lonLinkID';
  750:         $pubname = 'lonPubID';
  751:         if (exists($cookies{$secure})) {
  752:             $lonid=$cookies{$secure};
  753:         } elsif (exists($cookies{$name})) {
  754:             $lonid=$cookies{$name};
  755:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  756:             $lonid=$cookies{$linkname};
  757:         } elsif (exists($cookies{$pubname})) {
  758:             $lonid=$cookies{$pubname};
  759:         }
  760:     } else {
  761:         $lonid=$cookies{$name};
  762:     }
  763:     return undef if (!$lonid);
  764: 
  765:     my $handle=&LONCAPA::clean_handle($lonid->value);
  766:     if (-l "$lonidsdir/$handle.id") {
  767:         my $link = readlink("$lonidsdir/$handle.id");
  768:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  769:             $handle = $1;
  770:         }
  771:     }
  772:     if (!-e "$lonidsdir/$handle.id") {
  773:         if ((ref($domref)) && ($name eq 'lonID') && 
  774:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  775:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  776:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  777:                 $$domref = $possudom;
  778:             }
  779:         }
  780:         return undef;
  781:     }
  782: 
  783:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  784:     return undef if (!$opened);
  785: 
  786:     flock($idf,LOCK_SH);
  787:     my %disk_env;
  788:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  789: 	    &GDBM_READER(),0640)) {
  790: 	return undef;	
  791:     }
  792: 
  793:     if (!defined($disk_env{'user.name'})
  794: 	|| !defined($disk_env{'user.domain'})) {
  795:         untie(%disk_env);
  796: 	return undef;
  797:     }
  798: 
  799:     if (ref($userhashref) eq 'HASH') {
  800:         $userhashref->{'name'} = $disk_env{'user.name'};
  801:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  802:         if ($disk_env{'request.role'}) {
  803:             $userhashref->{'role'} = $disk_env{'request.role'};
  804:         }
  805:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  806:         if ($userhashref->{'lti'}) {
  807:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  808:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  809:         }
  810:     }
  811:     untie(%disk_env);
  812: 
  813:     return $handle;
  814: }
  815: 
  816: sub timed_flock {
  817:     my ($file,$lock_type) = @_;
  818:     my $failed=0;
  819:     eval {
  820: 	local $SIG{__DIE__}='DEFAULT';
  821: 	local $SIG{ALRM}=sub {
  822: 	    $failed=1;
  823: 	    die("failed lock");
  824: 	};
  825: 	alarm(13);
  826: 	flock($file,$lock_type);
  827: 	alarm(0);
  828:     };
  829:     if ($failed) {
  830: 	return undef;
  831:     } else {
  832: 	return 1;
  833:     }
  834: }
  835: 
  836: sub get_sessionfile_vars {
  837:     my ($handle,$lonidsdir,$storearr) = @_;
  838:     my %returnhash;
  839:     unless (ref($storearr) eq 'ARRAY') {
  840:         return %returnhash;
  841:     }
  842:     if (-l "$lonidsdir/$handle.id") {
  843:         my $link = readlink("$lonidsdir/$handle.id");
  844:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  845:             $handle = $1;
  846:         }
  847:     }
  848:     if ((-e "$lonidsdir/$handle.id") &&
  849:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  850:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  851:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  852:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  853:                 flock($idf,LOCK_SH);
  854:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  855:                         &GDBM_READER(),0640)) {
  856:                     foreach my $item (@{$storearr}) {
  857:                         $returnhash{$item} = $disk_env{$item};
  858:                     }
  859:                     untie(%disk_env);
  860:                 }
  861:             }
  862:         }
  863:     }
  864:     return %returnhash;
  865: }
  866: 
  867: # ---------------------------------------------------------- Append Environment
  868: 
  869: sub appenv {
  870:     my ($newenv,$roles) = @_;
  871:     if (ref($newenv) eq 'HASH') {
  872:         foreach my $key (keys(%{$newenv})) {
  873:             my $refused = 0;
  874: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  875:                 $refused = 1;
  876:                 if (ref($roles) eq 'ARRAY') {
  877:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  878:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  879:                         $refused = 0;
  880:                     }
  881:                 }
  882:             }
  883:             if ($refused) {
  884:                 &logthis("<font color=\"blue\">WARNING: ".
  885:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  886:                          .'</font>');
  887: 	        delete($newenv->{$key});
  888:             } else {
  889:                 $env{$key}=$newenv->{$key};
  890:             }
  891:         }
  892:         my $lonids = $perlvar{'lonIDsDir'};
  893:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  894:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  895:             if ($opened
  896: 	        && &timed_flock($env_file,LOCK_EX)
  897: 	        &&
  898: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  899: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  900: 	        while (my ($key,$value) = each(%{$newenv})) {
  901: 	            $disk_env{$key} = $value;
  902: 	        }
  903: 	        untie(%disk_env);
  904:             }
  905:         }
  906:     }
  907:     return 'ok';
  908: }
  909: # ----------------------------------------------------- Delete from Environment
  910: 
  911: sub delenv {
  912:     my ($delthis,$regexp,$roles) = @_;
  913:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  914:         my $refused = 1;
  915:         if (ref($roles) eq 'ARRAY') {
  916:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  917:             if (grep(/^\Q$role\E$/,@{$roles})) {
  918:                 $refused = 0;
  919:             }
  920:         }
  921:         if ($refused) {
  922:             &logthis("<font color=\"blue\">WARNING: ".
  923:                      "Attempt to delete from environment ".$delthis);
  924:             return 'error';
  925:         }
  926:     }
  927:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  928:     if ($opened
  929: 	&& &timed_flock($env_file,LOCK_EX)
  930: 	&&
  931: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  932: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  933: 	foreach my $key (keys(%disk_env)) {
  934: 	    if ($regexp) {
  935:                 if ($key=~/^$delthis/) {
  936:                     delete($env{$key});
  937:                     delete($disk_env{$key});
  938:                 } 
  939:             } else {
  940:                 if ($key=~/^\Q$delthis\E/) {
  941: 		    delete($env{$key});
  942: 		    delete($disk_env{$key});
  943: 	        }
  944:             }
  945: 	}
  946: 	untie(%disk_env);
  947:     }
  948:     return 'ok';
  949: }
  950: 
  951: sub get_env_multiple {
  952:     my ($name) = @_;
  953:     my @values;
  954:     if (defined($env{$name})) {
  955:         # exists is it an array
  956:         if (ref($env{$name})) {
  957:             @values=@{ $env{$name} };
  958:         } else {
  959:             $values[0]=$env{$name};
  960:         }
  961:     }
  962:     return(@values);
  963: }
  964: 
  965: # ------------------------------------------------------------------- Locking
  966: 
  967: sub set_lock {
  968:     my ($text)=@_;
  969:     $locknum++;
  970:     my $id=$$.'-'.$locknum;
  971:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  972:              'session.lock.'.$id => $text});
  973:     return $id;
  974: }
  975: 
  976: sub get_locks {
  977:     my $num=0;
  978:     my %texts=();
  979:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  980:        if ($lock=~/\w/) {
  981:           $num++;
  982:           $texts{$lock}=$env{'session.lock.'.$lock};
  983:        }
  984:    }
  985:    return ($num,%texts);
  986: }
  987: 
  988: sub remove_lock {
  989:     my ($id)=@_;
  990:     my $newlocks='';
  991:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  992:        if (($lock=~/\w/) && ($lock ne $id)) {
  993:           $newlocks.=','.$lock;
  994:        }
  995:     }
  996:     &appenv({'session.locks' => $newlocks});
  997:     &delenv('session.lock.'.$id);
  998: }
  999: 
 1000: sub remove_all_locks {
 1001:     my $activelocks=$env{'session.locks'};
 1002:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
 1003:        if ($lock=~/\w/) {
 1004:           &remove_lock($lock);
 1005:        }
 1006:     }
 1007: }
 1008: 
 1009: 
 1010: # ------------------------------------------ Find out current server userload
 1011: sub userload {
 1012:     my $numusers=0;
 1013:     {
 1014: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 1015: 	my $filename;
 1016: 	my $curtime=time;
 1017: 	while ($filename=readdir(LONIDS)) {
 1018: 	    next if ($filename eq '.' || $filename eq '..');
 1019: 	    next if ($filename =~ /publicuser_\d+\.id/);
 1020:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
 1021: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 1022: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 1023: 	}
 1024: 	closedir(LONIDS);
 1025:     }
 1026:     my $userloadpercent=0;
 1027:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 1028:     if ($maxuserload) {
 1029: 	$userloadpercent=100*$numusers/$maxuserload;
 1030:     }
 1031:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 1032:     return $userloadpercent;
 1033: }
 1034: 
 1035: # ------------------------------ Find server with least workload from spare.tab
 1036: 
 1037: sub spareserver {
 1038:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
 1039:     my $spare_server;
 1040:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
 1041:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
 1042:                                                      :  $userloadpercent;
 1043:     my ($uint_dom,$remotesessions);
 1044:     if (($udom ne '') && (&domain($udom) ne '')) {
 1045:         my $uprimary_id = &domain($udom,'primary');
 1046:         $uint_dom = &internet_dom($uprimary_id);
 1047:         my %udomdefaults = &get_domain_defaults($udom);
 1048:         $remotesessions = $udomdefaults{'remotesessions'};
 1049:     }
 1050:     my $spareshash = &this_host_spares($udom);
 1051:     if (ref($spareshash) eq 'HASH') {
 1052:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1053:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1054:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
 1055:                                              $try_server));
 1056: 	        ($spare_server, $lowest_load) =
 1057: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1058:             }
 1059:         }
 1060: 
 1061:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1062: 
 1063:         if (!$found_server) {
 1064:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1065: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1066:                     next unless (&spare_can_host($udom,$uint_dom,
 1067:                                                  $remotesessions,$try_server));
 1068: 	            ($spare_server, $lowest_load) =
 1069: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1070:                 }
 1071: 	    }
 1072:         }
 1073:     }
 1074: 
 1075:     if (!$want_server_name) {
 1076:         if (defined($spare_server)) {
 1077:             my $hostname = &hostname($spare_server);
 1078:             if (defined($hostname)) {
 1079:                 my $protocol = 'http';
 1080:                 if ($protocol{$spare_server} eq 'https') {
 1081:                     $protocol = $protocol{$spare_server};
 1082:                 }
 1083:                 my $alias = &use_proxy_alias($r,$spare_server);
 1084:                 $hostname = $alias if ($alias ne '');
 1085: 	        $spare_server = $protocol.'://'.$hostname;
 1086:             }
 1087:         }
 1088:     }
 1089:     return $spare_server;
 1090: }
 1091: 
 1092: sub compare_server_load {
 1093:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1094: 
 1095:     if ($required) {
 1096:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1097:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1098:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1099:         if (($major eq '' && $minor eq '') ||
 1100:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1101:             return ($spare_server,$lowest_load);
 1102:         }
 1103:     }
 1104: 
 1105:     my $loadans     = &reply('load',    $try_server);
 1106:     my $userloadans = &reply('userload',$try_server);
 1107: 
 1108:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1109: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1110:     }
 1111: 
 1112:     my $load;
 1113:     if ($loadans =~ /\d/) {
 1114: 	if ($userloadans =~ /\d/) {
 1115: 	    #both are numbers, pick the bigger one
 1116: 	    $load = ($loadans > $userloadans) ? $loadans 
 1117: 		                              : $userloadans;
 1118: 	} else {
 1119: 	    $load = $loadans;
 1120: 	}
 1121:     } else {
 1122: 	$load = $userloadans;
 1123:     }
 1124: 
 1125:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1126: 	$spare_server = $try_server;
 1127: 	$lowest_load  = $load;
 1128:     }
 1129:     return ($spare_server,$lowest_load);
 1130: }
 1131: 
 1132: # --------------------------- ask offload servers if user already has a session
 1133: sub find_existing_session {
 1134:     my ($udom,$uname) = @_;
 1135:     my $spareshash = &this_host_spares($udom);
 1136:     if (ref($spareshash) eq 'HASH') {
 1137:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1138:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1139:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1140:             }
 1141:         }
 1142:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1143:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1144:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1145:             }
 1146:         }
 1147:     }
 1148:     return;
 1149: }
 1150: 
 1151: sub delusersession {
 1152:     my ($lonid,$udom,$uname) = @_;
 1153:     my $uprimary_id = &domain($udom,'primary');
 1154:     my $uintdom = &internet_dom($uprimary_id);
 1155:     my $intdom = &internet_dom($lonid);
 1156:     my $serverhomedom = &host_domain($lonid);
 1157:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1158:         return &reply(join(':','delusersession',
 1159:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1160:     }
 1161:     return;
 1162: }
 1163: 
 1164: # check if user's browser sent load balancer cookie and server still has session
 1165: # and is not overloaded.
 1166: sub check_for_balancer_cookie {
 1167:     my ($r,$update_mtime) = @_;
 1168:     my ($otherserver,$cookie);
 1169:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1170:     if (exists($cookies{'balanceID'})) {
 1171:         my $balid = $cookies{'balanceID'};
 1172:         $cookie=&LONCAPA::clean_handle($balid->value);
 1173:         my $balancedir=$r->dir_config('lonBalanceDir');
 1174:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1175:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1176:                 my ($possudom,$possuname) = ($1,$2);
 1177:                 my $has_session = 0;
 1178:                 if ((&domain($possudom) ne '') &&
 1179:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1180:                     my $try_server;
 1181:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1182:                     if ($opened) {
 1183:                         flock($idf,LOCK_SH);
 1184:                         while (my $line = <$idf>) {
 1185:                             chomp($line);
 1186:                             if (&hostname($line) ne '') {
 1187:                                 $try_server = $line;
 1188:                                 last;
 1189:                             }
 1190:                         }
 1191:                         close($idf);
 1192:                         if (($try_server) &&
 1193:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1194:                             my $lowest_load = 30000;
 1195:                             ($otherserver,$lowest_load) =
 1196:                                 &compare_server_load($try_server,undef,$lowest_load);
 1197:                             if ($otherserver ne '' && $lowest_load < 100) {
 1198:                                 $has_session = 1;
 1199:                             } else {
 1200:                                 undef($otherserver);
 1201:                             }
 1202:                         }
 1203:                     }
 1204:                 }
 1205:                 if ($has_session) {
 1206:                     if ($update_mtime) {
 1207:                         my $atime = my $mtime = time;
 1208:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1209:                     }
 1210:                 } else {
 1211:                     unlink("$balancedir/$cookie.id");
 1212:                 }
 1213:             }
 1214:         }
 1215:     }
 1216:     return ($otherserver,$cookie);
 1217: }
 1218: 
 1219: sub updatebalcookie {
 1220:     my ($cookie,$balancer,$lastentry)=@_;
 1221:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1222:         my ($udom,$uname) = ($1,$2);
 1223:         my $uprimary_id = &domain($udom,'primary');
 1224:         my $uintdom = &internet_dom($uprimary_id);
 1225:         my $intdom = &internet_dom($balancer);
 1226:         my $serverhomedom = &host_domain($balancer);
 1227:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1228:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1229:         }
 1230:     }
 1231:     return;
 1232: }
 1233: 
 1234: sub delbalcookie {
 1235:     my ($cookie,$balancer) =@_;
 1236:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1237:         my ($udom,$uname) = ($1,$2);
 1238:         my $uprimary_id = &domain($udom,'primary');
 1239:         my $uintdom = &internet_dom($uprimary_id);
 1240:         my $intdom = &internet_dom($balancer);
 1241:         my $serverhomedom = &host_domain($balancer);
 1242:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1243:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1244:         }
 1245:     }
 1246: }
 1247: 
 1248: # -------------------------------- ask if server already has a session for user
 1249: sub has_user_session {
 1250:     my ($lonid,$udom,$uname) = @_;
 1251:     my $result = &reply(join(':','userhassession',
 1252: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1253:     return 1 if ($result eq 'ok');
 1254: 
 1255:     return 0;
 1256: }
 1257: 
 1258: # --------- determine least loaded server in a user's domain which allows login
 1259: 
 1260: sub choose_server {
 1261:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1262:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1263:     my %servers = &get_servers($udom);
 1264:     my $lowest_load = 30000;
 1265:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1266:     if ($skiploadbal) {
 1267:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1268:         unless (defined($cached)) {
 1269:             my $cachetime = 60*60*24;
 1270:             my %domconfig =
 1271:                 &get_dom('configuration',['loadbalancing'],$udom);
 1272:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1273:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1274:                                            $cachetime);
 1275:             }
 1276:         }
 1277:     }
 1278:     foreach my $lonhost (keys(%servers)) {
 1279:         if ($skiploadbal) {
 1280:             if (ref($balancers) eq 'HASH') {
 1281:                 next if (exists($balancers->{$lonhost}));
 1282:             }
 1283:         }
 1284:         my $loginvia;
 1285:         if ($checkloginvia) {
 1286:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1287:             if ($loginvia) {
 1288:                 my ($server,$path) = split(/:/,$loginvia);
 1289:                 ($login_host, $lowest_load) =
 1290:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1291:                 if ($login_host eq $server) {
 1292:                     $portal_path = $path;
 1293:                     $isredirect = 1;
 1294:                 }
 1295:             } else {
 1296:                 ($login_host, $lowest_load) =
 1297:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1298:                 if ($login_host eq $lonhost) {
 1299:                     $portal_path = '';
 1300:                     $isredirect = ''; 
 1301:                 }
 1302:             }
 1303:         } else {
 1304:             ($login_host, $lowest_load) =
 1305:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1306:         }
 1307:     }
 1308:     if ($login_host ne '') {
 1309:         $hostname = &hostname($login_host);
 1310:     }
 1311:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1312: }
 1313: 
 1314: sub get_course_sessions {
 1315:     my ($cnum,$cdom,$lastactivity) = @_;
 1316:     my %servers = &internet_dom_servers($cdom);
 1317:     my %returnhash;
 1318:     foreach my $server (sort(keys(%servers))) {
 1319:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1320:         my @pairs=split(/\&/,$rep);
 1321:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1322:             foreach my $item (@pairs) {
 1323:                 my ($key,$value)=split(/=/,$item,2);
 1324:                 $key = &unescape($key);
 1325:                 next if ($key =~ /^error: 2 /);
 1326:                 if (exists($returnhash{$key})) {
 1327:                     next if ($value < $returnhash{$key});
 1328:                 }
 1329:                 $returnhash{$key}=$value;
 1330:             }
 1331:         }
 1332:     }
 1333:     return %returnhash;
 1334: }
 1335: 
 1336: # --------------------------------------------- Try to change a user's password
 1337: 
 1338: sub changepass {
 1339:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1340:     $currentpass = &escape($currentpass);
 1341:     $newpass     = &escape($newpass);
 1342:     my $lonhost = $perlvar{'lonHostID'};
 1343:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1344: 		       $server);
 1345:     if (! $answer) {
 1346: 	&logthis("No reply on password change request to $server ".
 1347: 		 "by $uname in domain $udom.");
 1348:     } elsif ($answer =~ "^ok") {
 1349:         &logthis("$uname in $udom successfully changed their password ".
 1350: 		 "on $server.");
 1351:     } elsif ($answer =~ "^pwchange_failure") {
 1352: 	&logthis("$uname in $udom was unable to change their password ".
 1353: 		 "on $server.  The action was blocked by either lcpasswd ".
 1354: 		 "or pwchange");
 1355:     } elsif ($answer =~ "^non_authorized") {
 1356:         &logthis("$uname in $udom did not get their password correct when ".
 1357: 		 "attempting to change it on $server.");
 1358:     } elsif ($answer =~ "^auth_mode_error") {
 1359:         &logthis("$uname in $udom attempted to change their password despite ".
 1360: 		 "not being locally or internally authenticated on $server.");
 1361:     } elsif ($answer =~ "^unknown_user") {
 1362:         &logthis("$uname in $udom attempted to change their password ".
 1363: 		 "on $server but were unable to because $server is not ".
 1364: 		 "their home server.");
 1365:     } elsif ($answer =~ "^refused") {
 1366: 	&logthis("$server refused to change $uname in $udom password because ".
 1367: 		 "it was sent an unencrypted request to change the password.");
 1368:     } elsif ($answer =~ "invalid_client") {
 1369:         &logthis("$server refused to change $uname in $udom password because ".
 1370:                  "it was a reset by e-mail originating from an invalid server.");
 1371:     } elsif ($answer =~ "^prioruse") {
 1372:        &logthis("$server refused to change $uname in $udom password because ".
 1373:                 "the password had been used before");
 1374:     }
 1375:     return $answer;
 1376: }
 1377: 
 1378: # ----------------------- Try to determine user's current authentication scheme
 1379: 
 1380: sub queryauthenticate {
 1381:     my ($uname,$udom)=@_;
 1382:     my $uhome=&homeserver($uname,$udom);
 1383:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1384: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1385: 	return 'no_host';
 1386:     }
 1387:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1388:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1389: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1390:     }
 1391:     return $answer;
 1392: }
 1393: 
 1394: # --------- Try to authenticate user from domain's lib servers (first this one)
 1395: 
 1396: sub authenticate {
 1397:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1398:     $upass=&escape($upass);
 1399:     $uname= &LONCAPA::clean_username($uname);
 1400:     my $uhome=&homeserver($uname,$udom,1);
 1401:     my $newhome;
 1402:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1403: # Maybe the machine was offline and only re-appeared again recently?
 1404:         &reconlonc();
 1405: # One more
 1406: 	$uhome=&homeserver($uname,$udom,1);
 1407:         if (($uhome eq 'no_host') && $checkdefauth) {
 1408:             if (defined(&domain($udom,'primary'))) {
 1409:                 $newhome=&domain($udom,'primary');
 1410:             }
 1411:             if ($newhome ne '') {
 1412:                 $uhome = $newhome;
 1413:             }
 1414:         }
 1415: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1416: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1417: 	    return 'no_host';
 1418:         }
 1419:     }
 1420:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1421:     if ($answer eq 'authorized') {
 1422:         if ($newhome) {
 1423:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1424:             return 'no_account_on_host'; 
 1425:         } else {
 1426:             &logthis("User $uname at $udom authorized by $uhome");
 1427:             return $uhome;
 1428:         }
 1429:     }
 1430:     if ($answer eq 'non_authorized') {
 1431: 	&logthis("User $uname at $udom rejected by $uhome");
 1432: 	return 'no_host';
 1433:     }
 1434:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1435:     return 'no_host';
 1436: }
 1437: 
 1438: sub can_switchserver {
 1439:     my ($udom,$home) = @_;
 1440:     my ($canswitch,@intdoms);
 1441:     my $internet_names = &get_internet_names($home);
 1442:     if (ref($internet_names) eq 'ARRAY') {
 1443:         @intdoms = @{$internet_names};
 1444:     }
 1445:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1446:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1447:         $canswitch = 1;
 1448:     } else {
 1449:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1450:          my $serverhomedom = &host_domain($serverhomeID);
 1451:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1452:          my %udomdefaults = &get_domain_defaults($udom);
 1453:          my $remoterev = &get_server_loncaparev('',$home);
 1454:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1455:                                         $udomdefaults{'remotesessions'},
 1456:                                         $defdomdefaults{'hostedsessions'});
 1457:     }
 1458:     return $canswitch;
 1459: }
 1460: 
 1461: sub can_host_session {
 1462:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1463:     my $canhost = 1;
 1464:     my $host_idn = &internet_dom($lonhost);
 1465:     if (ref($remotesessions) eq 'HASH') {
 1466:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1467:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1468:                 $canhost = 0;
 1469:             } else {
 1470:                 $canhost = 1;
 1471:             }
 1472:         }
 1473:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1474:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1475:                 $canhost = 1;
 1476:             } else {
 1477:                 $canhost = 0;
 1478:             }
 1479:         }
 1480:         if ($canhost) {
 1481:             if ($remotesessions->{'version'} ne '') {
 1482:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1483:                 if ($reqmajor ne '' && $reqminor ne '') {
 1484:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1485:                         my $major = $1;
 1486:                         my $minor = $2;
 1487:                         if (($major < $reqmajor ) ||
 1488:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1489:                             $canhost = 0;
 1490:                         }
 1491:                     } else {
 1492:                         $canhost = 0;
 1493:                     }
 1494:                 }
 1495:             }
 1496:         }
 1497:     }
 1498:     if ($canhost) {
 1499:         if (ref($hostedsessions) eq 'HASH') {
 1500:             my $uprimary_id = &domain($udom,'primary');
 1501:             my $uint_dom = &internet_dom($uprimary_id);
 1502:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1503:                 if (($uint_dom ne '') && 
 1504:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1505:                     $canhost = 0;
 1506:                 } else {
 1507:                     $canhost = 1;
 1508:                 }
 1509:             }
 1510:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1511:                 if (($uint_dom ne '') && 
 1512:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1513:                     $canhost = 1;
 1514:                 } else {
 1515:                     $canhost = 0;
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520:     return $canhost;
 1521: }
 1522: 
 1523: sub spare_can_host {
 1524:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1525:     my $canhost=1;
 1526:     my $try_server_hostname = &hostname($try_server);
 1527:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1528:     my $serverhomedom = &host_domain($serverhomeID);
 1529:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1530:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1531:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1532:             $canhost = 0;
 1533:         }
 1534:     }
 1535:     if ($canhost) {
 1536:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1537:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1538:                 unless (&shared_institution($udom,$try_server)) {
 1539:                     $canhost = 0;
 1540:                 }
 1541:             }
 1542:         }
 1543:     }
 1544:     if (($canhost) && ($uint_dom)) {
 1545:         my @intdoms;
 1546:         my $internet_names = &get_internet_names($try_server);
 1547:         if (ref($internet_names) eq 'ARRAY') {
 1548:             @intdoms = @{$internet_names};
 1549:         }
 1550:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1551:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1552:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1553:                                          $remotesessions,
 1554:                                          $defdomdefaults{'hostedsessions'});
 1555:         }
 1556:     }
 1557:     return $canhost;
 1558: }
 1559: 
 1560: sub this_host_spares {
 1561:     my ($dom) = @_;
 1562:     my ($dom_in_use,$lonhost_in_use,$result);
 1563:     my @hosts = &current_machine_ids();
 1564:     foreach my $lonhost (@hosts) {
 1565:         if (&host_domain($lonhost) eq $dom) {
 1566:             $dom_in_use = $dom;
 1567:             $lonhost_in_use = $lonhost;
 1568:             last;
 1569:         }
 1570:     }
 1571:     if ($dom_in_use ne '') {
 1572:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1573:     }
 1574:     if (ref($result) ne 'HASH') {
 1575:         $lonhost_in_use = $perlvar{'lonHostID'};
 1576:         $dom_in_use = &host_domain($lonhost_in_use);
 1577:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1578:         if (ref($result) ne 'HASH') {
 1579:             $result = \%spareid;
 1580:         }
 1581:     }
 1582:     return $result;
 1583: }
 1584: 
 1585: sub spares_for_offload  {
 1586:     my ($dom_in_use,$lonhost_in_use) = @_;
 1587:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1588:     if (defined($cached)) {
 1589:         return $result;
 1590:     } else {
 1591:         my $cachetime = 60*60*24;
 1592:         my %domconfig =
 1593:             &get_dom('configuration',['usersessions'],$dom_in_use);
 1594:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1595:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1596:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1597:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1598:                 }
 1599:             }
 1600:         }
 1601:     }
 1602:     return;
 1603: }
 1604: 
 1605: sub get_lonbalancer_config {
 1606:     my ($servers) = @_;
 1607:     my ($currbalancer,$currtargets);
 1608:     if (ref($servers) eq 'HASH') {
 1609:         foreach my $server (keys(%{$servers})) {
 1610:             my %what = (
 1611:                          spareid => 1,
 1612:                          perlvar => 1,
 1613:                        );
 1614:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1615:             if ($result eq 'ok') {
 1616:                 if (ref($returnhash) eq 'HASH') {
 1617:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1618:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1619:                             $currbalancer = $server;
 1620:                             $currtargets = {};
 1621:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1622:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1623:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1624:                                 }
 1625:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1626:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1627:                                 }
 1628:                             }
 1629:                             last;
 1630:                         }
 1631:                     }
 1632:                 }
 1633:             }
 1634:         }
 1635:     }
 1636:     return ($currbalancer,$currtargets);
 1637: }
 1638: 
 1639: sub check_loadbalancing {
 1640:     my ($uname,$udom,$caller) = @_;
 1641:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1642:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1643:     my $lonhost = $perlvar{'lonHostID'};
 1644:     my @hosts = &current_machine_ids();
 1645:     my $uprimary_id = &domain($udom,'primary');
 1646:     my $uintdom = &internet_dom($uprimary_id);
 1647:     my $intdom = &internet_dom($lonhost);
 1648:     my $serverhomedom = &host_domain($lonhost);
 1649:     my $domneedscache;
 1650:     my $cachetime = 60*60*24;
 1651: 
 1652:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1653:         $dom_in_use = $udom;
 1654:         $homeintdom = 1;
 1655:     } else {
 1656:         $dom_in_use = $serverhomedom;
 1657:     }
 1658:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1659:     unless (defined($cached)) {
 1660:         my %domconfig =
 1661:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
 1662:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1663:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1664:         } else {
 1665:             $domneedscache = $dom_in_use;
 1666:         }
 1667:     }
 1668:     if (ref($result) eq 'HASH') {
 1669:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1670:             &check_balancer_result($result,@hosts);
 1671:         if ($is_balancer) {
 1672:             if (ref($currrules) eq 'HASH') {
 1673:                 if ($homeintdom) {
 1674:                     if ($uname ne '') {
 1675:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1676:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1677:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1678:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1679:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1680:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1681:                             }
 1682:                         }
 1683:                         if ($rule_in_effect eq '') {
 1684:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1685:                             if ($userenv{'inststatus'} ne '') {
 1686:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1687:                                 my ($othertitle,$usertypes,$types) =
 1688:                                     &Apache::loncommon::sorted_inst_types($udom);
 1689:                                 if (ref($types) eq 'ARRAY') {
 1690:                                     foreach my $type (@{$types}) {
 1691:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1692:                                             if (exists($currrules->{$type})) {
 1693:                                                 $rule_in_effect = $currrules->{$type};
 1694:                                             }
 1695:                                         }
 1696:                                     }
 1697:                                 }
 1698:                             } else {
 1699:                                 if (exists($currrules->{'default'})) {
 1700:                                     $rule_in_effect = $currrules->{'default'};
 1701:                                 }
 1702:                             }
 1703:                         }
 1704:                     } else {
 1705:                         if (exists($currrules->{'default'})) {
 1706:                             $rule_in_effect = $currrules->{'default'};
 1707:                         }
 1708:                     }
 1709:                 } else {
 1710:                     if ($currrules->{'_LC_external'} ne '') {
 1711:                         $rule_in_effect = $currrules->{'_LC_external'};
 1712:                     }
 1713:                 }
 1714:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1715:                                                        $uname,$udom);
 1716:             }
 1717:         }
 1718:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1719:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1720:         unless (defined($cached)) {
 1721:             my %domconfig =
 1722:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
 1723:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1724:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1725:             } else {
 1726:                 $domneedscache = $serverhomedom;
 1727:             }
 1728:         }
 1729:         if (ref($result) eq 'HASH') {
 1730:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1731:                 &check_balancer_result($result,@hosts);
 1732:             if ($is_balancer) {
 1733:                 if (ref($currrules) eq 'HASH') {
 1734:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1735:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1736:                     }
 1737:                 }
 1738:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1739:                                                        $uname,$udom);
 1740:             }
 1741:         } else {
 1742:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1743:                 $is_balancer = 1;
 1744:                 $offloadto = &this_host_spares($dom_in_use);
 1745:             }
 1746:             unless (defined($cached)) {
 1747:                 $domneedscache = $serverhomedom;
 1748:             }
 1749:         }
 1750:     } else {
 1751:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1752:             $is_balancer = 1;
 1753:             $offloadto = &this_host_spares($dom_in_use);
 1754:         }
 1755:         unless (defined($cached)) {
 1756:             $domneedscache = $serverhomedom;
 1757:         }
 1758:     }
 1759:     if ($domneedscache) {
 1760:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1761:     }
 1762:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1763:         my $lowest_load = 30000;
 1764:         if (ref($offloadto) eq 'HASH') {
 1765:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1766:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1767:                     ($otherserver,$lowest_load) =
 1768:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1769:                 }
 1770:             }
 1771:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1772: 
 1773:             if (!$found_server) {
 1774:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1775:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1776:                         ($otherserver,$lowest_load) =
 1777:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1778:                     }
 1779:                 }
 1780:             }
 1781:         } elsif (ref($offloadto) eq 'ARRAY') {
 1782:             if (@{$offloadto} == 1) {
 1783:                 $otherserver = $offloadto->[0];
 1784:             } elsif (@{$offloadto} > 1) {
 1785:                 foreach my $try_server (@{$offloadto}) {
 1786:                     ($otherserver,$lowest_load) =
 1787:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1788:                 }
 1789:             }
 1790:         }
 1791:         unless ($caller eq 'login') {
 1792:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1793:                 $is_balancer = 0;
 1794:                 if ($uname ne '' && $udom ne '') {
 1795:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1796:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1797:                                  'user.loadbalcheck.time' => time});
 1798:                     }
 1799:                 }
 1800:             }
 1801:         }
 1802:     }
 1803:     if (($is_balancer) && (!$homeintdom)) {
 1804:         undef($setcookie);
 1805:     }
 1806:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1807: }
 1808: 
 1809: sub check_balancer_result {
 1810:     my ($result,@hosts) = @_;
 1811:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1812:     if (ref($result) eq 'HASH') {
 1813:         if ($result->{'lonhost'} ne '') {
 1814:             my $currbalancer = $result->{'lonhost'};
 1815:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1816:                 $is_balancer = 1;
 1817:                 $currtargets = $result->{'targets'};
 1818:                 $currrules = $result->{'rules'};
 1819:             }
 1820:             $dom_balancers = $currbalancer;
 1821:         } else {
 1822:             if (keys(%{$result})) {
 1823:                 foreach my $key (keys(%{$result})) {
 1824:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1825:                         (ref($result->{$key}) eq 'HASH')) {
 1826:                         $is_balancer = 1;
 1827:                         $currrules = $result->{$key}{'rules'};
 1828:                         $currtargets = $result->{$key}{'targets'};
 1829:                         $setcookie = $result->{$key}{'cookie'};
 1830:                         last;
 1831:                     }
 1832:                 }
 1833:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1834:             }
 1835:         }
 1836:     }
 1837:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1838: }
 1839: 
 1840: sub get_loadbalancer_targets {
 1841:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1842:     my $offloadto;
 1843:     if ($rule_in_effect eq 'none') {
 1844:         return [$perlvar{'lonHostID'}];
 1845:     } elsif ($rule_in_effect eq '') {
 1846:         $offloadto = $currtargets;
 1847:     } else {
 1848:         if ($rule_in_effect eq 'homeserver') {
 1849:             my $homeserver = &homeserver($uname,$udom);
 1850:             if ($homeserver ne 'no_host') {
 1851:                 $offloadto = [$homeserver];
 1852:             }
 1853:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1854:             my %domconfig =
 1855:                 &get_dom('configuration',['loadbalancing'],$udom);
 1856:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1857:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1858:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1859:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 my %servers = &internet_dom_servers($udom);
 1864:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1865:                 if (&hostname($remotebalancer) ne '') {
 1866:                     $offloadto = [$remotebalancer];
 1867:                 }
 1868:             }
 1869:         } elsif (&hostname($rule_in_effect) ne '') {
 1870:             $offloadto = [$rule_in_effect];
 1871:         }
 1872:     }
 1873:     return $offloadto;
 1874: }
 1875: 
 1876: sub internet_dom_servers {
 1877:     my ($dom) = @_;
 1878:     my (%uniqservers,%servers);
 1879:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1880:     my @machinedoms = &machine_domains($primaryserver);
 1881:     foreach my $mdom (@machinedoms) {
 1882:         my %currservers = %servers;
 1883:         my %server = &get_servers($mdom);
 1884:         %servers = (%currservers,%server);
 1885:     }
 1886:     my %by_hostname;
 1887:     foreach my $id (keys(%servers)) {
 1888:         push(@{$by_hostname{$servers{$id}}},$id);
 1889:     }
 1890:     foreach my $hostname (sort(keys(%by_hostname))) {
 1891:         if (@{$by_hostname{$hostname}} > 1) {
 1892:             my $match = 0;
 1893:             foreach my $id (@{$by_hostname{$hostname}}) {
 1894:                 if (&host_domain($id) eq $dom) {
 1895:                     $uniqservers{$id} = $hostname;
 1896:                     $match = 1;
 1897:                 }
 1898:             }
 1899:             unless ($match) {
 1900:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1901:             }
 1902:         } else {
 1903:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1904:         }
 1905:     }
 1906:     return %uniqservers;
 1907: }
 1908: 
 1909: sub trusted_domains {
 1910:     my ($cmdtype,$calldom) = @_;
 1911:     my ($trusted,$untrusted);
 1912:     if (&domain($calldom) eq '') {
 1913:         return ($trusted,$untrusted);
 1914:     }
 1915:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1916:         return ($trusted,$untrusted);
 1917:     }
 1918:     my $callprimary = &domain($calldom,'primary');
 1919:     my $intcalldom = &internet_dom($callprimary);
 1920:     if ($intcalldom eq '') {
 1921:         return ($trusted,$untrusted);
 1922:     }
 1923: 
 1924:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
 1925:     unless (defined($cached)) {
 1926:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
 1927:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1928:         $trustconfig = $domconfig{'trust'};
 1929:     }
 1930:     if (ref($trustconfig)) {
 1931:         my (%possexc,%possinc,@allexc,@allinc); 
 1932:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1933:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1934:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1935:             }
 1936:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1937:                 $possinc{$intcalldom} = 1;
 1938:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1939:             }
 1940:         }
 1941:         if (keys(%possexc)) {
 1942:             if (keys(%possinc)) {
 1943:                 foreach my $key (sort(keys(%possexc))) {
 1944:                     next if ($key eq $intcalldom);
 1945:                     unless ($possinc{$key}) {
 1946:                         push(@allexc,$key);
 1947:                     }
 1948:                 }
 1949:             } else {
 1950:                 @allexc = sort(keys(%possexc));
 1951:             }
 1952:         }
 1953:         if (keys(%possinc)) {
 1954:             $possinc{$intcalldom} = 1;
 1955:             @allinc = sort(keys(%possinc));
 1956:         }
 1957:         if ((@allexc > 0) || (@allinc > 0)) {
 1958:             my %doms_by_intdom;
 1959:             my %allintdoms = &all_host_intdom();
 1960:             my %alldoms = &all_host_domain();
 1961:             foreach my $key (%allintdoms) {
 1962:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1963:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1964:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1965:                     }
 1966:                 } else {
 1967:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1968:                 }
 1969:             }
 1970:             foreach my $exc (@allexc) {
 1971:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1972:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1973:                 }
 1974:             }
 1975:             foreach my $inc (@allinc) {
 1976:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1977:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1978:                 }
 1979:             }
 1980:         }
 1981:     }
 1982:     return ($trusted,$untrusted);
 1983: }
 1984: 
 1985: sub will_trust {
 1986:     my ($cmdtype,$domain,$possdom) = @_;
 1987:     return 1 if ($domain eq $possdom);
 1988:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1989:     my $willtrust; 
 1990:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1991:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1992:             $willtrust = 1;
 1993:         }
 1994:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1995:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1996:             $willtrust = 1;
 1997:         }
 1998:     } else {
 1999:         $willtrust = 1;
 2000:     }
 2001:     return $willtrust;
 2002: }
 2003: 
 2004: # ---------------------- Find the homebase for a user from domain's lib servers
 2005: 
 2006: my %homecache;
 2007: sub homeserver {
 2008:     my ($uname,$udom,$ignoreBadCache)=@_;
 2009:     my $index="$uname:$udom";
 2010: 
 2011:     if (exists($homecache{$index})) { return $homecache{$index}; }
 2012: 
 2013:     my %servers = &get_servers($udom,'library');
 2014:     foreach my $tryserver (keys(%servers)) {
 2015:         next if ($ignoreBadCache ne 'true' && 
 2016: 		 exists($badServerCache{$tryserver}));
 2017: 
 2018: 	my $answer=reply("home:$udom:$uname",$tryserver);
 2019: 	if ($answer eq 'found') {
 2020: 	    delete($badServerCache{$tryserver}); 
 2021: 	    return $homecache{$index}=$tryserver;
 2022: 	} elsif ($answer eq 'no_host') {
 2023: 	    $badServerCache{$tryserver}=1;
 2024: 	}
 2025:     }    
 2026:     return 'no_host';
 2027: }
 2028: 
 2029: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 2030: 
 2031: sub idget {
 2032:     my ($udom,$idsref,$namespace)=@_;
 2033:     my %returnhash=();
 2034:     my @ids=(); 
 2035:     if (ref($idsref) eq 'ARRAY') {
 2036:         @ids = @{$idsref};
 2037:     } else {
 2038:         return %returnhash; 
 2039:     }
 2040:     if ($namespace eq '') {
 2041:         $namespace = 'ids';
 2042:     }
 2043:     
 2044:     my %servers = &get_servers($udom,'library');
 2045:     foreach my $tryserver (keys(%servers)) {
 2046: 	my $idlist=join('&', map { &escape($_); } @ids);
 2047: 	if ($namespace eq 'ids') {
 2048: 	    $idlist=~tr/A-Z/a-z/;
 2049: 	}
 2050: 	my $reply;
 2051: 	if ($namespace eq 'ids') {
 2052: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 2053: 	} else {
 2054: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 2055: 	}
 2056: 	my @answer=();
 2057: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2058: 	    @answer=split(/\&/,$reply);
 2059: 	}                    ;
 2060: 	my $i;
 2061: 	for ($i=0;$i<=$#ids;$i++) {
 2062: 	    if ($answer[$i]) {
 2063: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2064: 	    }
 2065: 	}
 2066:     }
 2067:     return %returnhash;
 2068: }
 2069: 
 2070: # ------------------------------------- Find the IDs behind a list of usernames
 2071: 
 2072: sub idrget {
 2073:     my ($udom,@unames)=@_;
 2074:     my %returnhash=();
 2075:     foreach my $uname (@unames) {
 2076:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2077:     }
 2078:     return %returnhash;
 2079: }
 2080: 
 2081: # Store away a list of names and associated student/employee IDs or clicker IDs
 2082: 
 2083: sub idput {
 2084:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2085:     my %servers=();
 2086:     my %ids=();
 2087:     my %byid = ();
 2088:     if (ref($idsref) eq 'HASH') {
 2089:         %ids=%{$idsref};
 2090:     }
 2091:     if ($namespace eq '') {
 2092:         $namespace = 'ids'; 
 2093:     }
 2094:     foreach my $uname (keys(%ids)) {
 2095: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2096:         if ($uhom eq '') {
 2097:             $uhom=&homeserver($uname,$udom);
 2098:         }
 2099:         if ($uhom ne 'no_host') {
 2100:             my $esc_unam=&escape($uname);
 2101:             if ($namespace eq 'ids') {
 2102:                 my $id=&escape($ids{$uname});
 2103:                 $id=~tr/A-Z/a-z/;
 2104:                 my $esc_unam=&escape($uname);
 2105:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2106:             } else {
 2107:                 my @currids = split(/,/,$ids{$uname});
 2108:                 foreach my $id (@currids) {
 2109:                     $byid{$uhom}{$id} .= $uname.',';
 2110:                 }
 2111:             }
 2112:         }
 2113:     }
 2114:     if ($namespace eq 'clickers') {
 2115:         foreach my $server (keys(%byid)) {
 2116:             if (ref($byid{$server}) eq 'HASH') {
 2117:                 foreach my $id (keys(%{$byid{$server}})) {
 2118:                     $byid{$server} =~ s/,$//;
 2119:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2120:                 }
 2121:             }
 2122:         }
 2123:     }
 2124:     foreach my $server (keys(%servers)) {
 2125:         $servers{$server} =~ s/\&$//;
 2126:         if ($namespace eq 'ids') {     
 2127:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2128:         } else {
 2129:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2130:         }
 2131:     }
 2132: }
 2133: 
 2134: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2135: 
 2136: sub iddel {
 2137:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2138:     my %result=();
 2139:     my %ids=();
 2140:     my %byid = ();
 2141:     if (ref($idshashref) eq 'HASH') {
 2142:         %ids=%{$idshashref};
 2143:     } else {
 2144:         return %result;
 2145:     }
 2146:     if ($namespace eq '') {
 2147:         $namespace = 'ids';
 2148:     }
 2149:     my %servers=();
 2150:     while (my ($id,$unamestr) = each(%ids)) {
 2151:         if ($namespace eq 'ids') {
 2152:             my $uhom = $uhome;
 2153:             if ($uhom eq '') { 
 2154:                 $uhom=&homeserver($unamestr,$udom);
 2155:             }
 2156:             if ($uhom ne 'no_host') {
 2157:                 $servers{$uhom}.='&'.&escape($id);
 2158:             }
 2159:          } else {
 2160:             my @curritems = split(/,/,$ids{$id});
 2161:             foreach my $uname (@curritems) {
 2162:                 my $uhom = $uhome;
 2163:                 if ($uhom eq '') {
 2164:                     $uhom=&homeserver($uname,$udom);
 2165:                 }
 2166:                 if ($uhom ne 'no_host') { 
 2167:                     $byid{$uhom}{$id} .= $uname.',';
 2168:                 }
 2169:             }
 2170:         }
 2171:     }
 2172:     if ($namespace eq 'clickers') {
 2173:         foreach my $server (keys(%byid)) {
 2174:             if (ref($byid{$server}) eq 'HASH') {
 2175:                 foreach my $id (keys(%{$byid{$server}})) {
 2176:                     $byid{$server}{$id} =~ s/,$//;
 2177:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2178:                 }
 2179:             }
 2180:         }
 2181:     }
 2182:     foreach my $server (keys(%servers)) {
 2183:         $servers{$server} =~ s/\&$//;
 2184:         if ($namespace eq 'ids') {
 2185:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2186:         } elsif ($namespace eq 'clickers') {
 2187:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2188:         }
 2189:     }
 2190:     return %result;
 2191: }
 2192: 
 2193: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2194: 
 2195: sub updateclickers {
 2196:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2197:     my %clickers;
 2198:     if (ref($idshashref) eq 'HASH') {
 2199:         %clickers=%{$idshashref};
 2200:     } else {
 2201:         return;
 2202:     }
 2203:     my $items='';
 2204:     foreach my $item (keys(%clickers)) {
 2205:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2206:     }
 2207:     $items=~s/\&$//;
 2208:     my $request = "updateclickers:$udom:$action:$items";
 2209:     if ($critical) {
 2210:         return &critical($request,$uhome);
 2211:     } else {
 2212:         return &reply($request,$uhome);
 2213:     }
 2214: }
 2215: 
 2216: # ------------------------------dump from db file owned by domainconfig user
 2217: sub dump_dom {
 2218:     my ($namespace, $udom, $regexp) = @_;
 2219: 
 2220:     $udom ||= $env{'user.domain'};
 2221: 
 2222:     return () unless $udom;
 2223: 
 2224:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2225: }
 2226: 
 2227: # ------------------------------------------ get items from domain db files   
 2228: 
 2229: sub get_dom {
 2230:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2231:     return if ($udom eq 'public');
 2232:     my $items='';
 2233:     foreach my $item (@$storearr) {
 2234:         $items.=&escape($item).'&';
 2235:     }
 2236:     $items=~s/\&$//;
 2237:     if (!$udom) {
 2238:         $udom=$env{'user.domain'};
 2239:         return if ($udom eq 'public');
 2240:         if (defined(&domain($udom,'primary'))) {
 2241:             $uhome=&domain($udom,'primary');
 2242:         } else {
 2243:             undef($uhome);
 2244:         }
 2245:     } else {
 2246:         if (!$uhome) {
 2247:             if (defined(&domain($udom,'primary'))) {
 2248:                 $uhome=&domain($udom,'primary');
 2249:             }
 2250:         }
 2251:     }
 2252:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2253:         my $rep;
 2254:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2255:             # domain information is hosted on this machine
 2256:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2257:         } else {
 2258:             if ($encrypt) {
 2259:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2260:             } else {
 2261:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2262:             }
 2263:         }
 2264:         my %returnhash;
 2265:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2266:             return %returnhash;
 2267:         }
 2268:         my @pairs=split(/\&/,$rep);
 2269:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2270:             return @pairs;
 2271:         }
 2272:         my $i=0;
 2273:         foreach my $item (@$storearr) {
 2274:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2275:             $i++;
 2276:         }
 2277:         return %returnhash;
 2278:     } else {
 2279:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2280:     }
 2281: }
 2282: 
 2283: # -------------------------------------------- put items in domain db files 
 2284: 
 2285: sub put_dom {
 2286:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2287:     if (!$udom) {
 2288:         $udom=$env{'user.domain'};
 2289:         if (defined(&domain($udom,'primary'))) {
 2290:             $uhome=&domain($udom,'primary');
 2291:         } else {
 2292:             undef($uhome);
 2293:         }
 2294:     } else {
 2295:         if (!$uhome) {
 2296:             if (defined(&domain($udom,'primary'))) {
 2297:                 $uhome=&domain($udom,'primary');
 2298:             }
 2299:         }
 2300:     } 
 2301:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2302:         my $items='';
 2303:         foreach my $item (keys(%$storehash)) {
 2304:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2305:         }
 2306:         $items=~s/\&$//;
 2307:         if ($encrypt) {
 2308:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2309:         } else {
 2310:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2311:         }
 2312:     } else {
 2313:         &logthis("put_dom failed - no homeserver and/or domain");
 2314:     }
 2315: }
 2316: 
 2317: # --------------------- newput for items in db file owned by domainconfig user
 2318: sub newput_dom {
 2319:     my ($namespace,$storehash,$udom) = @_;
 2320:     my $result;
 2321:     if (!$udom) {
 2322:         $udom=$env{'user.domain'};
 2323:     }
 2324:     if ($udom) {
 2325:         my $uname = &get_domainconfiguser($udom);
 2326:         $result = &newput($namespace,$storehash,$udom,$uname);
 2327:     }
 2328:     return $result;
 2329: }
 2330: 
 2331: # --------------------- delete for items in db file owned by domainconfig user
 2332: sub del_dom {
 2333:     my ($namespace,$storearr,$udom)=@_;
 2334:     if (ref($storearr) eq 'ARRAY') {
 2335:         if (!$udom) {
 2336:             $udom=$env{'user.domain'};
 2337:         }
 2338:         if ($udom) {
 2339:             my $uname = &get_domainconfiguser($udom); 
 2340:             return &del($namespace,$storearr,$udom,$uname);
 2341:         }
 2342:     }
 2343: }
 2344: 
 2345: sub store_dom {
 2346:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2347:     $$storehash{'ip'}=&get_requestor_ip();
 2348:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2349:     my $namevalue='';
 2350:     foreach my $key (keys(%{$storehash})) {
 2351:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2352:     }
 2353:     $namevalue=~s/\&$//;
 2354:     if (grep { $_ eq $home } current_machine_ids()) {
 2355:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2356:     } else {
 2357:         if ($namespace eq 'private') {
 2358:             return 'refused';
 2359:         } elsif ($encrypt) {
 2360:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2361:         } else {
 2362:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2363:         }
 2364:     }
 2365: }
 2366: 
 2367: sub restore_dom {
 2368:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2369:     my $answer;
 2370:     if (grep { $_ eq $home } current_machine_ids()) {
 2371:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2372:     } elsif ($namespace ne 'private') {
 2373:         if ($encrypt) {
 2374:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2375:         } else {
 2376:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2377:         }
 2378:     }
 2379:     my %returnhash=();
 2380:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2381:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2382:         foreach my $line (split(/\&/,$answer)) {
 2383:             my ($name,$value)=split(/\=/,$line);
 2384:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2385:         }
 2386:         my $version;
 2387:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2388:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2389:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2390:             }
 2391:         }
 2392:     }
 2393:     return %returnhash;
 2394: }
 2395: 
 2396: # ----------------------------------construct domainconfig user for a domain 
 2397: sub get_domainconfiguser {
 2398:     my ($udom) = @_;
 2399:     return $udom.'-domainconfig';
 2400: }
 2401: 
 2402: sub retrieve_inst_usertypes {
 2403:     my ($udom) = @_;
 2404:     my (%returnhash,@order);
 2405:     my %domdefs = &get_domain_defaults($udom);
 2406:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2407:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2408:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2409:     } else {
 2410:         if (defined(&domain($udom,'primary'))) {
 2411:             my $uhome=&domain($udom,'primary');
 2412:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2413:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2414:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2415:                 return (\%returnhash,\@order);
 2416:             }
 2417:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2418:             my @pairs=split(/\&/,$hashitems);
 2419:             foreach my $item (@pairs) {
 2420:                 my ($key,$value)=split(/=/,$item,2);
 2421:                 $key = &unescape($key);
 2422:                 next if ($key =~ /^error: 2 /);
 2423:                 $returnhash{$key}=&thaw_unescape($value);
 2424:             }
 2425:             my @esc_order = split(/\&/,$orderitems);
 2426:             foreach my $item (@esc_order) {
 2427:                 push(@order,&unescape($item));
 2428:             }
 2429:         } else {
 2430:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2431:         }
 2432:         return (\%returnhash,\@order);
 2433:     }
 2434: }
 2435: 
 2436: sub is_domainimage {
 2437:     my ($url) = @_;
 2438:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2439:         if (&domain($1) ne '') {
 2440:             return '1';
 2441:         }
 2442:     }
 2443:     return;
 2444: }
 2445: 
 2446: sub inst_directory_query {
 2447:     my ($srch) = @_;
 2448:     my $udom = $srch->{'srchdomain'};
 2449:     my %results;
 2450:     my $homeserver = &domain($udom,'primary');
 2451:     my $outcome;
 2452:     if ($homeserver ne '') {
 2453:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2454:             if ($srch->{'srchby'} eq 'email') {
 2455:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2456:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2457:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2458:                     (($major == 2) && ($minor < 12))) {
 2459:                     return;
 2460:                 }
 2461:             }
 2462:         }
 2463: 	my $queryid=&reply("querysend:instdirsearch:".
 2464: 			   &escape($srch->{'srchby'}).':'.
 2465: 			   &escape($srch->{'srchterm'}).':'.
 2466: 			   &escape($srch->{'srchtype'}),$homeserver);
 2467: 	my $host=&hostname($homeserver);
 2468: 	if ($queryid !~/^\Q$host\E\_/) {
 2469: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2470: 	    return;
 2471: 	}
 2472: 	my $response = &get_query_reply($queryid);
 2473: 	my $maxtries = 5;
 2474: 	my $tries = 1;
 2475: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2476: 	    $response = &get_query_reply($queryid);
 2477: 	    $tries ++;
 2478: 	}
 2479: 
 2480:         if (!&error($response) && $response ne 'refused') {
 2481:             if ($response eq 'unavailable') {
 2482:                 $outcome = $response;
 2483:             } else {
 2484:                 $outcome = 'ok';
 2485:                 my @matches = split(/\n/,$response);
 2486:                 foreach my $match (@matches) {
 2487:                     my ($key,$value) = split(/=/,$match);
 2488:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2489:                 }
 2490:             }
 2491:         }
 2492:     }
 2493:     return ($outcome,%results);
 2494: }
 2495: 
 2496: sub usersearch {
 2497:     my ($srch) = @_;
 2498:     my $dom = $srch->{'srchdomain'};
 2499:     my %results;
 2500:     my %libserv = &all_library();
 2501:     my $query = 'usersearch';
 2502:     foreach my $tryserver (keys(%libserv)) {
 2503:         if (&host_domain($tryserver) eq $dom) {
 2504:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2505:                 if ($srch->{'srchby'} eq 'email') {
 2506:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2507:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2508:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2509:                              (($major == 2) && ($minor < 12)));
 2510:                 }
 2511:             }
 2512:             my $host=&hostname($tryserver);
 2513:             my $queryid=
 2514:                 &reply("querysend:".&escape($query).':'.
 2515:                        &escape($srch->{'srchby'}).':'.
 2516:                        &escape($srch->{'srchtype'}).':'.
 2517:                        &escape($srch->{'srchterm'}),$tryserver);
 2518:             if ($queryid !~/^\Q$host\E\_/) {
 2519:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2520:                 next;
 2521:             }
 2522:             my $reply = &get_query_reply($queryid);
 2523:             my $maxtries = 1;
 2524:             my $tries = 1;
 2525:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2526:                 $reply = &get_query_reply($queryid);
 2527:                 $tries ++;
 2528:             }
 2529:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2530:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2531:             } else {
 2532:                 my @matches;
 2533:                 if ($reply =~ /\n/) {
 2534:                     @matches = split(/\n/,$reply);
 2535:                 } else {
 2536:                     @matches = split(/\&/,$reply);
 2537:                 }
 2538:                 foreach my $match (@matches) {
 2539:                     my ($uname,$udom,%userhash);
 2540:                     foreach my $entry (split(/:/,$match)) {
 2541:                         my ($key,$value) =
 2542:                             map {&unescape($_);} split(/=/,$entry);
 2543:                         $userhash{$key} = $value;
 2544:                         if ($key eq 'username') {
 2545:                             $uname = $value;
 2546:                         } elsif ($key eq 'domain') {
 2547:                             $udom = $value;
 2548:                         }
 2549:                     }
 2550:                     $results{$uname.':'.$udom} = \%userhash;
 2551:                 }
 2552:             }
 2553:         }
 2554:     }
 2555:     return %results;
 2556: }
 2557: 
 2558: sub get_instuser {
 2559:     my ($udom,$uname,$id) = @_;
 2560:     my $homeserver = &domain($udom,'primary');
 2561:     my ($outcome,%results);
 2562:     if ($homeserver ne '') {
 2563:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2564:                            &escape($id).':'.&escape($udom),$homeserver);
 2565:         my $host=&hostname($homeserver);
 2566:         if ($queryid !~/^\Q$host\E\_/) {
 2567:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2568:             return;
 2569:         }
 2570:         my $response = &get_query_reply($queryid);
 2571:         my $maxtries = 5;
 2572:         my $tries = 1;
 2573:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2574:             $response = &get_query_reply($queryid);
 2575:             $tries ++;
 2576:         }
 2577:         if (!&error($response) && $response ne 'refused') {
 2578:             if ($response eq 'unavailable') {
 2579:                 $outcome = $response;
 2580:             } else {
 2581:                 $outcome = 'ok';
 2582:                 my @matches = split(/\n/,$response);
 2583:                 foreach my $match (@matches) {
 2584:                     my ($key,$value) = split(/=/,$match);
 2585:                     $results{&unescape($key)} = &thaw_unescape($value);
 2586:                 }
 2587:             }
 2588:         }
 2589:     }
 2590:     my %userinfo;
 2591:     if (ref($results{$uname}) eq 'HASH') {
 2592:         %userinfo = %{$results{$uname}};
 2593:     } 
 2594:     return ($outcome,%userinfo);
 2595: }
 2596: 
 2597: sub get_multiple_instusers {
 2598:     my ($udom,$users,$caller) = @_;
 2599:     my ($outcome,$results);
 2600:     if (ref($users) eq 'HASH') {
 2601:         my $count = keys(%{$users}); 
 2602:         my $requested = &freeze_escape($users);
 2603:         my $homeserver = &domain($udom,'primary');
 2604:         if ($homeserver ne '') {
 2605:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2606:             my $host=&hostname($homeserver);
 2607:             if ($queryid !~/^\Q$host\E\_/) {
 2608:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2609:                          ' for host: '.$homeserver.'in domain '.$udom);
 2610:                 return ($outcome,$results);
 2611:             }
 2612:             my $response = &get_query_reply($queryid);
 2613:             my $maxtries = 5;
 2614:             if ($count > 100) {
 2615:                 $maxtries = 1+int($count/20);
 2616:             }
 2617:             my $tries = 1;
 2618:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2619:                 $response = &get_query_reply($queryid);
 2620:                 $tries ++;
 2621:             }
 2622:             if ($response eq '') {
 2623:                 $results = {};
 2624:                 foreach my $key (keys(%{$users})) {
 2625:                     my ($uname,$id);
 2626:                     if ($caller eq 'id') {
 2627:                         $id = $key;
 2628:                     } else {
 2629:                         $uname = $key;
 2630:                     }
 2631:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2632:                     $outcome = $resp;
 2633:                     if ($resp eq 'ok') {
 2634:                         %{$results} = (%{$results}, %info);
 2635:                     } else {
 2636:                         last;
 2637:                     }
 2638:                 }
 2639:             } elsif(!&error($response) && ($response ne 'refused')) {
 2640:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2641:                     $outcome = $response;
 2642:                 } else {
 2643:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2644:                     if ($outcome eq 'ok') {
 2645:                         $results = &thaw_unescape($userdata); 
 2646:                     }
 2647:                 }
 2648:             }
 2649:         }
 2650:     }
 2651:     return ($outcome,$results);
 2652: }
 2653: 
 2654: sub inst_rulecheck {
 2655:     my ($udom,$uname,$id,$item,$rules) = @_;
 2656:     my %returnhash;
 2657:     if ($udom ne '') {
 2658:         if (ref($rules) eq 'ARRAY') {
 2659:             @{$rules} = map {&escape($_);} (@{$rules});
 2660:             my $rulestr = join(':',@{$rules});
 2661:             my $homeserver=&domain($udom,'primary');
 2662:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2663:                 my $response;
 2664:                 if ($item eq 'username') {                
 2665:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2666:                                               ':'.&escape($uname).':'.$rulestr,
 2667:                                               $homeserver));
 2668:                 } elsif ($item eq 'id') {
 2669:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2670:                                               ':'.&escape($id).':'.$rulestr,
 2671:                                               $homeserver));
 2672:                 } elsif ($item eq 'selfcreate') {
 2673:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2674:                                                &escape($udom).':'.&escape($uname).
 2675:                                               ':'.$rulestr,$homeserver));
 2676:                 } elsif ($item eq 'unamemap') {
 2677:                     $response=&unescape(&reply('instunamemapcheck:'.
 2678:                                                &escape($udom).':'.&escape($uname).
 2679:                                               ':'.$rulestr,$homeserver));
 2680:                 }
 2681:                 if ($response ne 'refused') {
 2682:                     my @pairs=split(/\&/,$response);
 2683:                     foreach my $item (@pairs) {
 2684:                         my ($key,$value)=split(/=/,$item,2);
 2685:                         $key = &unescape($key);
 2686:                         next if ($key =~ /^error: 2 /);
 2687:                         $returnhash{$key}=&thaw_unescape($value);
 2688:                     }
 2689:                 }
 2690:             }
 2691:         }
 2692:     }
 2693:     return %returnhash;
 2694: }
 2695: 
 2696: sub inst_userrules {
 2697:     my ($udom,$check) = @_;
 2698:     my (%ruleshash,@ruleorder);
 2699:     if ($udom ne '') {
 2700:         my $homeserver=&domain($udom,'primary');
 2701:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2702:             my $response;
 2703:             if ($check eq 'id') {
 2704:                 $response=&reply('instidrules:'.&escape($udom),
 2705:                                  $homeserver);
 2706:             } elsif ($check eq 'email') {
 2707:                 $response=&reply('instemailrules:'.&escape($udom),
 2708:                                  $homeserver);
 2709:             } elsif ($check eq 'unamemap') {
 2710:                 $response=&reply('unamemaprules:'.&escape($udom),
 2711:                                  $homeserver); 
 2712:             } else {
 2713:                 $response=&reply('instuserrules:'.&escape($udom),
 2714:                                  $homeserver);
 2715:             }
 2716:             if (($response ne 'refused') && ($response ne 'error') && 
 2717:                 ($response ne 'unknown_cmd') && 
 2718:                 ($response ne 'no_such_host')) {
 2719:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2720:                 my @pairs=split(/\&/,$hashitems);
 2721:                 foreach my $item (@pairs) {
 2722:                     my ($key,$value)=split(/=/,$item,2);
 2723:                     $key = &unescape($key);
 2724:                     next if ($key =~ /^error: 2 /);
 2725:                     $ruleshash{$key}=&thaw_unescape($value);
 2726:                 }
 2727:                 my @esc_order = split(/\&/,$orderitems);
 2728:                 foreach my $item (@esc_order) {
 2729:                     push(@ruleorder,&unescape($item));
 2730:                 }
 2731:             }
 2732:         }
 2733:     }
 2734:     return (\%ruleshash,\@ruleorder);
 2735: }
 2736: 
 2737: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2738: 
 2739: sub get_domain_defaults {
 2740:     my ($domain,$ignore_cache) = @_;
 2741:     return if (($domain eq '') || ($domain eq 'public'));
 2742:     my $cachetime = 60*60*24;
 2743:     unless ($ignore_cache) {
 2744:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2745:         if (defined($cached)) {
 2746:             if (ref($result) eq 'HASH') {
 2747:                 return %{$result};
 2748:             }
 2749:         }
 2750:     }
 2751:     my %domdefaults;
 2752:     my %domconfig =
 2753:          &get_dom('configuration',['defaults','quotas',
 2754:                                   'requestcourses','inststatus',
 2755:                                   'coursedefaults','usersessions',
 2756:                                   'requestauthor','selfenrollment',
 2757:                                   'coursecategories','ssl','autoenroll',
 2758:                                   'trust','helpsettings','wafproxy',
 2759:                                   'ltisec','toolsec','domexttool',
 2760:                                   'exttool','privacy'],$domain);
 2761:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2762:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2763:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2764:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2765:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2766:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2767:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2768:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2769:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2770:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2771:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2772:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2773:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2774:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2775:     } else {
 2776:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2777:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2778:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2779:     }
 2780:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2781:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2782:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2783:         } else {
 2784:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2785:         }
 2786:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2787:         foreach my $item (@usertools) {
 2788:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2789:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2790:             }
 2791:         }
 2792:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2793:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2794:         }
 2795:     }
 2796:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2797:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2798:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2799:         }
 2800:     }
 2801:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2802:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2803:     }
 2804:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2805:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2806:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2807:         }
 2808:     }
 2809:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2810:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2811:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2812:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2813:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2814:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2815:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2816:         }
 2817:         foreach my $type (@coursetypes) {
 2818:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2819:                 unless ($type eq 'community') {
 2820:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2821:                 }
 2822:             }
 2823:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2824:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2825:             }
 2826:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
 2827:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
 2828:             }
 2829:             if ($domdefaults{'postsubmit'} eq 'on') {
 2830:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2831:                     $domdefaults{$type.'postsubtimeout'} = 
 2832:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2833:                 }
 2834:             }
 2835:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2836:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2837:             } else {
 2838:                 $domdefaults{$type.'domexttool'} = 1;
 2839:             }
 2840:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2841:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2842:             } else {
 2843:                 $domdefaults{$type.'exttool'} = 0;
 2844:             }
 2845:         }
 2846:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2847:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2848:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2849:                 if (@clonecodes) {
 2850:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2851:                 }
 2852:             }
 2853:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2854:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2855:         }
 2856:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2857:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2858:         }
 2859:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2860:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2861:         }
 2862:     }
 2863:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2864:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2865:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2866:         }
 2867:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2868:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2869:         }
 2870:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2871:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2872:         }
 2873:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2874:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2875:         }
 2876:     }
 2877:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2878:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2879:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2880:                             'approval','limit');
 2881:             foreach my $type (@coursetypes) {
 2882:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2883:                     my @mgrdc = ();
 2884:                     foreach my $item (@settings) {
 2885:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2886:                             push(@mgrdc,$item);
 2887:                         }
 2888:                     }
 2889:                     if (@mgrdc) {
 2890:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2891:                     }
 2892:                 }
 2893:             }
 2894:         }
 2895:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2896:             foreach my $type (@coursetypes) {
 2897:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2898:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2899:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2900:                     }
 2901:                 }
 2902:             }
 2903:         }
 2904:     }
 2905:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2906:         $domdefaults{'catauth'} = 'std';
 2907:         $domdefaults{'catunauth'} = 'std';
 2908:         if ($domconfig{'coursecategories'}{'auth'}) {
 2909:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2910:         }
 2911:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2912:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2913:         }
 2914:     }
 2915:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2916:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2917:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2918:         }
 2919:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2920:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2921:         }
 2922:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2923:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2924:         }
 2925:     }
 2926:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2927:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2928:         foreach my $prefix (@prefixes) {
 2929:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2930:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2931:             }
 2932:         }
 2933:     }
 2934:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2935:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2936:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2937:     }
 2938:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2939:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2940:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2941:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2942:         }
 2943:     }
 2944:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2945:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2946:             if ($domconfig{'wafproxy'}{$item}) {
 2947:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2948:             }
 2949:         }
 2950:     }
 2951:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2952:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2953:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2954:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2955:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2956:         }
 2957:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2958:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2959:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2960:             }
 2961:         }
 2962:     }
 2963:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2964:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2965:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2966:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2967:         }
 2968:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2969:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2970:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2971:             }
 2972:         }
 2973:     }
 2974:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 2975:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 2976:             foreach my $domtype ('instdom','extdom') {
 2977:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 2978:                     foreach my $roletype ('domain','author','course','community') {
 2979:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 2980:                             $domdefaults{'userapprovals'} = 1;
 2981:                             last;
 2982:                         }
 2983:                     }
 2984:                 }
 2985:                 last if ($domdefaults{'userapprovals'});
 2986:             }
 2987:         }
 2988:     }
 2989:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2990:     return %domdefaults;
 2991: }
 2992: 
 2993: sub get_dom_cats {
 2994:     my ($dom) = @_;
 2995:     return unless (&domain($dom));
 2996:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2997:     unless (defined($cached)) {
 2998:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2999:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 3000:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 3001:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 3002:             } else {
 3003:                 $cats = {};
 3004:             }
 3005:         } else {
 3006:             $cats = {};
 3007:         }
 3008:         &do_cache_new('cats',$dom,$cats,3600);
 3009:     }
 3010:     return $cats;
 3011: }
 3012: 
 3013: sub get_dom_instcats {
 3014:     my ($dom) = @_;
 3015:     return unless (&domain($dom));
 3016:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3017:     unless (defined($cached)) {
 3018:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3019:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3020:         if ($totcodes > 0) {
 3021:             my $caller = 'global';
 3022:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3023:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3024:                 $instcats = {
 3025:                                 totcodes => $totcodes,
 3026:                                 codes => \%codes,
 3027:                                 codetitles => \@codetitles,
 3028:                                 cat_titles => \%cat_titles,
 3029:                                 cat_order => \%cat_order,
 3030:                             };
 3031:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3032:             }
 3033:         }
 3034:     }
 3035:     return $instcats;
 3036: }
 3037: 
 3038: sub retrieve_instcodes {
 3039:     my ($coursecodes,$dom) = @_;
 3040:     my $totcodes;
 3041:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3042:     foreach my $course (keys(%courses)) {
 3043:         if (ref($courses{$course}) eq 'HASH') {
 3044:             if ($courses{$course}{'inst_code'} ne '') {
 3045:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3046:                 $totcodes ++;
 3047:             }
 3048:         }
 3049:     }
 3050:     return $totcodes;
 3051: }
 3052: 
 3053: sub course_portal_url {
 3054:     my ($cnum,$cdom,$r) = @_;
 3055:     my $chome = &homeserver($cnum,$cdom);
 3056:     my $hostname = &hostname($chome);
 3057:     my $protocol = $protocol{$chome};
 3058:     $protocol = 'http' if ($protocol ne 'https');
 3059:     my %domdefaults = &get_domain_defaults($cdom);
 3060:     my $firsturl;
 3061:     if ($domdefaults{'portal_def'}) {
 3062:         $firsturl = $domdefaults{'portal_def'};
 3063:     } else {
 3064:         my $alias = &use_proxy_alias($r,$chome);
 3065:         $hostname = $alias if ($alias ne '');
 3066:         $firsturl = $protocol.'://'.$hostname;
 3067:     }
 3068:     return $firsturl;
 3069: }
 3070: 
 3071: sub url_prefix {
 3072:     my ($r,$dom,$home,$context) = @_;
 3073:     my $prefix;
 3074:     my %domdefs = &get_domain_defaults($dom);
 3075:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3076:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3077:             $prefix = $1;
 3078:         }
 3079:     }
 3080:     if ($prefix eq '') {
 3081:         my $hostname = &hostname($home);
 3082:         my $protocol = $protocol{$home};
 3083:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3084:         my $alias = &use_proxy_alias($r,$home);
 3085:         $hostname = $alias if ($alias ne '');
 3086:         $prefix = $protocol.'://'.$hostname;
 3087:     }
 3088:     return $prefix;
 3089: }
 3090: 
 3091: # --------------------------------------------- Get domain config for passwords
 3092: 
 3093: sub get_passwdconf {
 3094:     my ($dom) = @_;
 3095:     my (%passwdconf,$gotconf,$lookup);
 3096:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3097:     if (defined($cached)) {
 3098:         if (ref($result) eq 'HASH') {
 3099:             %passwdconf = %{$result};
 3100:             $gotconf = 1;
 3101:         }
 3102:     }
 3103:     unless ($gotconf) {
 3104:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3105:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3106:             %passwdconf = %{$domconfig{'passwords'}};
 3107:         }
 3108:         my $cachetime = 24*60*60;
 3109:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3110:     }
 3111:     return %passwdconf;
 3112: }
 3113: 
 3114: # --------------------------------------------------- Assign a key to a student
 3115: 
 3116: sub assign_access_key {
 3117: #
 3118: # a valid key looks like uname:udom#comments
 3119: # comments are being appended
 3120: #
 3121:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3122:     $kdom=
 3123:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3124:     $knum=
 3125:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3126:     $cdom=
 3127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3128:     $cnum=
 3129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3130:     $udom=$env{'user.name'} unless (defined($udom));
 3131:     $uname=$env{'user.domain'} unless (defined($uname));
 3132:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3133:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3134:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3135:                                                   # assigned to this person
 3136:                                                   # - this should not happen,
 3137:                                                   # unless something went wrong
 3138:                                                   # the first time around
 3139: # ready to assign
 3140:         $logentry=$1.'; '.$logentry;
 3141:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3142:                                                  $kdom,$knum) eq 'ok') {
 3143: # key now belongs to user
 3144: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3145:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3146:                 &appenv({'environment.'.$envkey => $ckey});
 3147:                 return 'ok';
 3148:             } else {
 3149:                 return 
 3150:   'error: Count not permanently assign key, will need to be re-entered later.';
 3151: 	    }
 3152:         } else {
 3153:             return 'error: Could not assign key, try again later.';
 3154:         }
 3155:     } elsif (!$existing{$ckey}) {
 3156: # the key does not exist
 3157: 	return 'error: The key does not exist';
 3158:     } else {
 3159: # the key is somebody else's
 3160: 	return 'error: The key is already in use';
 3161:     }
 3162: }
 3163: 
 3164: # ------------------------------------------ put an additional comment on a key
 3165: 
 3166: sub comment_access_key {
 3167: #
 3168: # a valid key looks like uname:udom#comments
 3169: # comments are being appended
 3170: #
 3171:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3172:     $cdom=
 3173:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3174:     $cnum=
 3175:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3176:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3177:     if ($existing{$ckey}) {
 3178:         $existing{$ckey}.='; '.$logentry;
 3179: # ready to assign
 3180:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3181:                                                  $cdom,$cnum) eq 'ok') {
 3182: 	    return 'ok';
 3183:         } else {
 3184: 	    return 'error: Count not store comment.';
 3185:         }
 3186:     } else {
 3187: # the key does not exist
 3188: 	return 'error: The key does not exist';
 3189:     }
 3190: }
 3191: 
 3192: # ------------------------------------------------------ Generate a set of keys
 3193: 
 3194: sub generate_access_keys {
 3195:     my ($number,$cdom,$cnum,$logentry)=@_;
 3196:     $cdom=
 3197:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3198:     $cnum=
 3199:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3200:     unless (&allowed('mky',$cdom)) { return 0; }
 3201:     unless (($cdom) && ($cnum)) { return 0; }
 3202:     if ($number>10000) { return 0; }
 3203:     sleep(2); # make sure don't get same seed twice
 3204:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3205:     my $total=0;
 3206:     for (my $i=1;$i<=$number;$i++) {
 3207:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3208:                   sprintf("%lx",int(100000*rand)).'-'.
 3209:                   sprintf("%lx",int(100000*rand));
 3210:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3211:        $newkey=~s/0/h/g; # and also 0 and O
 3212:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3213:        if ($existing{$newkey}) {
 3214:            $i--;
 3215:        } else {
 3216: 	  if (&put('accesskeys',
 3217:               { $newkey => '# generated '.localtime().
 3218:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3219:                            '; '.$logentry },
 3220: 		   $cdom,$cnum) eq 'ok') {
 3221:               $total++;
 3222: 	  }
 3223:        }
 3224:     }
 3225:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3226:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3227:     return $total;
 3228: }
 3229: 
 3230: # ------------------------------------------------------- Validate an accesskey
 3231: 
 3232: sub validate_access_key {
 3233:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3234:     $cdom=
 3235:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3236:     $cnum=
 3237:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3238:     $udom=$env{'user.domain'} unless (defined($udom));
 3239:     $uname=$env{'user.name'} unless (defined($uname));
 3240:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3241:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3242: }
 3243: 
 3244: # ------------------------------------- Find the section of student in a course
 3245: sub devalidate_getsection_cache {
 3246:     my ($udom,$unam,$courseid)=@_;
 3247:     my $hashid="$udom:$unam:$courseid";
 3248:     &devalidate_cache_new('getsection',$hashid);
 3249: }
 3250: 
 3251: sub courseid_to_courseurl {
 3252:     my ($courseid) = @_;
 3253:     #already url style courseid
 3254:     return $courseid if ($courseid =~ m{^/});
 3255: 
 3256:     if (exists($env{'course.'.$courseid.'.num'})) {
 3257: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3258: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3259: 	return "/$cdom/$cnum";
 3260:     }
 3261: 
 3262:     my %courseinfo=&coursedescription($courseid);
 3263:     if (exists($courseinfo{'num'})) {
 3264: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3265:     }
 3266: 
 3267:     return undef;
 3268: }
 3269: 
 3270: sub getsection {
 3271:     my ($udom,$unam,$courseid)=@_;
 3272:     my $cachetime=1800;
 3273: 
 3274:     my $hashid="$udom:$unam:$courseid";
 3275:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3276:     if (defined($cached)) { return $result; }
 3277: 
 3278:     my %Pending; 
 3279:     my %Expired;
 3280:     #
 3281:     # Each role can either have not started yet (pending), be active, 
 3282:     #    or have expired.
 3283:     #
 3284:     # If there is an active role, we are done.
 3285:     #
 3286:     # If there is more than one role which has not started yet, 
 3287:     #     choose the one which will start sooner
 3288:     # If there is one role which has not started yet, return it.
 3289:     #
 3290:     # If there is more than one expired role, choose the one which ended last.
 3291:     # If there is a role which has expired, return it.
 3292:     #
 3293:     $courseid = &courseid_to_courseurl($courseid);
 3294:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3295:     foreach my $key (keys(%roleshash)) {
 3296:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3297:         my $section=$1;
 3298:         if ($key eq $courseid.'_st') { $section=''; }
 3299:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3300:         my $now=time;
 3301:         if (defined($end) && $end && ($now > $end)) {
 3302:             $Expired{$end}=$section;
 3303:             next;
 3304:         }
 3305:         if (defined($start) && $start && ($now < $start)) {
 3306:             $Pending{$start}=$section;
 3307:             next;
 3308:         }
 3309:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3310:     }
 3311:     #
 3312:     # Presumedly there will be few matching roles from the above
 3313:     # loop and the sorting time will be negligible.
 3314:     if (scalar(keys(%Pending))) {
 3315:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3316:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3317:     } 
 3318:     if (scalar(keys(%Expired))) {
 3319:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3320:         my $time = pop(@sorted);
 3321:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3322:     }
 3323:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3324: }
 3325: 
 3326: sub save_cache {
 3327:     &purge_remembered();
 3328:     #&Apache::loncommon::validate_page();
 3329:     undef(%env);
 3330:     undef($env_loaded);
 3331: }
 3332: 
 3333: my $to_remember=-1;
 3334: my %remembered;
 3335: my %accessed;
 3336: my $kicks=0;
 3337: my $hits=0;
 3338: sub make_key {
 3339:     my ($name,$id) = @_;
 3340:     if (length($id) > 65 
 3341: 	&& length(&escape($id)) > 200) {
 3342: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3343:     }
 3344:     return &escape($name.':'.$id);
 3345: }
 3346: 
 3347: sub devalidate_cache_new {
 3348:     my ($name,$id,$debug) = @_;
 3349:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3350:     my $remembered_id=$name.':'.$id;
 3351:     $id=&make_key($name,$id);
 3352:     $memcache->delete($id);
 3353:     delete($remembered{$remembered_id});
 3354:     delete($accessed{$remembered_id});
 3355: }
 3356: 
 3357: sub is_cached_new {
 3358:     my ($name,$id,$debug) = @_;
 3359:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3360:     if (exists($remembered{$remembered_id})) {
 3361: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3362: 	$accessed{$remembered_id}=[&gettimeofday()];
 3363: 	$hits++;
 3364: 	return ($remembered{$remembered_id},1);
 3365:     }
 3366:     $id=&make_key($name,$id);
 3367:     my $value = $memcache->get($id);
 3368:     if (!(defined($value))) {
 3369: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3370: 	return (undef,undef);
 3371:     }
 3372:     if ($value eq '__undef__') {
 3373: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3374: 	$value=undef;
 3375:     }
 3376:     &make_room($remembered_id,$value,$debug);
 3377:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3378:     return ($value,1);
 3379: }
 3380: 
 3381: sub do_cache_new {
 3382:     my ($name,$id,$value,$time,$debug) = @_;
 3383:     my $remembered_id=$name.':'.$id;
 3384:     $id=&make_key($name,$id);
 3385:     my $setvalue=$value;
 3386:     if (!defined($setvalue)) {
 3387: 	$setvalue='__undef__';
 3388:     }
 3389:     if (!defined($time) ) {
 3390: 	$time=600;
 3391:     }
 3392:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3393:     my $result = $memcache->set($id,$setvalue,$time);
 3394:     if (! $result) {
 3395: 	&logthis("caching of id -> $id  failed");
 3396: 	$memcache->disconnect_all();
 3397:     }
 3398:     # need to make a copy of $value
 3399:     &make_room($remembered_id,$value,$debug);
 3400:     return $value;
 3401: }
 3402: 
 3403: sub make_room {
 3404:     my ($remembered_id,$value,$debug)=@_;
 3405: 
 3406:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3407:                                     : $value;
 3408:     if ($to_remember<0) { return; }
 3409:     $accessed{$remembered_id}=[&gettimeofday()];
 3410:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3411:     my $to_kick;
 3412:     my $max_time=0;
 3413:     foreach my $other (keys(%accessed)) {
 3414: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3415: 	    $to_kick=$other;
 3416: 	    $max_time=&tv_interval($accessed{$other});
 3417: 	}
 3418:     }
 3419:     delete($remembered{$to_kick});
 3420:     delete($accessed{$to_kick});
 3421:     $kicks++;
 3422:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3423:     return;
 3424: }
 3425: 
 3426: sub purge_remembered {
 3427:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3428:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3429:     undef(%remembered);
 3430:     undef(%accessed);
 3431: }
 3432: # ------------------------------------- Read an entry from a user's environment
 3433: 
 3434: sub userenvironment {
 3435:     my ($udom,$unam,@what)=@_;
 3436:     my $items;
 3437:     foreach my $item (@what) {
 3438:         $items.=&escape($item).'&';
 3439:     }
 3440:     $items=~s/\&$//;
 3441:     my %returnhash=();
 3442:     my $uhome = &homeserver($unam,$udom);
 3443:     unless ($uhome eq 'no_host') {
 3444:         my @answer=split(/\&/, 
 3445:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3446:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3447:             return %returnhash;
 3448:         }
 3449:         my $i;
 3450:         for ($i=0;$i<=$#what;$i++) {
 3451: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3452:         }
 3453:     }
 3454:     return %returnhash;
 3455: }
 3456: 
 3457: # ---------------------------------------------------------- Get a studentphoto
 3458: sub studentphoto {
 3459:     my ($udom,$unam,$ext) = @_;
 3460:     my $home=&homeserver($unam,$udom);
 3461:     if (defined($env{'request.course.id'})) {
 3462:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3463:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3464:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3465:             } else {
 3466:                 my ($result,$perm_reqd)=
 3467: 		    &auto_photo_permission($unam,$udom);
 3468:                 if ($result eq 'ok') {
 3469:                     if (!($perm_reqd eq 'yes')) {
 3470:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3471:                     }
 3472:                 }
 3473:             }
 3474:         }
 3475:     } else {
 3476:         my ($result,$perm_reqd) = 
 3477: 	    &auto_photo_permission($unam,$udom);
 3478:         if ($result eq 'ok') {
 3479:             if (!($perm_reqd eq 'yes')) {
 3480:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3481:             }
 3482:         }
 3483:     }
 3484:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3485: }
 3486: 
 3487: sub retrievestudentphoto {
 3488:     my ($udom,$unam,$ext,$type) = @_;
 3489:     my $home=&homeserver($unam,$udom);
 3490:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3491:     if ($ret eq 'ok') {
 3492:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3493:         if ($type eq 'thumbnail') {
 3494:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3495:         }
 3496:         my $tokenurl=&tokenwrapper($url);
 3497:         return $tokenurl;
 3498:     } else {
 3499:         if ($type eq 'thumbnail') {
 3500:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3501:         } else { 
 3502:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3503:         }
 3504:     }
 3505: }
 3506: 
 3507: # -------------------------------------------------------------------- New chat
 3508: 
 3509: sub chatsend {
 3510:     my ($newentry,$anon,$group)=@_;
 3511:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3512:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3513:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3514:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3515: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3516: 		   &escape($newentry)).':'.$group,$chome);
 3517: }
 3518: 
 3519: # ------------------------------------------ Find current version of a resource
 3520: 
 3521: sub getversion {
 3522:     my $fname=&clutter(shift);
 3523:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3524:     return &currentversion(&filelocation('',$fname));
 3525: }
 3526: 
 3527: sub currentversion {
 3528:     my $fname=shift;
 3529:     my $author=$fname;
 3530:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3531:     my ($udom,$uname)=split(/\//,$author);
 3532:     my $home=&homeserver($uname,$udom);
 3533:     if ($home eq 'no_host') { 
 3534:         return -1; 
 3535:     }
 3536:     my $answer=&reply("currentversion:$fname",$home);
 3537:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3538: 	return -1;
 3539:     }
 3540:     return $answer;
 3541: }
 3542: 
 3543: #
 3544: # Return special version number of resource if set by override, empty otherwise
 3545: #
 3546: sub usedversion {
 3547:     my $fname=shift;
 3548:     unless ($fname) { $fname=$env{'request.uri'}; }
 3549:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3550:     if ($urlversion) { return $urlversion; }
 3551:     return '';
 3552: }
 3553: 
 3554: # ----------------------------- Subscribe to a resource, return URL if possible
 3555: 
 3556: sub subscribe {
 3557:     my $fname=shift;
 3558:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3559:     $fname=~s/[\n\r]//g;
 3560:     my $author=$fname;
 3561:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3562:     my ($udom,$uname)=split(/\//,$author);
 3563:     my $home=homeserver($uname,$udom);
 3564:     if ($home eq 'no_host') {
 3565:         return 'not_found';
 3566:     }
 3567:     my $answer=reply("sub:$fname",$home);
 3568:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3569: 	$answer.=' by '.$home;
 3570:     }
 3571:     return $answer;
 3572: }
 3573:     
 3574: # -------------------------------------------------------------- Replicate file
 3575: 
 3576: sub repcopy {
 3577:     my $filename=shift;
 3578:     $filename=~s/\/+/\//g;
 3579:     my $londocroot = $perlvar{'lonDocRoot'};
 3580:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3581:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3582:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3583: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3584: 	return &repcopy_userfile($filename);
 3585:     }
 3586:     $filename=~s/[\n\r]//g;
 3587:     my $transname="$filename.in.transfer";
 3588: # FIXME: this should flock
 3589:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3590:     my $remoteurl=subscribe($filename);
 3591:     if ($remoteurl =~ /^con_lost by/) {
 3592: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3593:            return 'unavailable';
 3594:     } elsif ($remoteurl eq 'not_found') {
 3595: 	   #&logthis("Subscribe returned not_found: $filename");
 3596: 	   return 'not_found';
 3597:     } elsif ($remoteurl =~ /^rejected by/) {
 3598: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3599:            return 'forbidden';
 3600:     } elsif ($remoteurl eq 'directory') {
 3601:            return 'ok';
 3602:     } else {
 3603:         my $author=$filename;
 3604:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3605:         my ($udom,$uname)=split(/\//,$author);
 3606:         my $home=homeserver($uname,$udom);
 3607:         unless ($home eq $perlvar{'lonHostID'}) {
 3608:            my @parts=split(/\//,$filename);
 3609:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3610:            if ($path ne "$londocroot/res") {
 3611:                &logthis("Malconfiguration for replication: $filename");
 3612: 	       return 'bad_request';
 3613:            }
 3614:            my $count;
 3615:            for ($count=5;$count<$#parts;$count++) {
 3616:                $path.="/$parts[$count]";
 3617:                if ((-e $path)!=1) {
 3618: 		   mkdir($path,0777);
 3619:                }
 3620:            }
 3621:            my $request=new HTTP::Request('GET',"$remoteurl");
 3622:            my $response;
 3623:            if ($remoteurl =~ m{/raw/}) {
 3624:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3625:            } else {
 3626:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3627:            }
 3628:            if ($response->is_error()) {
 3629: 	       unlink($transname);
 3630:                my $message=$response->status_line;
 3631:                &logthis("<font color=\"blue\">WARNING:"
 3632:                        ." LWP get: $message: $filename</font>");
 3633:                return 'unavailable';
 3634:            } else {
 3635: 	       if ($remoteurl!~/\.meta$/) {
 3636:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3637:                   my $mresponse;
 3638:                   if ($remoteurl =~ m{/raw/}) {
 3639:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3640:                   } else {
 3641:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3642:                   }
 3643:                   if ($mresponse->is_error()) {
 3644: 		      unlink($filename.'.meta');
 3645:                       &logthis(
 3646:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3647:                   }
 3648: 	       }
 3649:                rename($transname,$filename);
 3650:                return 'ok';
 3651:            }
 3652:        }
 3653:     }
 3654: }
 3655: 
 3656: # ------------------------------------------------- Unsubscribe from a resource
 3657: 
 3658: sub unsubscribe {
 3659:     my ($fname) = @_;
 3660:     my $answer;
 3661:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3662:     $fname=~s/[\n\r]//g;
 3663:     my $author=$fname;
 3664:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3665:     my ($udom,$uname)=split(/\//,$author);
 3666:     my $home=homeserver($uname,$udom);
 3667:     if ($home eq 'no_host') {
 3668:         $answer = 'no_host';
 3669:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3670:         $answer = 'home';
 3671:     } else {
 3672:         my $defdom = $perlvar{'lonDefDomain'};
 3673:         if (&will_trust('content',$defdom,$udom)) {
 3674:             $answer = reply("unsub:$fname",$home);
 3675:         } else {
 3676:             $answer = 'untrusted';
 3677:         }
 3678:     }
 3679:     return $answer;
 3680: }
 3681: 
 3682: # ------------------------------------------------ Get server side include body
 3683: sub ssi_body {
 3684:     my ($filelink,%form)=@_;
 3685:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3686:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3687:     }
 3688:     my $output='';
 3689:     my $response;
 3690:     if ($filelink=~/^https?\:/) {
 3691:        ($output,$response)=&externalssi($filelink);
 3692:     } else {
 3693:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3694:        $filelink .= 'inhibitmenu=yes';
 3695:        ($output,$response)=&ssi($filelink,%form);
 3696:     }
 3697:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3698:     $output=~s/^.*?\<body[^\>]*\>//si;
 3699:     $output=~s/\<\/body\s*\>.*?$//si;
 3700:     if (wantarray) {
 3701:         return ($output, $response);
 3702:     } else {
 3703:         return $output;
 3704:     }
 3705: }
 3706: 
 3707: # --------------------------------------------------------- Server Side Include
 3708: 
 3709: sub absolute_url {
 3710:     my ($host_name,$unalias,$keep_proto) = @_;
 3711:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3712:     if ($host_name eq '') {
 3713: 	$host_name = $ENV{'SERVER_NAME'};
 3714:     }
 3715:     if ($unalias) {
 3716:         my $alias = &get_proxy_alias();
 3717:         if ($alias eq $host_name) {
 3718:             my $lonhost = $perlvar{'lonHostID'};
 3719:             my $hostname = &hostname($lonhost);
 3720:             my $lcproto; 
 3721:             if (($keep_proto) || ($hostname eq '')) {
 3722:                 $lcproto = $protocol;
 3723:             } else {
 3724:                 $lcproto = $protocol{$lonhost};
 3725:                 $lcproto = 'http' if ($lcproto ne 'https');
 3726:                 $lcproto .= '://';
 3727:             }
 3728:             unless ($hostname eq '') {
 3729:                 return $lcproto.$hostname;
 3730:             }
 3731:         }
 3732:     }
 3733:     return $protocol.$host_name;
 3734: }
 3735: 
 3736: #
 3737: #   Server side include.
 3738: # Parameters:
 3739: #  fn     Possibly encrypted resource name/id.
 3740: #  form   Hash that describes how the rendering should be done
 3741: #         and other things.
 3742: # Returns:
 3743: #   Scalar context: The content of the response.
 3744: #   Array context:  2 element list of the content and the full response object.
 3745: #     
 3746: sub ssi {
 3747: 
 3748:     my ($fn,%form)=@_;
 3749:     my ($host,$request,$response);
 3750:     $host = &absolute_url('',1);
 3751: 
 3752:     $form{'no_update_last_known'}=1;
 3753:     &Apache::lonenc::check_encrypt(\$fn);
 3754:     if (%form) {
 3755:       $request=new HTTP::Request('POST',$host.$fn);
 3756:       $request->content(join('&',map { 
 3757:             my $name = escape($_);
 3758:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3759:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3760:             : &escape($form{$_}) );    
 3761:         } keys(%form)));
 3762:     } else {
 3763:       $request=new HTTP::Request('GET',$host.$fn);
 3764:     }
 3765: 
 3766:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3767:     my $lonhost = $perlvar{'lonHostID'};
 3768:     my $islocal;
 3769:     if (($env{'request.course.id'}) &&
 3770:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3771:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3772:         ($form{'grade_symb'} ne '') &&
 3773:         (&allowed('mgr',$env{'request.course.id'}.
 3774:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3775:         $islocal = 1;
 3776:     }
 3777:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3778:                                              '','','',$islocal);
 3779: 
 3780:     if (wantarray) {
 3781: 	return ($response->content, $response);
 3782:     } else {
 3783: 	return $response->content;
 3784:     }
 3785: }
 3786: 
 3787: sub externalssi {
 3788:     my ($url)=@_;
 3789:     my $request=new HTTP::Request('GET',$url);
 3790:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3791:     if (wantarray) {
 3792:         return ($response->content, $response);
 3793:     } else {
 3794:         return $response->content;
 3795:     }
 3796: }
 3797: 
 3798: 
 3799: # If the local copy of a replicated resource is outdated, trigger a  
 3800: # connection from the homeserver to flush the delayed queue. If no update 
 3801: # happens, remove local copies of outdated resource (and corresponding
 3802: # metadata file).
 3803: 
 3804: sub remove_stale_resfile {
 3805:     my ($url) = @_;
 3806:     my $removed;
 3807:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3808:         my $audom = $1;
 3809:         my $auname = $2;
 3810:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3811:             my $homeserver = &homeserver($auname,$audom);
 3812:             unless (($homeserver eq 'no_host') ||
 3813:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3814:                 my $fname = &filelocation('',$url);
 3815:                 if (-e $fname) {
 3816:                     my $hostname = &hostname($homeserver);
 3817:                     if ($hostname) {
 3818:                         my $protocol = $protocol{$homeserver};
 3819:                         $protocol = 'http' if ($protocol ne 'https');
 3820:                         my $uri = &declutter($url);
 3821:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3822:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3823:                         if ($response->is_success()) {
 3824:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3825:                             my $locmodtime = (stat($fname))[9];
 3826:                             if ($locmodtime < $remmodtime) {
 3827:                                 my $stale;
 3828:                                 my $answer = &reply('pong',$homeserver);
 3829:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3830:                                     sleep(0.2);
 3831:                                     $locmodtime = (stat($fname))[9];
 3832:                                     if ($locmodtime < $remmodtime) {
 3833:                                         my $posstransfer = $fname.'.in.transfer';
 3834:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3835:                                             $removed = 1;
 3836:                                         } else {
 3837:                                             $stale = 1;
 3838:                                         }
 3839:                                     } else {
 3840:                                         $removed = 1;
 3841:                                     }
 3842:                                 } else {
 3843:                                     $stale = 1;
 3844:                                 }
 3845:                                 if ($stale) {
 3846:                                     if (unlink($fname)) {
 3847:                                         if ($uri!~/\.meta$/) {
 3848:                                             if (-e $fname.'.meta') {
 3849:                                                 unlink($fname.'.meta');
 3850:                                             }
 3851:                                         }
 3852:                                         my $unsubresult = &unsubscribe($fname);
 3853:                                         unless ($unsubresult eq 'ok') {
 3854:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3855:                                         }
 3856:                                         $removed = 1;
 3857:                                     }
 3858:                                 }
 3859:                             }
 3860:                         }
 3861:                     }
 3862:                 }
 3863:             }
 3864:         }
 3865:     }
 3866:     return $removed;
 3867: }
 3868: 
 3869: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3870: 
 3871: sub allowuploaded {
 3872:     my ($srcurl,$url)=@_;
 3873:     $url=&clutter(&declutter($url));
 3874:     my $dir=$url;
 3875:     $dir=~s/\/[^\/]+$//;
 3876:     my %httpref=();
 3877:     my $httpurl=&hreflocation('',$url);
 3878:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3879:     &Apache::lonnet::appenv(\%httpref);
 3880: }
 3881: 
 3882: #
 3883: # Determine if the current user should be able to edit a particular resource,
 3884: # when viewing in course context.
 3885: # (a) When viewing resource used to determine if "Edit" item is included in 
 3886: #     Functions.
 3887: # (b) When displaying folder contents in course editor, used to determine if
 3888: #     "Edit" link will be displayed alongside resource.
 3889: #
 3890: #  input: six args -- filename (decluttered), course number, course domain,
 3891: #                   url, symb (if registered) and group (if this is a group
 3892: #                   item -- e.g., bulletin board, group page etc.).
 3893: #  output: array of five scalars -- 
 3894: #          $cfile -- url for file editing if editable on current server
 3895: #          $home -- homeserver of resource (i.e., for author if published,
 3896: #                                           or course if uploaded.).
 3897: #          $switchserver --  1 if server switch will be needed.
 3898: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3899: #          $forceview -- 1 if icon/link should be to go to view mode
 3900: #
 3901: 
 3902: sub can_edit_resource {
 3903:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3904:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3905: #
 3906: # For aboutme pages user can only edit his/her own.
 3907: #
 3908:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3909:         my ($sdom,$sname) = ($1,$2);
 3910:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3911:             $home = $env{'user.home'};
 3912:             $cfile = $resurl;
 3913:             if ($env{'form.forceedit'}) {
 3914:                 $forceview = 1;
 3915:             } else {
 3916:                 $forceedit = 1;
 3917:             }
 3918:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3919:         } else {
 3920:             return;
 3921:         }
 3922:     }
 3923: 
 3924:     if ($env{'request.course.id'}) {
 3925:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3926:         if ($group ne '') {
 3927: # if this is a group homepage or group bulletin board, check group privs
 3928:             my $allowed = 0;
 3929:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3930:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3931:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3932:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3933:                     $allowed = 1;
 3934:                 }
 3935:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3936:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3937:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3938:                     $allowed = 1;
 3939:                 }
 3940:             }
 3941:             if ($allowed) {
 3942:                 $home=&homeserver($cnum,$cdom);
 3943:                 if ($env{'form.forceedit'}) {
 3944:                     $forceview = 1;
 3945:                 } else {
 3946:                     $forceedit = 1;
 3947:                 }
 3948:                 $cfile = $resurl;
 3949:             } else {
 3950:                 return;
 3951:             }
 3952:         } else {
 3953:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3954:                 unless (&allowed('opa',$env{'request.course.id'})) {
 3955:                     return;
 3956:                 }
 3957:             } elsif (!$crsedit) {
 3958:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 3959: #
 3960: # No edit allowed where CC has switched to student role.
 3961: #
 3962:                     return;
 3963:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 3964:                          ($resurl =~ m{^/res/lib/templates/})) {
 3965:                     return;
 3966:                 }
 3967:             }
 3968:         }
 3969:     }
 3970: 
 3971:     if ($file ne '') {
 3972:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3973:             if (&is_course_upload($file,$cnum,$cdom)) {
 3974:                 $uploaded = 1;
 3975:                 $incourse = 1;
 3976:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3977:                     $cfile = &hreflocation('',$file);
 3978:                     if ($env{'form.forceedit'}) {
 3979:                         $forceview = 1;
 3980:                     } else {
 3981:                         $forceedit = 1;
 3982:                     }
 3983:                 }
 3984:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3985:                 $incourse = 1;
 3986:                 if ($env{'form.forceedit'}) {
 3987:                     $forceview = 1;
 3988:                 } else {
 3989:                     $forceedit = 1;
 3990:                 }
 3991:                 $cfile = $resurl;
 3992:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3993:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3994:                     $incourse = 1;
 3995:                     if ($env{'form.forceedit'}) {
 3996:                         $forceview = 1;
 3997:                     } else {
 3998:                         $forceedit = 1;
 3999:                     }
 4000:                     $cfile = $resurl;
 4001:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 4002:                     $incourse = 1;
 4003:                     $cfile = $resurl.'/smpedit';
 4004:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4005:                     $incourse = 1;
 4006:                     if ($env{'form.forceedit'}) {
 4007:                         $forceview = 1;
 4008:                     } else {
 4009:                         $forceedit = 1;
 4010:                     }
 4011:                     $cfile = $resurl;
 4012:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4013:                     my ($map,$id,$res) = &decode_symb($symb);
 4014:                     if ($map =~ /\.page$/) {
 4015:                         $incourse = 1;
 4016:                         if ($env{'form.forceedit'}) {
 4017:                             $forceview = 1;
 4018:                             $cfile = $map;
 4019:                         } else {
 4020:                             $forceedit = 1;
 4021:                             $cfile =  '/adm/wrapper'.$resurl;
 4022:                         }
 4023:                     }
 4024:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4025:                     $incourse = 1;
 4026:                     if ($env{'form.forceedit'}) {
 4027:                         $forceview = 1;
 4028:                     } else {
 4029:                         $forceedit = 1;
 4030:                     }
 4031:                     $cfile = $resurl;
 4032:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4033:                     $incourse = 1;
 4034:                     if ($env{'form.forceedit'}) {
 4035:                         $forceview = 1;
 4036:                     } else {
 4037:                         $forceedit = 1;
 4038:                     }
 4039:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4040:                 }
 4041:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4042:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4043:                 if (&is_on_map($template)) { 
 4044:                     $incourse = 1;
 4045:                     $forceview = 1;
 4046:                     $cfile = $template;
 4047:                 }
 4048:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4049:                 $incourse = 1;
 4050:                 if ($env{'form.forceedit'}) {
 4051:                     $forceview = 1;
 4052:                 } else {
 4053:                     $forceedit = 1;
 4054:                 }
 4055:                 $cfile = $resurl;
 4056:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4057:                 $incourse = 1;
 4058:                 if ($env{'form.forceedit'}) {
 4059:                     $forceview = 1;
 4060:                 } else {
 4061:                     $forceedit = 1;
 4062:                 }
 4063:                 $cfile = $resurl;
 4064:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4065:                 $incourse = 1;
 4066:                 $forceview = 1;
 4067:                 if ($symb) {
 4068:                     my ($map,$id,$res)=&decode_symb($symb);
 4069:                     $env{'request.symb'} = $symb;
 4070:                     $cfile = &clutter($res);
 4071:                 } else {
 4072:                     $cfile = $env{'form.suppurl'};
 4073:                     my $escfile = &unescape($cfile);
 4074:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4075:                         $cfile = '/adm/wrapper'.$escfile;
 4076:                     } else {
 4077:                         $escfile =~ s{^http://}{};
 4078:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4079:                     }
 4080:                 }
 4081:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4082:                 if ($env{'form.forceedit'}) {
 4083:                     $forceview = 1;
 4084:                 } else {
 4085:                     $forceedit = 1;
 4086:                 }
 4087:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4088:             }
 4089:         }
 4090:         if ($uploaded || $incourse) {
 4091:             $home=&homeserver($cnum,$cdom);
 4092:         } elsif ($file !~ m{/$}) {
 4093:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4094:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4095:             # Check that the user has permission to edit this resource
 4096:             my $setpriv = 1;
 4097:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4098:             if (defined($cfudom)) {
 4099:                 $home=&homeserver($cfuname,$cfudom);
 4100:                 $cfile=$file;
 4101:             }
 4102:         }
 4103:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4104:             (($home ne '') && ($home ne 'no_host'))) {
 4105:             my @ids=&current_machine_ids();
 4106:             unless (grep(/^\Q$home\E$/,@ids)) {
 4107:                 $switchserver=1;
 4108:             }
 4109:         }
 4110:     }
 4111:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4112: }
 4113: 
 4114: sub is_course_upload {
 4115:     my ($file,$cnum,$cdom) = @_;
 4116:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4117:     $uploadpath =~ s{^\/}{};
 4118:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4119:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4120:         return 1;
 4121:     }
 4122:     return;
 4123: }
 4124: 
 4125: sub in_course {
 4126:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4127:     if ($hideprivileged) {
 4128:         my $skipuser;
 4129:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4130:         my @possdoms = ($cdom);  
 4131:         if ($coursehash{'checkforpriv'}) { 
 4132:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4133:         }
 4134:         if (&privileged($uname,$udom,\@possdoms)) {
 4135:             $skipuser = 1;
 4136:             if ($coursehash{'nothideprivileged'}) {
 4137:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4138:                     my $user;
 4139:                     if ($item =~ /:/) {
 4140:                         $user = $item;
 4141:                     } else {
 4142:                         $user = join(':',split(/[\@]/,$item));
 4143:                     }
 4144:                     if ($user eq $uname.':'.$udom) {
 4145:                         undef($skipuser);
 4146:                         last;
 4147:                     }
 4148:                 }
 4149:             }
 4150:             if ($skipuser) {
 4151:                 return 0;
 4152:             }
 4153:         }
 4154:     }
 4155:     $type ||= 'any';
 4156:     if (!defined($cdom) || !defined($cnum)) {
 4157:         my $cid  = $env{'request.course.id'};
 4158:         $cdom = $env{'course.'.$cid.'.domain'};
 4159:         $cnum = $env{'course.'.$cid.'.num'};
 4160:     }
 4161:     my $typesref;
 4162:     if (($type eq 'any') || ($type eq 'all')) {
 4163:         $typesref = ['active','previous','future'];
 4164:     } elsif ($type eq 'previous' || $type eq 'future') {
 4165:         $typesref = [$type];
 4166:     }
 4167:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4168:                               $typesref,undef,[$cdom]);
 4169:     my ($tmp) = keys(%roles);
 4170:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4171:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4172:     if (@course_roles > 0) {
 4173:         return 1;
 4174:     }
 4175:     return 0;
 4176: }
 4177: 
 4178: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4179: # input: action, courseID, current domain, intended
 4180: #        path to file, source of file, instruction to parse file for objects,
 4181: #        ref to hash for embedded objects,
 4182: #        ref to hash for codebase of java objects.
 4183: #        reference to scalar to accommodate mime type determined
 4184: #          from File::MMagic if $parser = parse.
 4185: #
 4186: # output: url to file (if action was uploaddoc), 
 4187: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4188: #
 4189: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4190: # course.
 4191: #
 4192: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4193: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4194: #          course's home server.
 4195: #
 4196: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4197: #          be copied from $source (current location) to 
 4198: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4199: #         and will then be copied to
 4200: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4201: #         course's home server.
 4202: #
 4203: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4204: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4205: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4206: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4207: #         in course's home server.
 4208: #
 4209: 
 4210: sub process_coursefile {
 4211:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4212:         $mimetype)=@_;
 4213:     my $fetchresult;
 4214:     my $home=&homeserver($docuname,$docudom);
 4215:     if ($action eq 'propagate') {
 4216:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4217: 			     $home);
 4218:     } else {
 4219:         my $fpath = '';
 4220:         my $fname = $file;
 4221:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4222:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4223:         my $filepath = &build_filepath($fpath);
 4224:         if ($action eq 'copy') {
 4225:             if ($source eq '') {
 4226:                 $fetchresult = 'no source file';
 4227:                 return $fetchresult;
 4228:             } else {
 4229:                 my $destination = $filepath.'/'.$fname;
 4230:                 rename($source,$destination);
 4231:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4232:                                  $home);
 4233:             }
 4234:         } elsif ($action eq 'uploaddoc') {
 4235:             open(my $fh,'>',$filepath.'/'.$fname);
 4236:             print $fh $env{'form.'.$source};
 4237:             close($fh);
 4238:             if ($parser eq 'parse') {
 4239:                 my $mm = new File::MMagic;
 4240:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4241:                 if ($type eq 'text/html') {
 4242:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4243:                     unless ($parse_result eq 'ok') {
 4244:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4245:                     }
 4246:                 }
 4247:                 if (ref($mimetype)) {
 4248:                     $$mimetype = $type;
 4249:                 } 
 4250:             }
 4251:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4252:                                  $home);
 4253:             if ($fetchresult eq 'ok') {
 4254:                 return '/uploaded/'.$fpath.'/'.$fname;
 4255:             } else {
 4256:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4257:                         ' to host '.$home.': '.$fetchresult);
 4258:                 return '/adm/notfound.html';
 4259:             }
 4260:         }
 4261:     }
 4262:     unless ( $fetchresult eq 'ok') {
 4263:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4264:              ' to host '.$home.': '.$fetchresult);
 4265:     }
 4266:     return $fetchresult;
 4267: }
 4268: 
 4269: sub build_filepath {
 4270:     my ($fpath) = @_;
 4271:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4272:     unless ($fpath eq '') {
 4273:         my @parts=split('/',$fpath);
 4274:         foreach my $part (@parts) {
 4275:             $filepath.= '/'.$part;
 4276:             if ((-e $filepath)!=1) {
 4277:                 mkdir($filepath,0777);
 4278:             }
 4279:         }
 4280:     }
 4281:     return $filepath;
 4282: }
 4283: 
 4284: sub store_edited_file {
 4285:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4286:     my $file = $primary_url;
 4287:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4288:     my $fpath = '';
 4289:     my $fname = $file;
 4290:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4291:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4292:     my $filepath = &build_filepath($fpath);
 4293:     open(my $fh,'>',$filepath.'/'.$fname);
 4294:     print $fh $content;
 4295:     close($fh);
 4296:     my $home=&homeserver($docuname,$docudom);
 4297:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4298: 			  $home);
 4299:     if ($$fetchresult eq 'ok') {
 4300:         return '/uploaded/'.$fpath.'/'.$fname;
 4301:     } else {
 4302:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4303: 		 ' to host '.$home.': '.$$fetchresult);
 4304:         return '/adm/notfound.html';
 4305:     }
 4306: }
 4307: 
 4308: sub clean_filename {
 4309:     my ($fname,$args)=@_;
 4310: # Replace Windows backslashes by forward slashes
 4311:     $fname=~s/\\/\//g;
 4312:     if (!$args->{'keep_path'}) {
 4313:         # Get rid of everything but the actual filename
 4314: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4315:     }
 4316: # Replace spaces by underscores
 4317:     $fname=~s/\s+/\_/g;
 4318: # Transliterate non-ascii text to ascii
 4319:     my $lang = &Apache::lonlocal::current_language();
 4320:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4321: # Replace all other weird characters by nothing
 4322:     $fname=~s{[^/\w\.\-]}{}g;
 4323: # Replace all .\d. sequences with _\d. so they no longer look like version
 4324: # numbers
 4325:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4326: # Replace three or more adjacent underscores with one for consistency 
 4327: # with loncfile::filename_check() so complete url can be extracted by
 4328: # lonnet::decode_symb()
 4329:     $fname=~s/_{3,}/_/g;
 4330:     return $fname;
 4331: }
 4332: 
 4333: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4334: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4335: # image with the same aspect ratio as the original, but with dimensions which do 
 4336: # not exceed $resizewidth and $resizeheight.
 4337:  
 4338: sub resizeImage {
 4339:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4340:     my $ima = Image::Magick->new;
 4341:     my $resized;
 4342:     if (-e $img_path) {
 4343:         $ima->Read($img_path);
 4344:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4345:             my $width = $ima->Get('width');
 4346:             my $height = $ima->Get('height');
 4347:             if ($width > $resizewidth) {
 4348: 	        my $factor = $width/$resizewidth;
 4349:                 my $newheight = $height/$factor;
 4350:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4351:                 $resized = 1;
 4352:             }
 4353:         }
 4354:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4355:             my $width = $ima->Get('width');
 4356:             my $height = $ima->Get('height');
 4357:             if ($height > $resizeheight) {
 4358:                 my $factor = $height/$resizeheight;
 4359:                 my $newwidth = $width/$factor;
 4360:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4361:                 $resized = 1;
 4362:             }
 4363:         }
 4364:         if ($resized) {
 4365:             $ima->Write($img_path);
 4366:         }
 4367:     }
 4368:     return;
 4369: }
 4370: 
 4371: # --------------- Take an uploaded file and put it into the userfiles directory
 4372: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4373: #                    the desired filename is in $env{"form.$formname.filename"}
 4374: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4375: #                                    canceloverwrite, scantron, toollogo  or ''.
 4376: #                   if 'coursedoc': upload to the current course
 4377: #                   if 'existingfile': write file to tmp/overwrites directory 
 4378: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4379: #                   $context is passed as argument to &finishuserfileupload
 4380: #        $subdir - directory in userfile to store the file into
 4381: #        $parser - instruction to parse file for objects ($parser = parse) or
 4382: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4383: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4384: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4385: #        $allfiles - reference to hash for embedded objects
 4386: #        $codebase - reference to hash for codebase of java objects
 4387: #        $destuname - username for permanent storage of uploaded file
 4388: #        $destudom - domain for permanaent storage of uploaded file
 4389: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4390: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4391: #        $resizewidth - width (pixels) to which to resize uploaded image
 4392: #        $resizeheight - height (pixels) to which to resize uploaded image
 4393: #        $mimetype - reference to scalar to accommodate mime type determined
 4394: #                    from File::MMagic.
 4395: # 
 4396: # output: url of file in userspace, or error: <message> 
 4397: #             or /adm/notfound.html if failure to upload occurse
 4398: 
 4399: sub userfileupload {
 4400:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4401:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4402:     if (!defined($subdir)) { $subdir='unknown'; }
 4403:     my $fname=$env{'form.'.$formname.'.filename'};
 4404:     $fname=&clean_filename($fname);
 4405:     # See if there is anything left
 4406:     unless ($fname) { return 'error: no uploaded file'; }
 4407:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4408:     if ($fname =~ /^\./) {
 4409:         my ($s,$usec) = &gettimeofday();
 4410:         while (length($usec) < 6) {
 4411:             $usec = '0'.$usec;
 4412:         }
 4413:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4414:     }
 4415:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4416:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4417:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4418:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4419:         my $now = time;
 4420:         my $filepath;
 4421:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4422:              $filepath = 'tmp/helprequests/'.$now;
 4423:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4424:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4425:                          '_'.$env{'user.domain'}.'/pending';
 4426:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4427:             my ($docuname,$docudom);
 4428:             if ($destudom =~ /^$match_domain$/) {
 4429:                 $docudom = $destudom;
 4430:             } else {
 4431:                 $docudom = $env{'user.domain'};
 4432:             }
 4433:             if ($destuname =~ /^$match_username$/) {
 4434:                 $docuname = $destuname;
 4435:             } else {
 4436:                 $docuname = $env{'user.name'};
 4437:             }
 4438:             if (exists($env{'form.group'})) {
 4439:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4440:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4441:             }
 4442:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4443:             if ($context eq 'canceloverwrite') {
 4444:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4445:                 if (-e  $tempfile) {
 4446:                     my @info = stat($tempfile);
 4447:                     if ($info[9] eq $env{'form.timestamp'}) {
 4448:                         unlink($tempfile);
 4449:                     }
 4450:                 }
 4451:                 return;
 4452:             }
 4453:         }
 4454:         # Create the directory if not present
 4455:         my @parts=split(/\//,$filepath);
 4456:         my $fullpath = $perlvar{'lonDaemons'};
 4457:         for (my $i=0;$i<@parts;$i++) {
 4458:             $fullpath .= '/'.$parts[$i];
 4459:             if ((-e $fullpath)!=1) {
 4460:                 mkdir($fullpath,0777);
 4461:             }
 4462:         }
 4463:         open(my $fh,'>',$fullpath.'/'.$fname);
 4464:         print $fh $env{'form.'.$formname};
 4465:         close($fh);
 4466:         if ($context eq 'existingfile') {
 4467:             my @info = stat($fullpath.'/'.$fname);
 4468:             return ($fullpath.'/'.$fname,$info[9]);
 4469:         } else {
 4470:             return $fullpath.'/'.$fname;
 4471:         }
 4472:     }
 4473:     if ($subdir eq 'scantron') {
 4474:         $fname = 'scantron_orig_'.$fname;
 4475:     } else {
 4476:         $fname="$subdir/$fname";
 4477:     }
 4478:     if ($context eq 'coursedoc') {
 4479: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4480: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4481:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4482:             return &finishuserfileupload($docuname,$docudom,
 4483: 					 $formname,$fname,$parser,$allfiles,
 4484: 					 $codebase,$thumbwidth,$thumbheight,
 4485:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4486:         } else {
 4487:             if ($env{'form.folder'}) {
 4488:                 $fname=$env{'form.folder'}.'/'.$fname;
 4489:             }
 4490:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4491: 				       $fname,$formname,$parser,
 4492: 				       $allfiles,$codebase,$mimetype);
 4493:         }
 4494:     } elsif (defined($destuname)) {
 4495:         my $docuname=$destuname;
 4496:         my $docudom=$destudom;
 4497: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4498: 				     $parser,$allfiles,$codebase,
 4499:                                      $thumbwidth,$thumbheight,
 4500:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4501:     } else {
 4502:         my $docuname=$env{'user.name'};
 4503:         my $docudom=$env{'user.domain'};
 4504:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4505:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4506:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4507:         }
 4508: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4509: 				     $parser,$allfiles,$codebase,
 4510:                                      $thumbwidth,$thumbheight,
 4511:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4512:     }
 4513: }
 4514: 
 4515: sub finishuserfileupload {
 4516:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4517:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4518:     my $path=$docudom.'/'.$docuname.'/';
 4519:     my $filepath=$perlvar{'lonDocRoot'};
 4520:   
 4521:     my ($fnamepath,$file,$fetchthumb);
 4522:     $file=$fname;
 4523:     if ($fname=~m|/|) {
 4524:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4525: 	$path.=$fnamepath.'/';
 4526:     }
 4527:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4528:     my $count;
 4529:     for ($count=4;$count<=$#parts;$count++) {
 4530:         $filepath.="/$parts[$count]";
 4531:         if ((-e $filepath)!=1) {
 4532: 	    mkdir($filepath,0777);
 4533:         }
 4534:     }
 4535: 
 4536: # Save the file
 4537:     {
 4538: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4539: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4540: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4541: 	    return '/adm/notfound.html';
 4542: 	}
 4543:         if ($context eq 'overwrite') {
 4544:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4545:             my $target = $filepath.'/'.$file;
 4546:             if (-e $source) {
 4547:                 my @info = stat($source);
 4548:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4549:                     unless (&File::Copy::move($source,$target)) {
 4550:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4551:                         return "Moving from $source failed";
 4552:                     }
 4553:                 } else {
 4554:                     return "Temporary file: $source had unexpected date/time for last modification";
 4555:                 }
 4556:             } else {
 4557:                 return "Temporary file: $source missing";
 4558:             }
 4559:         } elsif (!print FH ($env{'form.'.$formname})) {
 4560: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4561: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4562: 	    return '/adm/notfound.html';
 4563: 	}
 4564: 	close(FH);
 4565:         if ($resizewidth && $resizeheight) {
 4566:             my $mm = new File::MMagic;
 4567:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4568:             if ($mime_type =~ m{^image/}) {
 4569: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4570:             }  
 4571: 	}
 4572:     }
 4573:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4574:         if (ref($mimetype)) {
 4575:             if ($$mimetype eq '') {
 4576:                 my $mm = new File::MMagic;
 4577:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4578:                 $$mimetype = $type;
 4579:             }
 4580:         }
 4581:     }
 4582:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4583:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4584:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4585:                                                        $allfiles,$codebase);
 4586:             unless ($parse_result eq 'ok') {
 4587:                 &logthis('Failed to parse '.$filepath.$file.
 4588: 	   	         ' for embedded media: '.$parse_result); 
 4589:             }
 4590:         }
 4591:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4592:         my $format = $env{'form.scantron_format'};
 4593:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4594:     }
 4595:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4596:         my $input = $filepath.'/'.$file;
 4597:         my $output = $filepath.'/'.'tn-'.$file;
 4598:         my $makethumb; 
 4599:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4600:         if ($context eq 'toollogo') {
 4601:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4602:             if ($fullwidth ne '' && $fullheight ne '') {
 4603:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4604:                     $makethumb = 1;
 4605:                 }
 4606:             }
 4607:         } else {
 4608:             $makethumb = 1;
 4609:         }
 4610:         if ($makethumb) {
 4611:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4612:             system({$args[0]} @args);
 4613:             if (-e $filepath.'/'.'tn-'.$file) {
 4614:                 $fetchthumb  = 1; 
 4615:             }
 4616:         }
 4617:     }
 4618:  
 4619: # Notify homeserver to grep it
 4620: #
 4621:     my $docuhome=&homeserver($docuname,$docudom);	
 4622:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4623:     if ($fetchresult eq 'ok') {
 4624:         if ($fetchthumb) {
 4625:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4626:             if ($thumbresult ne 'ok') {
 4627:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4628:                          $docuhome.': '.$thumbresult);
 4629:             }
 4630:         }
 4631: #
 4632: # Return the URL to it
 4633:         return '/uploaded/'.$path.$file;
 4634:     } else {
 4635:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4636: 		 ': '.$fetchresult);
 4637:         return '/adm/notfound.html';
 4638:     }
 4639: }
 4640: 
 4641: sub extract_embedded_items {
 4642:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4643:     my @state = ();
 4644:     my (%lastids,%related,%shockwave,%flashvars);
 4645:     my %javafiles = (
 4646:                       codebase => '',
 4647:                       code => '',
 4648:                       archive => ''
 4649:                     );
 4650:     my %mediafiles = (
 4651:                       src => '',
 4652:                       movie => '',
 4653:                      );
 4654:     my $p;
 4655:     if ($content) {
 4656:         $p = HTML::LCParser->new($content);
 4657:     } else {
 4658:         $p = HTML::LCParser->new($fullpath);
 4659:     }
 4660:     while (my $t=$p->get_token()) {
 4661: 	if ($t->[0] eq 'S') {
 4662: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4663: 	    push(@state, $tagname);
 4664:             if (lc($tagname) eq 'allow') {
 4665:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4666:             }
 4667: 	    if (lc($tagname) eq 'img') {
 4668: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4669: 	    }
 4670: 	    if (lc($tagname) eq 'a') {
 4671:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4672:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4673:                 }
 4674: 	    }
 4675:             if (lc($tagname) eq 'script') {
 4676:                 my $src;
 4677:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4678:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4679:                 } else {
 4680:                     if ($attr->{'src'} ne '') {
 4681:                         $src = $attr->{'src'};
 4682:                         &add_filetype($allfiles,$src,'src');
 4683:                     }
 4684:                 }
 4685:                 my $text = $p->get_trimmed_text();
 4686:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4687:                     my @swfargs = split(/,/,$1);
 4688:                     foreach my $item (@swfargs) {
 4689:                         $item =~ s/["']//g;
 4690:                         $item =~ s/^\s+//;
 4691:                         $item =~ s/\s+$//;
 4692:                     }
 4693:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4694:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4695:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4696:                         } else {
 4697:                             $related{$swfargs[0]} = [$swfargs[2]];
 4698:                         }
 4699:                     }
 4700:                 }
 4701:             }
 4702:             if (lc($tagname) eq 'link') {
 4703:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4704:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4705:                 }
 4706:             }
 4707: 	    if (lc($tagname) eq 'object' ||
 4708: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4709: 		foreach my $item (keys(%javafiles)) {
 4710: 		    $javafiles{$item} = '';
 4711: 		}
 4712:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4713:                     $lastids{lc($tagname)} = $attr->{'id'};
 4714:                 }
 4715: 	    }
 4716: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4717: 		my $name = lc($attr->{'name'});
 4718: 		foreach my $item (keys(%javafiles)) {
 4719: 		    if ($name eq $item) {
 4720: 			$javafiles{$item} = $attr->{'value'};
 4721: 			last;
 4722: 		    }
 4723: 		}
 4724:                 my $pathfrom;
 4725: 		foreach my $item (keys(%mediafiles)) {
 4726: 		    if ($name eq $item) {
 4727:                         $pathfrom = $attr->{'value'};
 4728:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4729: 			&add_filetype($allfiles,$pathfrom,$name);
 4730: 			last;
 4731: 		    }
 4732: 		}
 4733:                 if ($name eq 'flashvars') {
 4734:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4735:                 }
 4736:                 if ($pathfrom ne '') {
 4737:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4738:                                          $pathfrom);
 4739:                 }
 4740: 	    }
 4741: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4742: 		foreach my $item (keys(%javafiles)) {
 4743: 		    if ($attr->{$item}) {
 4744: 			$javafiles{$item} = $attr->{$item};
 4745: 			last;
 4746: 		    }
 4747: 		}
 4748: 		foreach my $item (keys(%mediafiles)) {
 4749: 		    if ($attr->{$item}) {
 4750: 			&add_filetype($allfiles,$attr->{$item},$item);
 4751: 			last;
 4752: 		    }
 4753: 		}
 4754:                 if (lc($tagname) eq 'embed') {
 4755:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4756:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4757:                                              $attr->{'src'});
 4758:                     }
 4759:                 }
 4760: 	    }
 4761:             if (lc($tagname) eq 'iframe') {
 4762:                 my $src = $attr->{'src'} ;
 4763:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4764:                     &add_filetype($allfiles,$src,'src');
 4765:                 } elsif ($src =~ m{^/}) {
 4766:                     if ($env{'request.course.id'}) {
 4767:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4768:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4769:                         my $url = &hreflocation('',$fullpath);
 4770:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4771:                             my $relpath = $1;
 4772:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4773:                                 &add_filetype($allfiles,$1,'src');
 4774:                             }
 4775:                         }
 4776:                     }
 4777:                 }
 4778:             }
 4779:             if ($t->[4] =~ m{/>$}) {
 4780:                 pop(@state);
 4781:             }
 4782: 	} elsif ($t->[0] eq 'E') {
 4783: 	    my ($tagname) = ($t->[1]);
 4784: 	    if ($javafiles{'codebase'} ne '') {
 4785: 		$javafiles{'codebase'} .= '/';
 4786: 	    }  
 4787: 	    if (lc($tagname) eq 'applet' ||
 4788: 		lc($tagname) eq 'object' ||
 4789: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4790: 		) {
 4791: 		foreach my $item (keys(%javafiles)) {
 4792: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4793: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4794: 			&add_filetype($allfiles,$file,$item);
 4795: 		    }
 4796: 		}
 4797: 	    } 
 4798: 	    pop @state;
 4799: 	}
 4800:     }
 4801:     foreach my $id (sort(keys(%flashvars))) {
 4802:         if ($shockwave{$id} ne '') {
 4803:             my @pairs = split(/\&/,$flashvars{$id});
 4804:             foreach my $pair (@pairs) {
 4805:                 my ($key,$value) = split(/\=/,$pair);
 4806:                 if ($key eq 'thumb') {
 4807:                     &add_filetype($allfiles,$value,$key);
 4808:                 } elsif ($key eq 'content') {
 4809:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4810:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4811:                     if ($ext ne '') {
 4812:                         &add_filetype($allfiles,$path.$value,$ext);
 4813:                     }
 4814:                 }
 4815:             }
 4816:         }
 4817:     }
 4818:     return 'ok';
 4819: }
 4820: 
 4821: sub add_filetype {
 4822:     my ($allfiles,$file,$type)=@_;
 4823:     if (exists($allfiles->{$file})) {
 4824: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4825: 	    push(@{$allfiles->{$file}}, &escape($type));
 4826: 	}
 4827:     } else {
 4828: 	@{$allfiles->{$file}} = (&escape($type));
 4829:     }
 4830: }
 4831: 
 4832: sub embedded_dependency {
 4833:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4834:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4835:         if (($identifier ne '') &&
 4836:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4837:             ($pathfrom ne '')) {
 4838:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4839:             foreach my $dep (@{$related->{$identifier}}) {
 4840:                 &add_filetype($allfiles,$path.$dep,'object');
 4841:             }
 4842:         }
 4843:     }
 4844:     return;
 4845: }
 4846: 
 4847: sub check_dimensions {
 4848:     my ($inputfile) = @_;
 4849:     my ($fullwidth,$fullheight);
 4850:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4851:         my $mm = new File::MMagic;
 4852:         my $mime_type = $mm->checktype_filename($inputfile);
 4853:         if ($mime_type =~ m{^image/}) {
 4854:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4855:                 my $imageinfo = <PIPE>;
 4856:                 if (!close(PIPE)) {
 4857:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4858:                 }
 4859:                 chomp($imageinfo);
 4860:                 my ($fullsize) =
 4861:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4862:                 if ($fullsize) {
 4863:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4864:                 }
 4865:             }
 4866:         }
 4867:     }
 4868:     return ($fullwidth,$fullheight);
 4869: }
 4870: 
 4871: sub bubblesheet_converter {
 4872:     my ($cdom,$fullpath,$config,$format) = @_;
 4873:     if ((&domain($cdom) ne '') &&
 4874:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4875:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4876:         my (%csvcols,%csvoptions);
 4877:         if (ref($config->{'fields'}) eq 'HASH') {  
 4878:             %csvcols = %{$config->{'fields'}};
 4879:         }
 4880:         if (ref($config->{'options'}) eq 'HASH') {
 4881:             %csvoptions = %{$config->{'options'}};
 4882:         }
 4883:         my %csvbynum = reverse(%csvcols);
 4884:         my %scantronconf = &get_scantron_config($format,$cdom);
 4885:         if (keys(%scantronconf)) {
 4886:             my %bynum = (
 4887:                           $scantronconf{CODEstart} => 'CODEstart',
 4888:                           $scantronconf{IDstart}   => 'IDstart',
 4889:                           $scantronconf{PaperID}   => 'PaperID',
 4890:                           $scantronconf{FirstName} => 'FirstName',
 4891:                           $scantronconf{LastName}  => 'LastName',
 4892:                           $scantronconf{Qstart}    => 'Qstart',
 4893:                         );
 4894:             my @ordered;
 4895:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4896:                 push(@ordered,$bynum{$item});
 4897:             }
 4898:             my %mapstart = (
 4899:                               CODEstart => 'CODE',
 4900:                               IDstart   => 'ID',
 4901:                               PaperID   => 'PaperID',
 4902:                               FirstName => 'FirstName',
 4903:                               LastName  => 'LastName',
 4904:                               Qstart    => 'FirstQuestion',
 4905:                            );
 4906:             my %maplength = (
 4907:                               CODEstart => 'CODElength',
 4908:                               IDstart   => 'IDlength',
 4909:                               PaperID   => 'PaperIDlength',
 4910:                               FirstName => 'FirstNamelength',
 4911:                               LastName  => 'LastNamelength',
 4912:             );
 4913:             if (open(my $fh,'<',$fullpath)) {
 4914:                 my $output;
 4915:                 my %lettdig = &letter_to_digits();
 4916:                 my %diglett = reverse(%lettdig);
 4917:                 my $numletts = scalar(keys(%lettdig));
 4918:                 my $num = 0;
 4919:                 while (my $line=<$fh>) {
 4920:                     $num ++;
 4921:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4922:                     $line =~ s{[\r\n]+$}{};
 4923:                     my %found;
 4924:                     my @values = split(/,/,$line,-1);
 4925:                     my ($qstart,$record);
 4926:                     for (my $i=0; $i<@values; $i++) {
 4927:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4928:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4929:                             if ($values[$i] eq '') {
 4930:                                 $values[$i] = $scantronconf{'Qoff'};
 4931:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4932:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4933:                                     $values[$i] = $lettdig{uc($values[$i])};
 4934:                                 }
 4935:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4936:                                 if ($values[$i] =~ /^[0-9]$/) {
 4937:                                     $values[$i] = $diglett{$values[$i]};
 4938:                                 }
 4939:                             } else {
 4940:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4941:                                     my $digit;
 4942:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4943:                                         $digit = $lettdig{uc($values[$i])}-1;
 4944:                                         if ($values[$i] eq 'J') {
 4945:                                             $digit += $numletts;
 4946:                                         }
 4947:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4948:                                         $digit = $values[$i]-1;
 4949:                                         if ($values[$i] eq '0') {
 4950:                                             $digit += $numletts;
 4951:                                         }
 4952:                                     }
 4953:                                     my $qval='';
 4954:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4955:                                         if ($j == $digit) {
 4956:                                             $qval .= $scantronconf{'Qon'};
 4957:                                         } else {
 4958:                                             $qval .= $scantronconf{'Qoff'};
 4959:                                         }
 4960:                                     }
 4961:                                     $values[$i] = $qval;
 4962:                                 }
 4963:                             }
 4964:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4965:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4966:                             }
 4967:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4968:                             if ($numblank > 0) {
 4969:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4970:                             }
 4971:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4972:                                 $qstart = $i;
 4973:                                 $found{$csvbynum{$i}} = $values[$i];
 4974:                             } else {
 4975:                                 $found{'FirstQuestion'} .= $values[$i];
 4976:                             }
 4977:                         } elsif (exists($csvbynum{$i})) {
 4978:                             if ($csvoptions{'rem'}) {
 4979:                                 $values[$i] =~ s/^\s+//;
 4980:                             }
 4981:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4982:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4983:                                     $values[$i] = '0'.$values[$i];
 4984:                                 }
 4985:                             }
 4986:                             $found{$csvbynum{$i}} = $values[$i];
 4987:                         }
 4988:                     }
 4989:                     foreach my $item (@ordered) {
 4990:                         my $currlength = 1+length($record);
 4991:                         my $numspaces = $scantronconf{$item} - $currlength;
 4992:                         if ($numspaces > 0) {
 4993:                             $record .= (' ' x $numspaces);
 4994:                         }
 4995:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4996:                             unless ($item eq 'Qstart') {
 4997:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4998:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4999:                                 }
 5000:                             }
 5001:                             $record .= $found{$mapstart{$item}};
 5002:                         }
 5003:                     }
 5004:                     $output .= "$record\n";
 5005:                 }
 5006:                 close($fh);
 5007:                 if ($output) {
 5008:                     if (open(my $fh,'>',$fullpath)) {
 5009:                         print $fh $output;
 5010:                         close($fh);
 5011:                     }
 5012:                 }
 5013:             }
 5014:         }
 5015:         return;
 5016:     }
 5017: }
 5018: 
 5019: sub letter_to_digits {
 5020:     my %lettdig = (
 5021:                     A => 1,
 5022:                     B => 2,
 5023:                     C => 3,
 5024:                     D => 4,
 5025:                     E => 5,
 5026:                     F => 6,
 5027:                     G => 7,
 5028:                     H => 8,
 5029:                     I => 9,
 5030:                     J => 0,
 5031:                   );
 5032:     return %lettdig;
 5033: }
 5034: 
 5035: sub get_scantron_config {
 5036:     my ($which,$cdom) = @_;
 5037:     my @lines = &get_scantronformat_file($cdom);
 5038:     my %config;
 5039:     #FIXME probably should move to XML it has already gotten a bit much now
 5040:     foreach my $line (@lines) {
 5041:         my ($name,$descrip)=split(/:/,$line);
 5042:         if ($name ne $which ) { next; }
 5043:         chomp($line);
 5044:         my @config=split(/:/,$line);
 5045:         $config{'name'}=$config[0];
 5046:         $config{'description'}=$config[1];
 5047:         $config{'CODElocation'}=$config[2];
 5048:         $config{'CODEstart'}=$config[3];
 5049:         $config{'CODElength'}=$config[4];
 5050:         $config{'IDstart'}=$config[5];
 5051:         $config{'IDlength'}=$config[6];
 5052:         $config{'Qstart'}=$config[7];
 5053:         $config{'Qlength'}=$config[8];
 5054:         $config{'Qoff'}=$config[9];
 5055:         $config{'Qon'}=$config[10];
 5056:         $config{'PaperID'}=$config[11];
 5057:         $config{'PaperIDlength'}=$config[12];
 5058:         $config{'FirstName'}=$config[13];
 5059:         $config{'FirstNamelength'}=$config[14];
 5060:         $config{'LastName'}=$config[15];
 5061:         $config{'LastNamelength'}=$config[16];
 5062:         $config{'BubblesPerRow'}=$config[17];
 5063:         last;
 5064:     }
 5065:     return %config;
 5066: }
 5067: 
 5068: sub get_scantronformat_file {
 5069:     my ($cdom) = @_;
 5070:     if ($cdom eq '') {
 5071:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5072:     }
 5073:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5074:     my $gottab = 0;
 5075:     my @lines;
 5076:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5077:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5078:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5079:             if ($formatfile ne '-1') {
 5080:                 @lines = split("\n",$formatfile,-1);
 5081:                 $gottab = 1;
 5082:             }
 5083:         }
 5084:     }
 5085:     if (!$gottab) {
 5086:         my $confname = $cdom.'-domainconfig';
 5087:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5088:         my $formatfile = &getfile($default);
 5089:         if ($formatfile ne '-1') {
 5090:             @lines = split("\n",$formatfile,-1);
 5091:             $gottab = 1;
 5092:         }
 5093:     }
 5094:     if (!$gottab) {
 5095:         my @domains = &current_machine_domains();
 5096:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5097:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5098:                 @lines = <$fh>;
 5099:                 close($fh);
 5100:             }
 5101:         } else {
 5102:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5103:                 @lines = <$fh>;
 5104:                 close($fh);
 5105:             }
 5106:         }
 5107:         chomp(@lines);
 5108:     }
 5109:     return @lines;
 5110: }
 5111: 
 5112: sub removeuploadedurl {
 5113:     my ($url)=@_;	
 5114:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5115:     return &removeuserfile($uname,$udom,$fname);
 5116: }
 5117: 
 5118: sub removeuserfile {
 5119:     my ($docuname,$docudom,$fname)=@_;
 5120:     my $home=&homeserver($docuname,$docudom);    
 5121:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5122:     if ($result eq 'ok') {	
 5123:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5124:             my $metafile = $fname.'.meta';
 5125:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5126: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5127:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5128:             my $sqlresult = 
 5129:                 &update_portfolio_table($docuname,$docudom,$file,
 5130:                                         'portfolio_metadata',$group,
 5131:                                         'delete');
 5132:         }
 5133:     }
 5134:     return $result;
 5135: }
 5136: 
 5137: sub mkdiruserfile {
 5138:     my ($docuname,$docudom,$dir)=@_;
 5139:     my $home=&homeserver($docuname,$docudom);
 5140:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5141: }
 5142: 
 5143: sub renameuserfile {
 5144:     my ($docuname,$docudom,$old,$new)=@_;
 5145:     my $home=&homeserver($docuname,$docudom);
 5146:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5147:                         &escape("$old").':'.&escape("$new"),$home);
 5148:     if ($result eq 'ok') {
 5149:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5150:             my $oldmeta = $old.'.meta';
 5151:             my $newmeta = $new.'.meta';
 5152:             my $metaresult = 
 5153:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5154: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5155:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5156:             my $sqlresult = 
 5157:                 &update_portfolio_table($docuname,$docudom,$file,
 5158:                                         'portfolio_metadata',$group,
 5159:                                         'delete');
 5160:         }
 5161:     }
 5162:     return $result;
 5163: }
 5164: 
 5165: # ------------------------------------------------------------------------- Log
 5166: 
 5167: sub log {
 5168:     my ($dom,$nam,$hom,$what)=@_;
 5169:     return critical("log:$dom:$nam:$what",$hom);
 5170: }
 5171: 
 5172: # ------------------------------------------------------------------ Course Log
 5173: #
 5174: # This routine flushes several buffers of non-mission-critical nature
 5175: #
 5176: 
 5177: sub flushcourselogs {
 5178:     &logthis('Flushing log buffers');
 5179: #
 5180: # course logs
 5181: # This is a log of all transactions in a course, which can be used
 5182: # for data mining purposes
 5183: #
 5184: # It also collects the courseid database, which lists last transaction
 5185: # times and course titles for all courseids
 5186: #
 5187:     my %courseidbuffer=();
 5188:     foreach my $crsid (keys(%courselogs)) {
 5189:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5190: 		          &escape($courselogs{$crsid}),
 5191: 		          $coursehombuf{$crsid}) eq 'ok') {
 5192: 	    delete $courselogs{$crsid};
 5193:         } else {
 5194:             &logthis('Failed to flush log buffer for '.$crsid);
 5195:             if (length($courselogs{$crsid})>40000) {
 5196:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5197:                         " exceeded maximum size, deleting.</font>");
 5198:                delete $courselogs{$crsid};
 5199:             }
 5200:         }
 5201:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5202:             'description' => $coursedescrbuf{$crsid},
 5203:             'inst_code'    => $courseinstcodebuf{$crsid},
 5204:             'type'        => $coursetypebuf{$crsid},
 5205:             'owner'       => $courseownerbuf{$crsid},
 5206:         };
 5207:     }
 5208: #
 5209: # Write course id database (reverse lookup) to homeserver of courses 
 5210: # Is used in pickcourse
 5211: #
 5212:     foreach my $crs_home (keys(%courseidbuffer)) {
 5213:         my $response = &courseidput(&host_domain($crs_home),
 5214:                                     $courseidbuffer{$crs_home},
 5215:                                     $crs_home,'timeonly');
 5216:     }
 5217: #
 5218: # File accesses
 5219: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5220: #
 5221:     foreach my $entry (keys(%accesshash)) {
 5222:         if ($entry =~ /___count$/) {
 5223:             my ($dom,$name);
 5224:             ($dom,$name,undef)=
 5225: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5226:             if (! defined($dom) || $dom eq '' || 
 5227:                 ! defined($name) || $name eq '') {
 5228:                 my $cid = $env{'request.course.id'};
 5229: #
 5230: # FIXME 11/29/2021
 5231: # Typo in rev. 1.458 (2003/12/09)??
 5232: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5233: #
 5234: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5235: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5236: # in a nohist_accesscount.db file for the user rather than the course.
 5237: #
 5238: # That said there is a lot of noise in the data being stored.
 5239: # So counts for prtspool/  and adm/ etc. are recorded.
 5240: #
 5241: # A review of which items ending '___count' are written to %accesshash should likely be 
 5242: # made before deciding whether to set these to 'course.' instead of 'request.'
 5243: #
 5244: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5245: # accesses for things which are not published resources, regardless of course, and
 5246: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5247: # anyone in the course for things which are not published resources.
 5248: #
 5249: # For an author, nohist_accesscount.db ends up having records for other items
 5250: # mixed up with the legitimate access counts for the author's published resources.
 5251: #
 5252:                 $dom  = $env{'request.'.$cid.'.domain'};
 5253:                 $name = $env{'request.'.$cid.'.num'};
 5254:             }
 5255:             my $value = $accesshash{$entry};
 5256:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5257:             my %temphash=($url => $value);
 5258:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5259:             if ($result eq 'ok') {
 5260:                 delete $accesshash{$entry};
 5261:             }
 5262:         } else {
 5263:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5264:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5265:             my %temphash=($entry => $accesshash{$entry});
 5266:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5267:                 delete $accesshash{$entry};
 5268:             }
 5269:         }
 5270:     }
 5271: #
 5272: # Roles
 5273: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5274: #
 5275:     foreach my $entry (keys(%userrolehash)) {
 5276:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5277: 	    split(/\:/,$entry);
 5278:         if (&put('nohist_userroles',
 5279:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5280:                 $rudom,$runame) eq 'ok') {
 5281: 	    delete $userrolehash{$entry};
 5282:         }
 5283:     }
 5284: #
 5285: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5286: #
 5287:     my %domrolebuffer = ();
 5288:     foreach my $entry (keys(%domainrolehash)) {
 5289:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5290:         if ($domrolebuffer{$rudom}) {
 5291:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5292:                       '='.&escape($domainrolehash{$entry});
 5293:         } else {
 5294:             $domrolebuffer{$rudom}.=&escape($entry).
 5295:                       '='.&escape($domainrolehash{$entry});
 5296:         }
 5297:         delete $domainrolehash{$entry};
 5298:     }
 5299:     foreach my $dom (keys(%domrolebuffer)) {
 5300: 	my %servers;
 5301: 	if (defined(&domain($dom,'primary'))) {
 5302: 	    my $primary=&domain($dom,'primary');
 5303: 	    my $hostname=&hostname($primary);
 5304: 	    $servers{$primary} = $hostname;
 5305: 	} else { 
 5306: 	    %servers = &get_servers($dom,'library');
 5307: 	}
 5308: 	foreach my $tryserver (keys(%servers)) {
 5309: 	    if (&reply('domroleput:'.$dom.':'.
 5310: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5311: 		last;
 5312: 	    } else {  
 5313: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5314: 	    }
 5315:         }
 5316:     }
 5317:     $dumpcount++;
 5318: }
 5319: 
 5320: sub courselog {
 5321:     my $what=shift;
 5322:     $what=time.':'.$what;
 5323:     unless ($env{'request.course.id'}) { return ''; }
 5324:     $coursedombuf{$env{'request.course.id'}}=
 5325:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5326:     $coursenumbuf{$env{'request.course.id'}}=
 5327:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5328:     $coursehombuf{$env{'request.course.id'}}=
 5329:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5330:     $coursedescrbuf{$env{'request.course.id'}}=
 5331:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5332:     $courseinstcodebuf{$env{'request.course.id'}}=
 5333:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5334:     $courseownerbuf{$env{'request.course.id'}}=
 5335:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5336:     $coursetypebuf{$env{'request.course.id'}}=
 5337:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5338:     if (defined $courselogs{$env{'request.course.id'}}) {
 5339: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5340:     } else {
 5341: 	$courselogs{$env{'request.course.id'}}.=$what;
 5342:     }
 5343:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5344: 	&flushcourselogs();
 5345:     }
 5346: }
 5347: 
 5348: sub courseacclog {
 5349:     my $fnsymb=shift;
 5350:     unless ($env{'request.course.id'}) { return ''; }
 5351:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5352:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5353:         $what.=':POST';
 5354:         # FIXME: Probably ought to escape things....
 5355: 	foreach my $key (keys(%env)) {
 5356:             if ($key=~/^form\.(.*)/) {
 5357:                 my $formitem = $1;
 5358:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5359:                     $what.=':'.$formitem.'='.$env{$key};
 5360:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5361:                     if ($formitem eq 'proctorpassword') {
 5362:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5363:                     } else {
 5364:                         $what.=':'.$formitem.'='.$env{$key};
 5365:                     }
 5366:                 }
 5367:             }
 5368:         }
 5369:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5370:         # FIXME: We should not be depending on a form parameter that someone
 5371:         # editing lonsearchcat.pm might change in the future.
 5372:         if ($env{'form.phase'} eq 'course_search') {
 5373:             $what.= ':POST';
 5374:             # FIXME: Probably ought to escape things....
 5375:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5376:                                  'crsdiscuss') {
 5377:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5378:             }
 5379:         }
 5380:     }
 5381:     &courselog($what);
 5382: }
 5383: 
 5384: sub countacc {
 5385:     my $url=&declutter(shift);
 5386:     return if (! defined($url) || $url eq '');
 5387:     unless ($env{'request.course.id'}) { return ''; }
 5388: #
 5389: # Mark that this url was used in this course
 5390: #
 5391:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5392: #
 5393: # Increase the access count for this resource in this child process
 5394: #
 5395:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5396:     $accesshash{$key}++;
 5397: }
 5398: 
 5399: sub linklog {
 5400:     my ($from,$to)=@_;
 5401:     $from=&declutter($from);
 5402:     $to=&declutter($to);
 5403:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5404:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5405: }
 5406: 
 5407: sub statslog {
 5408:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5409:     if ($users<2) { return; }
 5410:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5411:             'course'       => $env{'request.course.id'},
 5412:             'sections'     => '"all"',
 5413:             'num_students' => $users,
 5414:             'part'         => $part,
 5415:             'symb'         => $symb,
 5416:             'mean_tries'   => $av_attempts,
 5417:             'deg_of_diff'  => $degdiff});
 5418:     foreach my $key (keys(%dynstore)) {
 5419:         $accesshash{$key}=$dynstore{$key};
 5420:     }
 5421: }
 5422:   
 5423: sub userrolelog {
 5424:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5425:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5426:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5427:        $userrolehash
 5428:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5429:                     =$tend.':'.$tstart;
 5430:     }
 5431:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5432:        $userrolehash
 5433:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5434:                     =$tend.':'.$tstart;
 5435:     }
 5436:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5437:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5438:        $domainrolehash
 5439:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5440:                     = $tend.':'.$tstart;
 5441:     }
 5442: }
 5443: 
 5444: sub courserolelog {
 5445:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5446:         $context,$othdomby,$requester)=@_;
 5447:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5448:         my $cdom = $1;
 5449:         my $cnum = $2;
 5450:         my $sec = $3;
 5451:         my $namespace = 'rolelog';
 5452:         my %storehash = (
 5453:                            role    => $trole,
 5454:                            start   => $tstart,
 5455:                            end     => $tend,
 5456:                            selfenroll => $selfenroll,
 5457:                            context    => $context,
 5458:                         );
 5459:         if ($othdomby) {
 5460:             if ($othdomby eq 'othdombydc') {
 5461:                 $storehash{'approval'} = 'domain';
 5462:             } elsif ($othdomby eq 'othdombyuser') {
 5463:                 $storehash{'approval'} = 'user'; 
 5464:             }
 5465:             if ($requester ne '') {
 5466:                 $storehash{'requester'} = $requester;
 5467:             }
 5468:         }
 5469:         if ($trole eq 'gr') {
 5470:             $namespace = 'groupslog';
 5471:             $storehash{'group'} = $sec;
 5472:         } else {
 5473:             $storehash{'section'} = $sec;
 5474:             my ($curruserdomstr,$newuserdomstr);
 5475:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
 5476:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
 5477:             } else {
 5478:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 5479:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
 5480:             }
 5481:             if ($curruserdomstr ne '') {
 5482:                 my @udoms = split(/,/,$curruserdomstr);
 5483:                 unless (grep(/^\Q$domain\E/,@udoms)) {
 5484:                     push(@udoms,$domain);
 5485:                     $newuserdomstr = join(',',sort(@udoms));
 5486:                 }
 5487:             } else {
 5488:                 $newuserdomstr = $domain;
 5489:             }
 5490:             if ($newuserdomstr ne '') {
 5491:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
 5492:                                      $cdom,$cnum);
 5493:                 if ($putresult eq 'ok') {
 5494:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
 5495:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
 5496:                             ($context eq 'automated') || ($context eq 'domain')) {
 5497:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
 5498:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 5499:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
 5500:                         }
 5501:                     }
 5502:                 }
 5503:             }
 5504:         }
 5505:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5506:                    $domain,$cnum,$cdom);
 5507:         if (($trole ne 'st') || ($sec ne '')) {
 5508:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5509:         }
 5510:     }
 5511:     return;
 5512: }
 5513: 
 5514: sub domainrolelog {
 5515:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5516:         $context,$othdomby,$requester)=@_;
 5517:     if ($area =~ m{^/($match_domain)/$}) {
 5518:         my $cdom = $1;
 5519:         my $domconfiguser = &get_domainconfiguser($cdom);
 5520:         my $namespace = 'rolelog';
 5521:         my %storehash = (
 5522:                            role    => $trole,
 5523:                            start   => $tstart,
 5524:                            end     => $tend,
 5525:                            context => $context,
 5526:                         );
 5527:         if ($othdomby) {
 5528:             if ($othdomby eq 'othdombydc') {
 5529:                 $storehash{'approval'} = 'domain';
 5530:             } elsif ($othdomby eq 'othdombyuser') {
 5531:                 $storehash{'approval'} = 'user';
 5532:             }
 5533:             if ($requester ne '') {
 5534:                 $storehash{'requester'} = $requester;
 5535:             }
 5536:         }
 5537:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5538:                    $domain,$domconfiguser,$cdom);
 5539:     }
 5540:     return;
 5541: 
 5542: }
 5543: 
 5544: sub coauthorrolelog {
 5545:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5546:         $context,$othdomby,$requester)=@_;
 5547:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5548:         my $audom = $1;
 5549:         my $auname = $2;
 5550:         my $namespace = 'rolelog';
 5551:         my %storehash = (
 5552:                            role    => $trole,
 5553:                            start   => $tstart,
 5554:                            end     => $tend,
 5555:                            context => $context,
 5556:                         );
 5557:         if ($othdomby) {
 5558:             if ($othdomby eq 'othdombydc') {
 5559:                 $storehash{'approval'} = 'domain';
 5560:             } elsif ($othdomby eq 'othdombyuser') {
 5561:                 $storehash{'approval'} = 'user';
 5562:             }
 5563:             if ($requester ne '') {
 5564:                 $storehash{'requester'} = $requester;
 5565:             }
 5566:         }
 5567:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5568:                    $domain,$auname,$audom);
 5569:     }
 5570:     return;
 5571: }
 5572: 
 5573: sub get_course_adv_roles {
 5574:     my ($cid,$codes) = @_;
 5575:     $cid=$env{'request.course.id'} unless (defined($cid));
 5576:     my %coursehash=&coursedescription($cid);
 5577:     my $crstype = &Apache::loncommon::course_type($cid);
 5578:     my %nothide=();
 5579:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5580:         if ($user !~ /:/) {
 5581: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5582:         } else {
 5583:             $nothide{$user}=1;
 5584:         }
 5585:     }
 5586:     my @possdoms = ($coursehash{'domain'});
 5587:     if ($coursehash{'checkforpriv'}) {
 5588:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5589:     }
 5590:     my %returnhash=();
 5591:     my %dumphash=
 5592:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5593:     my $now=time;
 5594:     my %privileged;
 5595:     foreach my $entry (keys(%dumphash)) {
 5596: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5597:         if (($tstart) && ($tstart<0)) { next; }
 5598:         if (($tend) && ($tend<$now)) { next; }
 5599:         if (($tstart) && ($now<$tstart)) { next; }
 5600:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5601: 	if ($username eq '' || $domain eq '') { next; }
 5602:         if ((&privileged($username,$domain,\@possdoms)) &&
 5603:             (!$nothide{$username.':'.$domain})) { next; }
 5604: 	if ($role eq 'cr') { next; }
 5605:         if ($codes) {
 5606:             if ($section) { $role .= ':'.$section; }
 5607:             if ($returnhash{$role}) {
 5608:                 $returnhash{$role}.=','.$username.':'.$domain;
 5609:             } else {
 5610:                 $returnhash{$role}=$username.':'.$domain;
 5611:             }
 5612:         } else {
 5613:             my $key=&plaintext($role,$crstype);
 5614:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5615:             if ($returnhash{$key}) {
 5616: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5617:             } else {
 5618:                 $returnhash{$key}=$username.':'.$domain;
 5619:             }
 5620:         }
 5621:     }
 5622:     return %returnhash;
 5623: }
 5624: 
 5625: sub get_my_roles {
 5626:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5627:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5628:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5629:     my (%dumphash,%nothide);
 5630:     if ($context eq 'userroles') {
 5631:         %dumphash = &dump('roles',$udom,$uname);
 5632:     } else {
 5633:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5634:         if ($hidepriv) {
 5635:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5636:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5637:                 if ($user !~ /:/) {
 5638:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5639:                 } else {
 5640:                     $nothide{$user} = 1;
 5641:                 }
 5642:             }
 5643:         }
 5644:     }
 5645:     my %returnhash=();
 5646:     my $now=time;
 5647:     my %privileged;
 5648:     foreach my $entry (keys(%dumphash)) {
 5649:         my ($role,$tend,$tstart);
 5650:         if ($context eq 'userroles') {
 5651:             next if ($entry =~ /^rolesdef/);
 5652: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5653:         } else {
 5654:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5655:         }
 5656:         if (($tstart) && ($tstart<0)) { next; }
 5657:         my $status = 'active';
 5658:         if (($tend) && ($tend<=$now)) {
 5659:             $status = 'previous';
 5660:         } 
 5661:         if (($tstart) && ($now<$tstart)) {
 5662:             $status = 'future';
 5663:         }
 5664:         if (ref($types) eq 'ARRAY') {
 5665:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5666:                 next;
 5667:             } 
 5668:         } else {
 5669:             if ($status ne 'active') {
 5670:                 next;
 5671:             }
 5672:         }
 5673:         my ($rolecode,$username,$domain,$section,$area);
 5674:         if ($context eq 'userroles') {
 5675:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5676:             (undef,$domain,$username,$section) = split(/\//,$area);
 5677:         } else {
 5678:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5679:         }
 5680:         if (ref($roledoms) eq 'ARRAY') {
 5681:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5682:                 next;
 5683:             }
 5684:         }
 5685:         if (ref($roles) eq 'ARRAY') {
 5686:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5687:                 if ($role =~ /^cr\//) {
 5688:                     if (!grep(/^cr$/,@{$roles})) {
 5689:                         next;
 5690:                     }
 5691:                 } elsif ($role =~ /^gr\//) {
 5692:                     if (!grep(/^gr$/,@{$roles})) {
 5693:                         next;
 5694:                     }
 5695:                 } else {
 5696:                     next;
 5697:                 }
 5698:             }
 5699:         }
 5700:         if ($hidepriv) {
 5701:             my @privroles = ('dc','su');
 5702:             if ($context eq 'userroles') {
 5703:                 next if (grep(/^\Q$role\E$/,@privroles));
 5704:             } else {
 5705:                 my $possdoms = [$domain];
 5706:                 if (ref($roledoms) eq 'ARRAY') {
 5707:                    push(@{$possdoms},@{$roledoms}); 
 5708:                 }
 5709:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5710:                     if (!$nothide{$username.':'.$domain}) {
 5711:                         next;
 5712:                     }
 5713:                 }
 5714:             }
 5715:         }
 5716:         if ($withsec) {
 5717:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5718:                 $tstart.':'.$tend;
 5719:         } else {
 5720:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5721:         }
 5722:     }
 5723:     return %returnhash;
 5724: }
 5725: 
 5726: sub get_all_adhocroles {
 5727:     my ($dom) = @_;
 5728:     my @roles_by_num = ();
 5729:     my %domdefaults = &get_domain_defaults($dom);
 5730:     my (%description,%access_in_dom,%access_info);
 5731:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5732:         my $count = 0;
 5733:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5734:         my %ordered;
 5735:         foreach my $role (sort(keys(%domcurrent))) {
 5736:             my ($order,$desc,$access_in_dom);
 5737:             if (ref($domcurrent{$role}) eq 'HASH') {
 5738:                 $order = $domcurrent{$role}{'order'};
 5739:                 $desc = $domcurrent{$role}{'desc'};
 5740:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5741:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5742:             }
 5743:             if ($order eq '') {
 5744:                 $order = $count;
 5745:             }
 5746:             $ordered{$order} = $role;
 5747:             if ($desc ne '') {
 5748:                 $description{$role} = $desc;
 5749:             } else {
 5750:                 $description{$role}= $role;
 5751:             }
 5752:             $count++;
 5753:         }
 5754:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5755:             push(@roles_by_num,$ordered{$item});
 5756:         }
 5757:     }
 5758:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5759: }
 5760: 
 5761: sub get_my_adhocroles {
 5762:     my ($cid,$checkreg) = @_;
 5763:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5764:     if ($env{'request.course.id'} eq $cid) {
 5765:         $cdom = $env{'course.'.$cid.'.domain'};
 5766:         $cnum = $env{'course.'.$cid.'.num'};
 5767:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5768:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5769:         $cdom = $1;
 5770:         $cnum = $2;
 5771:         %info = &get('environment',['internal.coursecode'],
 5772:                      $cdom,$cnum);
 5773:     }
 5774:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5775:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5776:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5777:         if ($rosterhash{$user} ne '') {
 5778:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5779:             return ([],{}) if ($type eq 'auto');
 5780:         }
 5781:     }
 5782:     if (($cdom ne '') && ($cnum ne ''))  {
 5783:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5784:             my $then=$env{'user.login.time'};
 5785:             my $update=$env{'user.update.time'};
 5786:             if (!$update) {
 5787:                 $update = $then;
 5788:             }
 5789:             my @liveroles;
 5790:             foreach my $role ('dh','da') {
 5791:                 if ($env{"user.role.$role./$cdom/"}) {
 5792:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5793:                     my $limit = $update;
 5794:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5795:                         $limit = $then;
 5796:                     }
 5797:                     my $activerole = 1;
 5798:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5799:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5800:                     if ($activerole) {
 5801:                         push(@liveroles,$role);
 5802:                     }
 5803:                 }
 5804:             }
 5805:             if (@liveroles) {
 5806:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5807:                     my ($accessref,$accessinfo,%access_in_dom);
 5808:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5809:                     if (ref($roles_by_num) eq 'ARRAY') {
 5810:                         if (@{$roles_by_num}) {
 5811:                             my %settings;
 5812:                             if ($env{'request.course.id'} eq $cid) {
 5813:                                 foreach my $envkey (keys(%env)) {
 5814:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5815:                                         $settings{$1} = $env{$envkey};
 5816:                                     }
 5817:                                 }
 5818:                             } else {
 5819:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5820:                             }
 5821:                             my %setincrs;
 5822:                             if ($settings{'internal.adhocaccess'}) {
 5823:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5824:                             }
 5825:                             my @statuses;
 5826:                             if ($env{'environment.inststatus'}) {
 5827:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5828:                             }
 5829:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5830:                             if (ref($accessref) eq 'HASH') {
 5831:                                 %access_in_dom = %{$accessref};
 5832:                             }
 5833:                             foreach my $role (@{$roles_by_num}) {
 5834:                                 my ($curraccess,@okstatus,@personnel);
 5835:                                 if ($setincrs{$role}) {
 5836:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5837:                                     if ($curraccess eq 'status') {
 5838:                                         @okstatus = split(/\&/,$rest);
 5839:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5840:                                         @personnel = split(/\&/,$rest);
 5841:                                     }
 5842:                                 } else {
 5843:                                     $curraccess = $access_in_dom{$role};
 5844:                                     if (ref($accessinfo) eq 'HASH') {
 5845:                                         if ($curraccess eq 'status') {
 5846:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5847:                                                 @okstatus = @{$accessinfo->{$role}};
 5848:                                             }
 5849:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5850:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5851:                                                 @personnel = @{$accessinfo->{$role}};
 5852:                                             }
 5853:                                         }
 5854:                                     }
 5855:                                 }
 5856:                                 if ($curraccess eq 'none') {
 5857:                                     next;
 5858:                                 } elsif ($curraccess eq 'all') {
 5859:                                     push(@possroles,$role);
 5860:                                 } elsif ($curraccess eq 'dh') {
 5861:                                     if (grep(/^dh$/,@liveroles)) {
 5862:                                         push(@possroles,$role);
 5863:                                     } else {
 5864:                                         next;
 5865:                                     }
 5866:                                 } elsif ($curraccess eq 'da') {
 5867:                                     if (grep(/^da$/,@liveroles)) {
 5868:                                         push(@possroles,$role);
 5869:                                     } else {
 5870:                                         next;
 5871:                                     }
 5872:                                 } elsif ($curraccess eq 'status') {
 5873:                                     if (@okstatus) {
 5874:                                         if (!@statuses) {
 5875:                                             if (grep(/^default$/,@okstatus)) {
 5876:                                                 push(@possroles,$role);
 5877:                                             }
 5878:                                         } else {
 5879:                                             foreach my $status (@okstatus) {
 5880:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5881:                                                     push(@possroles,$role);
 5882:                                                     last;
 5883:                                                 }
 5884:                                             }
 5885:                                         }
 5886:                                     }
 5887:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5888:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5889:                                         if ($curraccess eq 'exc') {
 5890:                                             push(@possroles,$role);
 5891:                                         }
 5892:                                     } elsif ($curraccess eq 'inc') {
 5893:                                         push(@possroles,$role);
 5894:                                     }
 5895:                                 }
 5896:                             }
 5897:                         }
 5898:                     }
 5899:                 }
 5900:             }
 5901:         }
 5902:     }
 5903:     unless (ref($description) eq 'HASH') {
 5904:         if (ref($roles_by_num) eq 'ARRAY') {
 5905:             my %desc;
 5906:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5907:             $description = \%desc;
 5908:         } else {
 5909:             $description = {};
 5910:         }
 5911:     }
 5912:     return (\@possroles,$description);
 5913: }
 5914: 
 5915: # ----------------------------------------------------- Frontpage Announcements
 5916: #
 5917: #
 5918: 
 5919: sub postannounce {
 5920:     my ($server,$text)=@_;
 5921:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5922:     unless ($text=~/\w/) { $text=''; }
 5923:     return &reply('setannounce:'.&escape($text),$server);
 5924: }
 5925: 
 5926: sub getannounce {
 5927: 
 5928:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5929: 	my $announcement='';
 5930: 	while (my $line = <$fh>) { $announcement .= $line; }
 5931: 	close($fh);
 5932: 	if ($announcement=~/\w/) { 
 5933: 	    return 
 5934:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5935:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5936: 	} else {
 5937: 	    return '';
 5938: 	}
 5939:     } else {
 5940: 	return '';
 5941:     }
 5942: }
 5943: 
 5944: # ---------------------------------------------------------- Course ID routines
 5945: # Deal with domain's nohist_courseid.db files
 5946: #
 5947: 
 5948: sub courseidput {
 5949:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5950:     return unless (ref($storehash) eq 'HASH');
 5951:     my $outcome;
 5952:     if ($caller eq 'timeonly') {
 5953:         my $cids = '';
 5954:         foreach my $item (keys(%$storehash)) {
 5955:             $cids.=&escape($item).'&';
 5956:         }
 5957:         $cids=~s/\&$//;
 5958:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5959:                           $coursehome);       
 5960:     } else {
 5961:         my $items = '';
 5962:         foreach my $item (keys(%$storehash)) {
 5963:             $items.= &escape($item).'='.
 5964:                      &freeze_escape($$storehash{$item}).'&';
 5965:         }
 5966:         $items=~s/\&$//;
 5967:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5968:                           $coursehome);
 5969:     }
 5970:     if ($outcome eq 'unknown_cmd') {
 5971:         my $what;
 5972:         foreach my $cid (keys(%$storehash)) {
 5973:             $what .= &escape($cid).'=';
 5974:             foreach my $item ('description','inst_code','owner','type') {
 5975:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5976:             }
 5977:             $what =~ s/\:$/&/;
 5978:         }
 5979:         $what =~ s/\&$//;  
 5980:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5981:     } else {
 5982:         return $outcome;
 5983:     }
 5984: }
 5985: 
 5986: sub courseiddump {
 5987:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5988:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5989:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5990:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5991:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5992:     my $as_hash = 1;
 5993:     my %returnhash;
 5994:     if (!$domfilter) { $domfilter=''; }
 5995:     my %libserv = &all_library();
 5996:     foreach my $tryserver (keys(%libserv)) {
 5997:         if ( (  $hostidflag == 1 
 5998: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5999: 	     || (!defined($hostidflag)) ) {
 6000: 
 6001: 	    if (($domfilter eq '') ||
 6002: 		(&host_domain($tryserver) eq $domfilter)) {
 6003:                 my $rep;
 6004:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 6005:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 6006:                         join(":", (&host_domain($tryserver), $sincefilter, 
 6007:                                 &escape($descfilter), &escape($instcodefilter), 
 6008:                                 &escape($ownerfilter), &escape($coursefilter),
 6009:                                 &escape($typefilter), &escape($regexp_ok), 
 6010:                                 $as_hash, &escape($selfenrollonly), 
 6011:                                 &escape($catfilter), $showhidden, $caller, 
 6012:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 6013:                                 &escape($createdbefore), &escape($createdafter), 
 6014:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 6015:                                 $reqcrsdom,&escape($reqinstcode))));
 6016:                 } else {
 6017:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 6018:                              $sincefilter.':'.&escape($descfilter).':'.
 6019:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 6020:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 6021:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 6022:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 6023:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 6024:                              &escape($cc_clone).':'.$cloneonly.':'.
 6025:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 6026:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 6027:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 6028:                 }
 6029:                      
 6030:                 my @pairs=split(/\&/,$rep);
 6031:                 foreach my $item (@pairs) {
 6032:                     my ($key,$value)=split(/\=/,$item,2);
 6033:                     $key = &unescape($key);
 6034:                     next if ($key =~ /^error: 2 /);
 6035:                     my $result = &thaw_unescape($value);
 6036:                     if (ref($result) eq 'HASH') {
 6037:                         $returnhash{$key}=$result;
 6038:                     } else {
 6039:                         my @responses = split(/:/,$value);
 6040:                         my @items = ('description','inst_code','owner','type');
 6041:                         for (my $i=0; $i<@responses; $i++) {
 6042:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6043:                         }
 6044:                     }
 6045:                 }
 6046:             }
 6047:         }
 6048:     }
 6049:     return %returnhash;
 6050: }
 6051: 
 6052: sub courselastaccess {
 6053:     my ($cdom,$cnum,$hostidref) = @_;
 6054:     my %returnhash;
 6055:     if ($cdom && $cnum) {
 6056:         my $chome = &homeserver($cnum,$cdom);
 6057:         if ($chome ne 'no_host') {
 6058:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6059:             &extract_lastaccess(\%returnhash,$rep);
 6060:         }
 6061:     } else {
 6062:         if (!$cdom) { $cdom=''; }
 6063:         my %libserv = &all_library();
 6064:         foreach my $tryserver (keys(%libserv)) {
 6065:             if (ref($hostidref) eq 'ARRAY') {
 6066:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6067:             } 
 6068:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6069:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6070:                 &extract_lastaccess(\%returnhash,$rep);
 6071:             }
 6072:         }
 6073:     }
 6074:     return %returnhash;
 6075: }
 6076: 
 6077: sub extract_lastaccess {
 6078:     my ($returnhash,$rep) = @_;
 6079:     if (ref($returnhash) eq 'HASH') {
 6080:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6081:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6082:                  $rep eq '') {
 6083:             my @pairs=split(/\&/,$rep);
 6084:             foreach my $item (@pairs) {
 6085:                 my ($key,$value)=split(/\=/,$item,2);
 6086:                 $key = &unescape($key);
 6087:                 next if ($key =~ /^error: 2 /);
 6088:                 $returnhash->{$key} = &thaw_unescape($value);
 6089:             }
 6090:         }
 6091:     }
 6092:     return;
 6093: }
 6094: 
 6095: # ---------------------------------------------------------- DC e-mail
 6096: 
 6097: sub dcmailput {
 6098:     my ($domain,$msgid,$message,$server)=@_;
 6099:     my $status = &critical(
 6100:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6101:        &escape($message),$server);
 6102:     return $status;
 6103: }
 6104: 
 6105: sub dcmaildump {
 6106:     my ($dom,$startdate,$enddate,$senders) = @_;
 6107:     my %returnhash=();
 6108: 
 6109:     if (defined(&domain($dom,'primary'))) {
 6110:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6111:                                                          &escape($enddate).':';
 6112: 	my @esc_senders=map { &escape($_)} @$senders;
 6113: 	$cmd.=&escape(join('&',@esc_senders));
 6114: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6115:             my ($key,$value) = split(/\=/,$line,2);
 6116:             if (($key) && ($value)) {
 6117:                 $returnhash{&unescape($key)} = &unescape($value);
 6118:             }
 6119:         }
 6120:     }
 6121:     return %returnhash;
 6122: }
 6123: # ---------------------------------------------------------- Domain roles
 6124: 
 6125: sub get_domain_roles {
 6126:     my ($dom,$roles,$startdate,$enddate)=@_;
 6127:     if ((!defined($startdate)) || ($startdate eq '')) {
 6128:         $startdate = '.';
 6129:     }
 6130:     if ((!defined($enddate)) || ($enddate eq '')) {
 6131:         $enddate = '.';
 6132:     }
 6133:     my $rolelist;
 6134:     if (ref($roles) eq 'ARRAY') {
 6135:         $rolelist = join('&',@{$roles});
 6136:     }
 6137:     my %personnel = ();
 6138: 
 6139:     my %servers = &get_servers($dom,'library');
 6140:     foreach my $tryserver (keys(%servers)) {
 6141: 	%{$personnel{$tryserver}}=();
 6142: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6143: 					    &escape($startdate).':'.
 6144: 					    &escape($enddate).':'.
 6145: 					    &escape($rolelist), $tryserver))) {
 6146: 	    my ($key,$value) = split(/\=/,$line,2);
 6147: 	    if (($key) && ($value)) {
 6148: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6149: 	    }
 6150: 	}
 6151:     }
 6152:     return %personnel;
 6153: }
 6154: 
 6155: sub get_active_domroles {
 6156:     my ($dom,$roles) = @_;
 6157:     return () unless (ref($roles) eq 'ARRAY');
 6158:     my $now = time;
 6159:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6160:     my %domroles;
 6161:     foreach my $server (keys(%dompersonnel)) {
 6162:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6163:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6164:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6165:         }
 6166:     }
 6167:     return %domroles;
 6168: }
 6169: 
 6170: # ----------------------------------------------------------- Interval timing 
 6171: 
 6172: {
 6173: # Caches needed for speedup of navmaps
 6174: # We don't want to cache this for very long at all (5 seconds at most)
 6175: # 
 6176: # The user for whom we cache
 6177: my $cachedkey='';
 6178: # The cached times for this user
 6179: my %cachedtimes=();
 6180: # When this was last done
 6181: my $cachedtime='';
 6182: 
 6183: sub load_all_first_access {
 6184:     my ($uname,$udom,$ignorecache)=@_;
 6185:     if (($cachedkey eq $uname.':'.$udom) &&
 6186:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6187:         (!$ignorecache)) {
 6188:         return;
 6189:     }
 6190:     $cachedtime=time;
 6191:     $cachedkey=$uname.':'.$udom;
 6192:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6193: }
 6194: 
 6195: sub get_first_access {
 6196:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6197:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6198:     if ($argsymb) { $symb=$argsymb; }
 6199:     my ($map,$id,$res)=&decode_symb($symb);
 6200:     if ($argmap) { $map = $argmap; }
 6201:     if ($type eq 'course') {
 6202: 	$res='course';
 6203:     } elsif ($type eq 'map') {
 6204: 	$res=&symbread($map);
 6205:     } else {
 6206: 	$res=$symb;
 6207:     }
 6208:     &load_all_first_access($uname,$udom,$ignorecache);
 6209:     return $cachedtimes{"$courseid\0$res"};
 6210: }
 6211: 
 6212: sub set_first_access {
 6213:     my ($type,$interval)=@_;
 6214:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6215:     my ($map,$id,$res)=&decode_symb($symb);
 6216:     if ($type eq 'course') {
 6217: 	$res='course';
 6218:     } elsif ($type eq 'map') {
 6219: 	$res=&symbread($map);
 6220:     } else {
 6221: 	$res=$symb;
 6222:     }
 6223:     $cachedkey='';
 6224:     my $firstaccess=&get_first_access($type,$symb,$map);
 6225:     if ($firstaccess) {
 6226:         &logthis("First access time already set ($firstaccess) when attempting ".
 6227:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6228:                  "in $courseid");
 6229:         return 'already_set';
 6230:     } else {
 6231:         my $start = time;
 6232: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6233:                           $udom,$uname);
 6234:         if ($putres eq 'ok') {
 6235:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6236:                  $udom,$uname); 
 6237:             &appenv(
 6238:                      {
 6239:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6240:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6241:                      }
 6242:                   );
 6243:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6244:                 $cachedtimes{"$courseid\0$res"} = $start;
 6245:             }
 6246:         } elsif ($putres ne 'refused') {
 6247:             &logthis("Result: $putres when attempting to set first access time ".
 6248:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6249:         }
 6250:         return $putres;
 6251:     }
 6252:     return 'already_set';
 6253: }
 6254: }
 6255: 
 6256: # --------------------------------------------- Set Expire Date for Spreadsheet
 6257: 
 6258: sub expirespread {
 6259:     my ($uname,$udom,$stype,$usymb)=@_;
 6260:     my $cid=$env{'request.course.id'}; 
 6261:     if ($cid) {
 6262:        my $now=time;
 6263:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6264:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6265:                             $env{'course.'.$cid.'.num'}.
 6266: 	        	    ':nohist_expirationdates:'.
 6267:                             &escape($key).'='.$now,
 6268:                             $env{'course.'.$cid.'.home'})
 6269:     }
 6270:     return 'ok';
 6271: }
 6272: 
 6273: # ----------------------------------------------------- Devalidate Spreadsheets
 6274: 
 6275: sub devalidate {
 6276:     my ($symb,$uname,$udom)=@_;
 6277:     my $cid=$env{'request.course.id'}; 
 6278:     if ($cid) {
 6279:         # delete the stored spreadsheets for
 6280:         # - the student level sheet of this user in course's homespace
 6281:         # - the assessment level sheet for this resource 
 6282:         #   for this user in user's homespace
 6283: 	# - current conditional state info
 6284: 	my $key=$uname.':'.$udom.':';
 6285:         my $status=
 6286: 	    &del('nohist_calculatedsheets',
 6287: 		 [$key.'studentcalc:'],
 6288: 		 $env{'course.'.$cid.'.domain'},
 6289: 		 $env{'course.'.$cid.'.num'})
 6290: 		.' '.
 6291: 	    &del('nohist_calculatedsheets_'.$cid,
 6292: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6293:         unless ($status eq 'ok ok') {
 6294:            &logthis('Could not devalidate spreadsheet '.
 6295:                     $uname.' at '.$udom.' for '.
 6296: 		    $symb.': '.$status);
 6297:         }
 6298: 	&delenv('user.state.'.$cid);
 6299:     }
 6300: }
 6301: 
 6302: sub get_scalar {
 6303:     my ($string,$end) = @_;
 6304:     my $value;
 6305:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6306: 	$value = $1;
 6307:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6308: 	$value = $1;
 6309:     }
 6310:     return &unescape($value);
 6311: }
 6312: 
 6313: sub array2str {
 6314:   my (@array) = @_;
 6315:   my $result=&arrayref2str(\@array);
 6316:   $result=~s/^__ARRAY_REF__//;
 6317:   $result=~s/__END_ARRAY_REF__$//;
 6318:   return $result;
 6319: }
 6320: 
 6321: sub arrayref2str {
 6322:   my ($arrayref) = @_;
 6323:   my $result='__ARRAY_REF__';
 6324:   foreach my $elem (@$arrayref) {
 6325:     if(ref($elem) eq 'ARRAY') {
 6326:       $result.=&arrayref2str($elem).'&';
 6327:     } elsif(ref($elem) eq 'HASH') {
 6328:       $result.=&hashref2str($elem).'&';
 6329:     } elsif(ref($elem)) {
 6330:       #print("Got a ref of ".(ref($elem))." skipping.");
 6331:     } else {
 6332:       $result.=&escape($elem).'&';
 6333:     }
 6334:   }
 6335:   $result=~s/\&$//;
 6336:   $result .= '__END_ARRAY_REF__';
 6337:   return $result;
 6338: }
 6339: 
 6340: sub hash2str {
 6341:   my (%hash) = @_;
 6342:   my $result=&hashref2str(\%hash);
 6343:   $result=~s/^__HASH_REF__//;
 6344:   $result=~s/__END_HASH_REF__$//;
 6345:   return $result;
 6346: }
 6347: 
 6348: sub hashref2str {
 6349:   my ($hashref)=@_;
 6350:   my $result='__HASH_REF__';
 6351:   foreach my $key (sort(keys(%$hashref))) {
 6352:     if (ref($key) eq 'ARRAY') {
 6353:       $result.=&arrayref2str($key).'=';
 6354:     } elsif (ref($key) eq 'HASH') {
 6355:       $result.=&hashref2str($key).'=';
 6356:     } elsif (ref($key)) {
 6357:       $result.='=';
 6358:       #print("Got a ref of ".(ref($key))." skipping.");
 6359:     } else {
 6360: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6361:     }
 6362: 
 6363:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6364:       $result.=&arrayref2str($hashref->{$key}).'&';
 6365:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6366:       $result.=&hashref2str($hashref->{$key}).'&';
 6367:     } elsif(ref($hashref->{$key})) {
 6368:        $result.='&';
 6369:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6370:     } else {
 6371:       $result.=&escape($hashref->{$key}).'&';
 6372:     }
 6373:   }
 6374:   $result=~s/\&$//;
 6375:   $result .= '__END_HASH_REF__';
 6376:   return $result;
 6377: }
 6378: 
 6379: sub str2hash {
 6380:     my ($string)=@_;
 6381:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6382:     return %$hash;
 6383: }
 6384: 
 6385: sub str2hashref {
 6386:   my ($string) = @_;
 6387: 
 6388:   my %hash;
 6389: 
 6390:   if($string !~ /^__HASH_REF__/) {
 6391:       if (! ($string eq '' || !defined($string))) {
 6392: 	  $hash{'error'}='Not hash reference';
 6393:       }
 6394:       return (\%hash, $string);
 6395:   }
 6396: 
 6397:   $string =~ s/^__HASH_REF__//;
 6398: 
 6399:   while($string !~ /^__END_HASH_REF__/) {
 6400:       #key
 6401:       my $key='';
 6402:       if($string =~ /^__HASH_REF__/) {
 6403:           ($key, $string)=&str2hashref($string);
 6404:           if(defined($key->{'error'})) {
 6405:               $hash{'error'}='Bad data';
 6406:               return (\%hash, $string);
 6407:           }
 6408:       } elsif($string =~ /^__ARRAY_REF__/) {
 6409:           ($key, $string)=&str2arrayref($string);
 6410:           if($key->[0] eq 'Array reference error') {
 6411:               $hash{'error'}='Bad data';
 6412:               return (\%hash, $string);
 6413:           }
 6414:       } else {
 6415:           $string =~ s/^(.*?)=//;
 6416: 	  $key=&unescape($1);
 6417:       }
 6418:       $string =~ s/^=//;
 6419: 
 6420:       #value
 6421:       my $value='';
 6422:       if($string =~ /^__HASH_REF__/) {
 6423:           ($value, $string)=&str2hashref($string);
 6424:           if(defined($value->{'error'})) {
 6425:               $hash{'error'}='Bad data';
 6426:               return (\%hash, $string);
 6427:           }
 6428:       } elsif($string =~ /^__ARRAY_REF__/) {
 6429:           ($value, $string)=&str2arrayref($string);
 6430:           if($value->[0] eq 'Array reference error') {
 6431:               $hash{'error'}='Bad data';
 6432:               return (\%hash, $string);
 6433:           }
 6434:       } else {
 6435: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6436:       }
 6437:       $string =~ s/^&//;
 6438: 
 6439:       $hash{$key}=$value;
 6440:   }
 6441: 
 6442:   $string =~ s/^__END_HASH_REF__//;
 6443: 
 6444:   return (\%hash, $string);
 6445: }
 6446: 
 6447: sub str2array {
 6448:     my ($string)=@_;
 6449:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6450:     return @$array;
 6451: }
 6452: 
 6453: sub str2arrayref {
 6454:   my ($string) = @_;
 6455:   my @array;
 6456: 
 6457:   if($string !~ /^__ARRAY_REF__/) {
 6458:       if (! ($string eq '' || !defined($string))) {
 6459: 	  $array[0]='Array reference error';
 6460:       }
 6461:       return (\@array, $string);
 6462:   }
 6463: 
 6464:   $string =~ s/^__ARRAY_REF__//;
 6465: 
 6466:   while($string !~ /^__END_ARRAY_REF__/) {
 6467:       my $value='';
 6468:       if($string =~ /^__HASH_REF__/) {
 6469:           ($value, $string)=&str2hashref($string);
 6470:           if(defined($value->{'error'})) {
 6471:               $array[0] ='Array reference error';
 6472:               return (\@array, $string);
 6473:           }
 6474:       } elsif($string =~ /^__ARRAY_REF__/) {
 6475:           ($value, $string)=&str2arrayref($string);
 6476:           if($value->[0] eq 'Array reference error') {
 6477:               $array[0] ='Array reference error';
 6478:               return (\@array, $string);
 6479:           }
 6480:       } else {
 6481: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6482:       }
 6483:       $string =~ s/^&//;
 6484: 
 6485:       push(@array, $value);
 6486:   }
 6487: 
 6488:   $string =~ s/^__END_ARRAY_REF__//;
 6489: 
 6490:   return (\@array, $string);
 6491: }
 6492: 
 6493: # -------------------------------------------------------------------Temp Store
 6494: 
 6495: sub tmpreset {
 6496:   my ($symb,$namespace,$domain,$stuname) = @_;
 6497:   if (!$symb) {
 6498:     $symb=&symbread();
 6499:     if (!$symb) { $symb= $env{'request.url'}; }
 6500:   }
 6501:   $symb=escape($symb);
 6502: 
 6503:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6504:   $namespace=~s/\//\_/g;
 6505:   $namespace=~s/\W//g;
 6506: 
 6507:   if (!$domain) { $domain=$env{'user.domain'}; }
 6508:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6509:   if ($domain eq 'public' && $stuname eq 'public') {
 6510:       $stuname=&get_requestor_ip();
 6511:   }
 6512:   my $path=LONCAPA::tempdir();
 6513:   my %hash;
 6514:   if (tie(%hash,'GDBM_File',
 6515: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6516: 	  &GDBM_WRCREAT(),0640)) {
 6517:     foreach my $key (keys(%hash)) {
 6518:       if ($key=~ /:$symb/) {
 6519: 	delete($hash{$key});
 6520:       }
 6521:     }
 6522:   }
 6523: }
 6524: 
 6525: sub tmpstore {
 6526:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6527: 
 6528:   if (!$symb) {
 6529:     $symb=&symbread();
 6530:     if (!$symb) { $symb= $env{'request.url'}; }
 6531:   }
 6532:   $symb=escape($symb);
 6533: 
 6534:   if (!$namespace) {
 6535:     # I don't think we would ever want to store this for a course.
 6536:     # it seems this will only be used if we don't have a course.
 6537:     #$namespace=$env{'request.course.id'};
 6538:     #if (!$namespace) {
 6539:       $namespace=$env{'request.state'};
 6540:     #}
 6541:   }
 6542:   $namespace=~s/\//\_/g;
 6543:   $namespace=~s/\W//g;
 6544:   if (!$domain) { $domain=$env{'user.domain'}; }
 6545:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6546:   if ($domain eq 'public' && $stuname eq 'public') {
 6547:       $stuname=&get_requestor_ip();
 6548:   }
 6549:   my $now=time;
 6550:   my %hash;
 6551:   my $path=LONCAPA::tempdir();
 6552:   if (tie(%hash,'GDBM_File',
 6553: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6554: 	  &GDBM_WRCREAT(),0640)) {
 6555:     $hash{"version:$symb"}++;
 6556:     my $version=$hash{"version:$symb"};
 6557:     my $allkeys=''; 
 6558:     foreach my $key (keys(%$storehash)) {
 6559:       $allkeys.=$key.':';
 6560:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6561:     }
 6562:     $hash{"$version:$symb:timestamp"}=$now;
 6563:     $allkeys.='timestamp';
 6564:     $hash{"$version:keys:$symb"}=$allkeys;
 6565:     if (untie(%hash)) {
 6566:       return 'ok';
 6567:     } else {
 6568:       return "error:$!";
 6569:     }
 6570:   } else {
 6571:     return "error:$!";
 6572:   }
 6573: }
 6574: 
 6575: # -----------------------------------------------------------------Temp Restore
 6576: 
 6577: sub tmprestore {
 6578:   my ($symb,$namespace,$domain,$stuname) = @_;
 6579: 
 6580:   if (!$symb) {
 6581:     $symb=&symbread();
 6582:     if (!$symb) { $symb= $env{'request.url'}; }
 6583:   }
 6584:   $symb=escape($symb);
 6585: 
 6586:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6587: 
 6588:   if (!$domain) { $domain=$env{'user.domain'}; }
 6589:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6590:   if ($domain eq 'public' && $stuname eq 'public') {
 6591:       $stuname=&get_requestor_ip();
 6592:   }
 6593:   my %returnhash;
 6594:   $namespace=~s/\//\_/g;
 6595:   $namespace=~s/\W//g;
 6596:   my %hash;
 6597:   my $path=LONCAPA::tempdir();
 6598:   if (tie(%hash,'GDBM_File',
 6599: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6600: 	  &GDBM_READER(),0640)) {
 6601:     my $version=$hash{"version:$symb"};
 6602:     $returnhash{'version'}=$version;
 6603:     my $scope;
 6604:     for ($scope=1;$scope<=$version;$scope++) {
 6605:       my $vkeys=$hash{"$scope:keys:$symb"};
 6606:       my @keys=split(/:/,$vkeys);
 6607:       my $key;
 6608:       $returnhash{"$scope:keys"}=$vkeys;
 6609:       foreach $key (@keys) {
 6610: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6611: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6612:       }
 6613:     }
 6614:     if (!(untie(%hash))) {
 6615:       return "error:$!";
 6616:     }
 6617:   } else {
 6618:     return "error:$!";
 6619:   }
 6620:   return %returnhash;
 6621: }
 6622: 
 6623: # ----------------------------------------------------------------------- Store
 6624: 
 6625: sub store {
 6626:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6627:     my $home='';
 6628: 
 6629:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6630: 
 6631:     $symb=&symbclean($symb);
 6632:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6633: 
 6634:     if (!$domain) { $domain=$env{'user.domain'}; }
 6635:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6636: 
 6637:     &devalidate($symb,$stuname,$domain);
 6638: 
 6639:     $symb=escape($symb);
 6640:     if (!$namespace) { 
 6641:        unless ($namespace=$env{'request.course.id'}) { 
 6642:           return ''; 
 6643:        } 
 6644:     }
 6645:     if (!$home) { $home=$env{'user.home'}; }
 6646: 
 6647:     $$storehash{'ip'}=&get_requestor_ip();
 6648:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6649: 
 6650:     my $namevalue='';
 6651:     foreach my $key (keys(%$storehash)) {
 6652:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6653:     }
 6654:     $namevalue=~s/\&$//;
 6655:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6656:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6657: }
 6658: 
 6659: # -------------------------------------------------------------- Critical Store
 6660: 
 6661: sub cstore {
 6662:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6663:     my $home='';
 6664: 
 6665:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6666: 
 6667:     $symb=&symbclean($symb);
 6668:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6669: 
 6670:     if (!$domain) { $domain=$env{'user.domain'}; }
 6671:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6672: 
 6673:     &devalidate($symb,$stuname,$domain);
 6674: 
 6675:     $symb=escape($symb);
 6676:     if (!$namespace) { 
 6677:        unless ($namespace=$env{'request.course.id'}) { 
 6678:           return ''; 
 6679:        } 
 6680:     }
 6681:     if (!$home) { $home=$env{'user.home'}; }
 6682: 
 6683:     $$storehash{'ip'}=&get_requestor_ip();
 6684:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6685: 
 6686:     my $namevalue='';
 6687:     foreach my $key (keys(%$storehash)) {
 6688:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6689:     }
 6690:     $namevalue=~s/\&$//;
 6691:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6692:     return critical
 6693:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6694: }
 6695: 
 6696: # --------------------------------------------------------------------- Restore
 6697: 
 6698: sub restore {
 6699:     my ($symb,$namespace,$domain,$stuname) = @_;
 6700:     my $home='';
 6701: 
 6702:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6703: 
 6704:     if (!$symb) {
 6705:         return if ($namespace eq 'courserequests');
 6706:         unless ($symb=escape(&symbread())) { return ''; }
 6707:     } else {
 6708:         unless ($namespace eq 'courserequests') {
 6709:             $symb=&escape(&symbclean($symb));
 6710:         }
 6711:     }
 6712:     if (!$namespace) { 
 6713:        unless ($namespace=$env{'request.course.id'}) { 
 6714:           return ''; 
 6715:        } 
 6716:     }
 6717:     if (!$domain) { $domain=$env{'user.domain'}; }
 6718:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6719:     if (!$home) { $home=$env{'user.home'}; }
 6720:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6721: 
 6722:     my %returnhash=();
 6723:     foreach my $line (split(/\&/,$answer)) {
 6724: 	my ($name,$value)=split(/\=/,$line);
 6725:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6726:     }
 6727:     my $version;
 6728:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6729:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6730:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6731:        }
 6732:     }
 6733:     return %returnhash;
 6734: }
 6735: 
 6736: # ---------------------------------------------------------- Course Description
 6737: #
 6738: #  
 6739: 
 6740: sub coursedescription {
 6741:     my ($courseid,$args)=@_;
 6742:     $courseid=~s/^\///;
 6743:     $courseid=~s/\_/\//g;
 6744:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6745:     my $chome=&homeserver($cnum,$cdomain);
 6746:     my $normalid=$cdomain.'_'.$cnum;
 6747:     # need to always cache even if we get errors otherwise we keep 
 6748:     # trying and trying and trying to get the course description.
 6749:     my %envhash=();
 6750:     my %returnhash=();
 6751:     
 6752:     my $expiretime=600;
 6753:     if ($env{'request.course.id'} eq $normalid) {
 6754: 	$expiretime=120;
 6755:     }
 6756: 
 6757:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6758:     if (!$args->{'freshen_cache'}
 6759: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6760: 	foreach my $key (keys(%env)) {
 6761: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6762: 	    my ($setting) = $1;
 6763: 	    $returnhash{$setting} = $env{$key};
 6764: 	}
 6765: 	return %returnhash;
 6766:     }
 6767: 
 6768:     # get the data again
 6769: 
 6770:     if (!$args->{'one_time'}) {
 6771: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6772:     }
 6773: 
 6774:     if ($chome ne 'no_host') {
 6775:        %returnhash=&dump('environment',$cdomain,$cnum);
 6776:        if (!exists($returnhash{'con_lost'})) {
 6777: 	   my $username = $env{'user.name'}; # Defult username
 6778: 	   if(defined $args->{'user'}) {
 6779: 	       $username = $args->{'user'};
 6780: 	   }
 6781:            $returnhash{'home'}= $chome;
 6782: 	   $returnhash{'domain'} = $cdomain;
 6783: 	   $returnhash{'num'} = $cnum;
 6784:            if (!defined($returnhash{'type'})) {
 6785:                $returnhash{'type'} = 'Course';
 6786:            }
 6787:            while (my ($name,$value) = each %returnhash) {
 6788:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6789:            }
 6790:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6791:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6792: 	       $username.'_'.$cdomain.'_'.$cnum;
 6793:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6794:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6795:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6796:        }
 6797:     }
 6798:     if (!$args->{'one_time'}) {
 6799: 	&appenv(\%envhash);
 6800:     }
 6801:     return %returnhash;
 6802: }
 6803: 
 6804: sub update_released_required {
 6805:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6806:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6807:         $cid = $env{'request.course.id'};
 6808:         $cdom = $env{'course.'.$cid.'.domain'};
 6809:         $cnum = $env{'course.'.$cid.'.num'};
 6810:         $chome = $env{'course.'.$cid.'.home'};
 6811:     }
 6812:     if ($needsrelease) {
 6813:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6814:         my $needsupdate;
 6815:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6816:             $needsupdate = 1;
 6817:         } else {
 6818:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6819:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6820:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6821:                 $needsupdate = 1;
 6822:             }
 6823:         }
 6824:         if ($needsupdate) {
 6825:             my %needshash = (
 6826:                              'internal.releaserequired' => $needsrelease,
 6827:                             );
 6828:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6829:             if ($putresult eq 'ok') {
 6830:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6831:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6832:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6833:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6834:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6835:                 }
 6836:             }
 6837:         }
 6838:     }
 6839:     return;
 6840: }
 6841: 
 6842: # -------------------------------------------------See if a user is privileged
 6843: 
 6844: sub privileged {
 6845:     my ($username,$domain,$possdomains,$possroles)=@_;
 6846:     my $now = time;
 6847:     my $roles;
 6848:     if (ref($possroles) eq 'ARRAY') {
 6849:         $roles = $possroles; 
 6850:     } else {
 6851:         $roles = ['dc','su'];
 6852:     }
 6853:     if (ref($possdomains) eq 'ARRAY') {
 6854:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6855:         foreach my $dom (@{$possdomains}) {
 6856:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6857:                 (ref($privileged{$dom}) eq 'HASH')) {
 6858:                 foreach my $role (@{$roles}) {
 6859:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6860:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6861:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6862:                             return 1 unless (($end && $end < $now) ||
 6863:                                              ($start && $start > $now));
 6864:                         }
 6865:                     }
 6866:                 }
 6867:             }
 6868:         }
 6869:     } else {
 6870:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6871:         my $now = time;
 6872: 
 6873:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6874:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6875:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6876:                 return 1 unless ($tend && $tend < $now) 
 6877:                         or ($tstart && $tstart > $now);
 6878:             }
 6879:         }
 6880:     }
 6881:     return 0;
 6882: }
 6883: 
 6884: sub privileged_by_domain {
 6885:     my ($domains,$roles) = @_;
 6886:     my %privileged = ();
 6887:     my $cachetime = 60*60*24;
 6888:     my $now = time;
 6889:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6890:         return %privileged;
 6891:     }
 6892:     foreach my $dom (@{$domains}) {
 6893:         next if (ref($privileged{$dom}) eq 'HASH');
 6894:         my $needroles;
 6895:         foreach my $role (@{$roles}) {
 6896:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6897:             if (defined($cached)) {
 6898:                 if (ref($result) eq 'HASH') {
 6899:                     $privileged{$dom}{$role} = $result;
 6900:                 }
 6901:             } else {
 6902:                 $needroles = 1;
 6903:             }
 6904:         }
 6905:         if ($needroles) {
 6906:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6907:             $privileged{$dom} = {};
 6908:             foreach my $server (keys(%dompersonnel)) {
 6909:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6910:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6911:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6912:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6913:                         next if ($end && $end < $now);
 6914:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6915:                             $dompersonnel{$server}{$item};
 6916:                     }
 6917:                 }
 6918:             }
 6919:             if (ref($privileged{$dom}) eq 'HASH') {
 6920:                 foreach my $role (@{$roles}) {
 6921:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6922:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6923:                     } else {
 6924:                         my %hash = ();
 6925:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6926:                     }
 6927:                 }
 6928:             }
 6929:         }
 6930:     }
 6931:     return %privileged;
 6932: }
 6933: 
 6934: # -------------------------------------------------------- Get user privileges
 6935: 
 6936: sub rolesinit {
 6937:     my ($domain, $username) = @_;
 6938:     my %userroles = ('user.login.time' => time);
 6939:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6940: 
 6941:     # firstaccess and timerinterval are related to timed maps/resources. 
 6942:     # also, blocking can be triggered by an activating timer
 6943:     # it's saved in the user's %env.
 6944:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6945:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6946:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6947:         %timerintchk, %timerintenv);
 6948: 
 6949:     foreach my $key (keys(%firstaccess)) {
 6950:         my ($cid, $rest) = split(/\0/, $key);
 6951:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6952:     }
 6953: 
 6954:     foreach my $key (keys(%timerinterval)) {
 6955:         my ($cid,$rest) = split(/\0/,$key);
 6956:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6957:     }
 6958: 
 6959:     my %allroles=();
 6960:     my %allgroups=();
 6961: 
 6962:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6963:         my $role = $rolesdump{$area};
 6964:         $area =~ s/\_\w\w$//;
 6965: 
 6966:         my ($trole, $tend, $tstart, $group_privs);
 6967: 
 6968:         if ($role =~ /^cr/) {
 6969:         # Custom role, defined by a user 
 6970:         # e.g., user.role.cr/msu/smith/mynewrole
 6971:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6972:                 $trole = $1;
 6973:                 ($tend, $tstart) = split('_', $2);
 6974:             } else {
 6975:                 $trole = $role;
 6976:             }
 6977:         } elsif ($role =~ m|^gr/|) {
 6978:         # Role of member in a group, defined within a course/community
 6979:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6980:             ($trole, $tend, $tstart) = split(/_/, $role);
 6981:             next if $tstart eq '-1';
 6982:             ($trole, $group_privs) = split(/\//, $trole);
 6983:             $group_privs = &unescape($group_privs);
 6984:         } else {
 6985:         # Just a normal role, defined in roles.tab
 6986:             ($trole, $tend, $tstart) = split(/_/,$role);
 6987:         }
 6988: 
 6989:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6990:                  $username);
 6991:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6992: 
 6993:         # role expired or not available yet?
 6994:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6995:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6996: 
 6997:         next if $area eq '' or $trole eq '';
 6998: 
 6999:         my $spec = "$trole.$area";
 7000:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 7001: 
 7002:         if ($trole =~ /^cr\//) {
 7003:         # Custom role, defined by a user
 7004:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7005:         } elsif ($trole eq 'gr') {
 7006:         # Role of a member in a group, defined within a course/community
 7007:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 7008:             next;
 7009:         } else {
 7010:         # Normal role, defined in roles.tab
 7011:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7012:         }
 7013: 
 7014:         my $cid = $tdomain.'_'.$trest;
 7015:         unless ($firstaccchk{$cid}) {
 7016:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 7017:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 7018:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 7019:                         $coursetimerstarts{$cid}{$item}; 
 7020:                 }
 7021:             }
 7022:             $firstaccchk{$cid} = 1;
 7023:         }
 7024:         unless ($timerintchk{$cid}) {
 7025:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 7026:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 7027:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 7028:                        $coursetimerintervals{$cid}{$item};
 7029:                 }
 7030:             }
 7031:             $timerintchk{$cid} = 1;
 7032:         }
 7033:     }
 7034: 
 7035:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7036:                                                           \%allroles, \%allgroups);
 7037:     $env{'user.adv'} = $userroles{'user.adv'};
 7038:     $env{'user.rar'} = $userroles{'user.rar'};
 7039: 
 7040:     return (\%userroles,\%firstaccenv,\%timerintenv);
 7041: }
 7042: 
 7043: sub set_arearole {
 7044:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7045:     unless ($nolog) {
 7046: # log the associated role with the area
 7047:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7048:     }
 7049:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7050: }
 7051: 
 7052: sub custom_roleprivs {
 7053:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7054:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7055:     my $homsvr = &homeserver($rauthor,$rdomain);
 7056:     if (&hostname($homsvr) ne '') {
 7057:         my ($rdummy,$roledef)=
 7058:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7059:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7060:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7061:             if (defined($syspriv)) {
 7062:                 if ($trest =~ /^$match_community$/) {
 7063:                     $syspriv =~ s/bre\&S//; 
 7064:                 }
 7065:                 $$allroles{'cm./'}.=':'.$syspriv;
 7066:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7067:             }
 7068:             if ($tdomain ne '') {
 7069:                 if (defined($dompriv)) {
 7070:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7071:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7072:                 }
 7073:                 if (($trest ne '') && (defined($coursepriv))) {
 7074:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7075:                         my $rolename = $1;
 7076:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7077:                     }
 7078:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7079:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7080:                 }
 7081:             }
 7082:         }
 7083:     }
 7084: }
 7085: 
 7086: sub course_adhocrole_privs {
 7087:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7088:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7089:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7090:         my (%currprivs,%storeprivs);
 7091:         foreach my $item (split(/:/,$coursepriv)) {
 7092:             my ($priv,$restrict) = split(/\&/,$item);
 7093:             $currprivs{$priv} = $restrict;
 7094:         }
 7095:         my (%possadd,%possremove,%full);
 7096:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7097:             my ($priv,$restrict)=split(/\&/,$item);
 7098:             $full{$priv} = $restrict;
 7099:         }
 7100:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7101:             next if ($item eq '');
 7102:             my ($rule,$rest) = split(/=/,$item);
 7103:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7104:             foreach my $priv (split(/:/,$rest)) {
 7105:                 if ($priv ne '') {
 7106:                     if ($rule eq 'off') {
 7107:                         $possremove{$priv} = 1;
 7108:                     } else {
 7109:                         $possadd{$priv} = 1;
 7110:                     }
 7111:                 }
 7112:             }
 7113:         }
 7114:         foreach my $priv (sort(keys(%full))) {
 7115:             if (exists($currprivs{$priv})) {
 7116:                 unless (exists($possremove{$priv})) {
 7117:                     $storeprivs{$priv} = $currprivs{$priv};
 7118:                 }
 7119:             } elsif (exists($possadd{$priv})) {
 7120:                 $storeprivs{$priv} = $full{$priv};
 7121:             }
 7122:         }
 7123:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7124:     }
 7125:     return $coursepriv;
 7126: }
 7127: 
 7128: sub group_roleprivs {
 7129:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7130:     my $access = 1;
 7131:     my $now = time;
 7132:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7133:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7134:     if ($access) {
 7135:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7136:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7137:     }
 7138: }
 7139: 
 7140: sub standard_roleprivs {
 7141:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7142:     if (defined($pr{$trole.':s'})) {
 7143:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7144:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7145:     }
 7146:     if ($tdomain ne '') {
 7147:         if (defined($pr{$trole.':d'})) {
 7148:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7149:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7150:         }
 7151:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7152:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7153:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7154:         }
 7155:     }
 7156: }
 7157: 
 7158: sub set_userprivs {
 7159:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7160:     my $author=0;
 7161:     my $adv=0;
 7162:     my $rar=0;
 7163:     my %grouproles = ();
 7164:     if (keys(%{$allgroups}) > 0) {
 7165:         my @groupkeys; 
 7166:         foreach my $role (keys(%{$allroles})) {
 7167:             push(@groupkeys,$role);
 7168:         }
 7169:         if (ref($groups_roles) eq 'HASH') {
 7170:             foreach my $key (keys(%{$groups_roles})) {
 7171:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7172:                     push(@groupkeys,$key);
 7173:                 }
 7174:             }
 7175:         }
 7176:         if (@groupkeys > 0) {
 7177:             foreach my $role (@groupkeys) {
 7178:                 my ($trole,$area,$sec,$extendedarea);
 7179:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7180:                     $trole = $1;
 7181:                     $area = $2;
 7182:                     $sec = $3;
 7183:                     $extendedarea = $area.$sec;
 7184:                     if (exists($$allgroups{$area})) {
 7185:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7186:                             my $spec = $trole.'.'.$extendedarea;
 7187:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7188:                                                 $$allgroups{$area}{$group};
 7189:                         }
 7190:                     }
 7191:                 }
 7192:             }
 7193:         }
 7194:     }
 7195:     foreach my $group (keys(%grouproles)) {
 7196:         $$allroles{$group} = $grouproles{$group};
 7197:     }
 7198:     foreach my $role (keys(%{$allroles})) {
 7199:         my %thesepriv;
 7200:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7201:         foreach my $item (split(/:/,$$allroles{$role})) {
 7202:             if ($item ne '') {
 7203:                 my ($privilege,$restrictions)=split(/&/,$item);
 7204:                 if ($restrictions eq '') {
 7205:                     $thesepriv{$privilege}='F';
 7206:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7207:                     $thesepriv{$privilege}.=$restrictions;
 7208:                 }
 7209:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7210:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7211:             }
 7212:         }
 7213:         my $thesestr='';
 7214:         foreach my $priv (sort(keys(%thesepriv))) {
 7215: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7216: 	}
 7217:         $userroles->{'user.priv.'.$role} = $thesestr;
 7218:     }
 7219:     return ($author,$adv,$rar);
 7220: }
 7221: 
 7222: sub role_status {
 7223:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7224:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7225:         my ($one,$two) = split(m{\./},$rolekey,2);
 7226:         (undef,undef,$$role) = split(/\./,$one,3);
 7227:         unless (!defined($$role) || $$role eq '') {
 7228:             $$where = '/'.$two;
 7229:             $$trolecode=$$role.'.'.$$where;
 7230:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7231:             $$tstatus='is';
 7232:             if ($$tstart && $$tstart>$update) {
 7233:                 $$tstatus='future';
 7234:                 if ($$tstart<$now) {
 7235:                     if ($$tstart && $$tstart>$refresh) {
 7236:                         if (($$where ne '') && ($$role ne '')) {
 7237:                             my (%allroles,%allgroups,$group_privs,
 7238:                                 %groups_roles,@rolecodes);
 7239:                             my %userroles = (
 7240:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7241:                             );
 7242:                             @rolecodes = ('cm'); 
 7243:                             my $spec=$$role.'.'.$$where;
 7244:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7245:                             if ($$role =~ /^cr\//) {
 7246:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7247:                                 push(@rolecodes,'cr');
 7248:                             } elsif ($$role eq 'gr') {
 7249:                                 push(@rolecodes,$$role);
 7250:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7251:                                                     $env{'user.name'});
 7252:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7253:                                 (undef,my $group_privs) = split(/\//,$trole);
 7254:                                 $group_privs = &unescape($group_privs);
 7255:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7256:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7257:                                 &get_groups_roles($tdomain,$trest,
 7258:                                                   \%course_roles,\@rolecodes,
 7259:                                                   \%groups_roles);
 7260:                             } else {
 7261:                                 push(@rolecodes,$$role);
 7262:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7263:                             }
 7264:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7265:                                                                    \%groups_roles);
 7266:                             &appenv(\%userroles,\@rolecodes);
 7267:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7268:                         }
 7269:                     }
 7270:                     $$tstatus = 'is';
 7271:                 }
 7272:             }
 7273:             if ($$tend) {
 7274:                 if ($$tend<$update) {
 7275:                     $$tstatus='expired';
 7276:                 } elsif ($$tend<$now) {
 7277:                     $$tstatus='will_not';
 7278:                 }
 7279:             }
 7280:         }
 7281:     }
 7282: }
 7283: 
 7284: sub get_groups_roles {
 7285:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7286:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7287:                   (ref($rolecodes) eq 'ARRAY') && 
 7288:                   (ref($groups_roles) eq 'HASH')); 
 7289:     if (keys(%{$cdom_courseroles}) > 0) {
 7290:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7291:         if ($cdom ne '' && $cnum ne '') {
 7292:             foreach my $key (keys(%{$cdom_courseroles})) {
 7293:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7294:                     my $crsrole = $1;
 7295:                     my $crssec = $2;
 7296:                     if ($crsrole =~ /^cr/) {
 7297:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7298:                             push(@{$rolecodes},'cr');
 7299:                         }
 7300:                     } else {
 7301:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7302:                             push(@{$rolecodes},$crsrole);
 7303:                         }
 7304:                     }
 7305:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7306:                     if ($crssec ne '') {
 7307:                         $rolekey .= "/$crssec";
 7308:                     }
 7309:                     $rolekey .= './';
 7310:                     $groups_roles->{$rolekey} = $rolecodes;
 7311:                 }
 7312:             }
 7313:         }
 7314:     }
 7315:     return;
 7316: }
 7317: 
 7318: sub delete_env_groupprivs {
 7319:     my ($where,$courseroles,$possroles) = @_;
 7320:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7321:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7322:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7323:         %{$courseroles->{$udom}} =
 7324:             &get_my_roles('','','userroles',['active'],
 7325:                           $possroles,[$udom],1);
 7326:     }
 7327:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7328:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7329:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7330:             my $area = '/'.$cdom.'/'.$cnum;
 7331:             my $privkey = "user.priv.$crsrole.$area";
 7332:             if ($crssec ne '') {
 7333:                 $privkey .= '/'.$crssec;
 7334:             }
 7335:             $privkey .= ".$area/$group";
 7336:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7337:         }
 7338:     }
 7339:     return;
 7340: }
 7341: 
 7342: sub check_adhoc_privs {
 7343:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7344:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7345:     if ($sec) {
 7346:         $cckey .= '/'.$sec;
 7347:     } 
 7348:     my $setprivs;
 7349:     if ($env{$cckey}) {
 7350:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7351:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7352:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7353:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7354:             $setprivs = 1;
 7355:         }
 7356:     } else {
 7357:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7358:         $setprivs = 1;
 7359:     }
 7360:     return $setprivs;
 7361: }
 7362: 
 7363: sub set_adhoc_privileges {
 7364: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7365:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7366:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7367:     if ($sec ne '') {
 7368:         $area .= '/'.$sec;
 7369:     }
 7370:     my $spec = $role.'.'.$area;
 7371:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7372:                                   $env{'user.name'},1);
 7373:     my %rolehash = ();
 7374:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7375:         my $rolename = $1;
 7376:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7377:         my %domdef = &get_domain_defaults($dcdom);
 7378:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7379:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7380:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7381:             }
 7382:         }
 7383:     } else {
 7384:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7385:     }
 7386:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7387:     &appenv(\%userroles,[$role,'cm']);
 7388:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7389:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7390:             ($caller eq 'tiny')) {
 7391:         &appenv( {'request.role'        => $spec,
 7392:                   'request.role.domain' => $dcdom,
 7393:                   'request.course.sec'  => $sec,
 7394:                  }
 7395:                );
 7396:         my $tadv=0;
 7397:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7398:         &appenv({'request.role.adv'    => $tadv});
 7399:     }
 7400: }
 7401: 
 7402: # --------------------------------------------------------------- get interface
 7403: 
 7404: sub get {
 7405:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7406:    my $items='';
 7407:    foreach my $item (@$storearr) {
 7408:        $items.=&escape($item).'&';
 7409:    }
 7410:    $items=~s/\&$//;
 7411:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7412:    if (!$uname) { $uname=$env{'user.name'}; }
 7413:    my $uhome=&homeserver($uname,$udomain);
 7414: 
 7415:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7416:    my @pairs=split(/\&/,$rep);
 7417:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7418:      return @pairs;
 7419:    }
 7420:    my %returnhash=();
 7421:    my $i=0;
 7422:    foreach my $item (@$storearr) {
 7423:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7424:       $i++;
 7425:    }
 7426:    return %returnhash;
 7427: }
 7428: 
 7429: # --------------------------------------------------------------- del interface
 7430: 
 7431: sub del {
 7432:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7433:    my $items='';
 7434:    foreach my $item (@$storearr) {
 7435:        $items.=&escape($item).'&';
 7436:    }
 7437: 
 7438:    $items=~s/\&$//;
 7439:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7440:    if (!$uname) { $uname=$env{'user.name'}; }
 7441:    my $uhome=&homeserver($uname,$udomain);
 7442:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7443: }
 7444: 
 7445: # -------------------------------------------------------------- dump interface
 7446: 
 7447: sub unserialize {
 7448:     my ($rep, $escapedkeys) = @_;
 7449: 
 7450:     return {} if $rep =~ /^error/;
 7451: 
 7452:     my %returnhash=();
 7453: 	foreach my $item (split(/\&/,$rep)) {
 7454: 	    my ($key, $value) = split(/=/, $item, 2);
 7455: 	    $key = unescape($key) unless $escapedkeys;
 7456: 	    next if $key =~ /^error: 2 /;
 7457: 	    $returnhash{$key} = &thaw_unescape($value);
 7458: 	}
 7459:     #return %returnhash;
 7460:     return \%returnhash;
 7461: }        
 7462: 
 7463: # see Lond::dump_with_regexp
 7464: # if $escapedkeys hash keys won't get unescaped.
 7465: sub dump {
 7466:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7467:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7468:     if (!$uname) { $uname=$env{'user.name'}; }
 7469:     my $uhome=&homeserver($uname,$udomain);
 7470: 
 7471:     if ($regexp) {
 7472:         $regexp=&escape($regexp);
 7473:     } else {
 7474:         $regexp='.';
 7475:     }
 7476:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7477:         # user is hosted on this machine
 7478:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7479:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7480:         return %{unserialize($reply, $escapedkeys)};
 7481:     }
 7482:     my $rep;
 7483:     if ($encrypt) {
 7484:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7485:     } else {
 7486:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7487:     }
 7488:     my @pairs=split(/\&/,$rep);
 7489:     my %returnhash=();
 7490:     if (!($rep =~ /^error/ )) {
 7491: 	foreach my $item (@pairs) {
 7492: 	    my ($key,$value)=split(/=/,$item,2);
 7493:         $key = unescape($key) unless $escapedkeys;
 7494:         #$key = &unescape($key);
 7495: 	    next if ($key =~ /^error: 2 /);
 7496: 	    $returnhash{$key}=&thaw_unescape($value);
 7497: 	}
 7498:     }
 7499:     return %returnhash;
 7500: }
 7501: 
 7502: 
 7503: # --------------------------------------------------------- dumpstore interface
 7504: 
 7505: sub dumpstore {
 7506:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7507:    # same as dump but keys must be escaped. They may contain colon separated
 7508:    # lists of values that may themself contain colons (e.g. symbs).
 7509:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7510: }
 7511: 
 7512: # -------------------------------------------------------------- keys interface
 7513: 
 7514: sub getkeys {
 7515:    my ($namespace,$udomain,$uname)=@_;
 7516:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7517:    if (!$uname) { $uname=$env{'user.name'}; }
 7518:    my $uhome=&homeserver($uname,$udomain);
 7519:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7520:    my @keyarray=();
 7521:    foreach my $key (split(/\&/,$rep)) {
 7522:       next if ($key =~ /^error: 2 /);
 7523:       push(@keyarray,&unescape($key));
 7524:    }
 7525:    return @keyarray;
 7526: }
 7527: 
 7528: # --------------------------------------------------------------- currentdump
 7529: sub currentdump {
 7530:    my ($courseid,$sdom,$sname)=@_;
 7531:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7532:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7533:    $sname    = $env{'user.name'}         if (! defined($sname));
 7534:    my $uhome = &homeserver($sname,$sdom);
 7535:    my $rep;
 7536: 
 7537:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7538:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7539:                    $courseid)));
 7540:    } else {
 7541:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7542:    }
 7543: 
 7544:    return if ($rep =~ /^(error:|no_such_host)/);
 7545:    #
 7546:    my %returnhash=();
 7547:    #
 7548:    if ($rep eq 'unknown_cmd') {
 7549:        # an old lond will not know currentdump
 7550:        # Do a dump and make it look like a currentdump
 7551:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7552:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7553:        my %hash = @tmp;
 7554:        @tmp=();
 7555:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7556:    } else {
 7557:        my @pairs=split(/\&/,$rep);
 7558:        foreach my $pair (@pairs) {
 7559:            my ($key,$value)=split(/=/,$pair,2);
 7560:            my ($symb,$param) = split(/:/,$key);
 7561:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7562:                                                         &thaw_unescape($value);
 7563:        }
 7564:    }
 7565:    return %returnhash;
 7566: }
 7567: 
 7568: sub convert_dump_to_currentdump{
 7569:     my %hash = %{shift()};
 7570:     my %returnhash;
 7571:     # Code ripped from lond, essentially.  The only difference
 7572:     # here is the unescaping done by lonnet::dump().  Conceivably
 7573:     # we might run in to problems with parameter names =~ /^v\./
 7574:     while (my ($key,$value) = each(%hash)) {
 7575:         my ($v,$symb,$param) = split(/:/,$key);
 7576: 	$symb  = &unescape($symb);
 7577: 	$param = &unescape($param);
 7578:         next if ($v eq 'version' || $symb eq 'keys');
 7579:         next if (exists($returnhash{$symb}) &&
 7580:                  exists($returnhash{$symb}->{$param}) &&
 7581:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7582:         $returnhash{$symb}->{$param}=$value;
 7583:         $returnhash{$symb}->{'v.'.$param}=$v;
 7584:     }
 7585:     #
 7586:     # Remove all of the keys in the hashes which keep track of
 7587:     # the version of the parameter.
 7588:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7589:         # use a foreach because we are going to delete from the hash.
 7590:         foreach my $key (keys(%$param_hash)) {
 7591:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7592:         }
 7593:     }
 7594:     return \%returnhash;
 7595: }
 7596: 
 7597: # ------------------------------------------------------ critical inc interface
 7598: 
 7599: sub cinc {
 7600:     return &inc(@_,'critical');
 7601: }
 7602: 
 7603: # --------------------------------------------------------------- inc interface
 7604: 
 7605: sub inc {
 7606:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7607:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7608:     if (!$uname) { $uname=$env{'user.name'}; }
 7609:     my $uhome=&homeserver($uname,$udomain);
 7610:     my $items='';
 7611:     if (! ref($store)) {
 7612:         # got a single value, so use that instead
 7613:         $items = &escape($store).'=&';
 7614:     } elsif (ref($store) eq 'SCALAR') {
 7615:         $items = &escape($$store).'=&';        
 7616:     } elsif (ref($store) eq 'ARRAY') {
 7617:         $items = join('=&',map {&escape($_);} @{$store});
 7618:     } elsif (ref($store) eq 'HASH') {
 7619:         while (my($key,$value) = each(%{$store})) {
 7620:             $items.= &escape($key).'='.&escape($value).'&';
 7621:         }
 7622:     }
 7623:     $items=~s/\&$//;
 7624:     if ($critical) {
 7625: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7626:     } else {
 7627: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7628:     }
 7629: }
 7630: 
 7631: # --------------------------------------------------------------- put interface
 7632: 
 7633: sub put {
 7634:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7635:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7636:    if (!$uname) { $uname=$env{'user.name'}; }
 7637:    my $uhome=&homeserver($uname,$udomain);
 7638:    my $items='';
 7639:    foreach my $item (keys(%$storehash)) {
 7640:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7641:    }
 7642:    $items=~s/\&$//;
 7643:    if ($encrypt) {
 7644:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7645:    } else {
 7646:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7647:    }
 7648: }
 7649: 
 7650: # ------------------------------------------------------------ newput interface
 7651: 
 7652: sub newput {
 7653:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7655:    if (!$uname) { $uname=$env{'user.name'}; }
 7656:    my $uhome=&homeserver($uname,$udomain);
 7657:    my $items='';
 7658:    foreach my $key (keys(%$storehash)) {
 7659:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7660:    }
 7661:    $items=~s/\&$//;
 7662:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7663: }
 7664: 
 7665: # ---------------------------------------------------------  putstore interface
 7666: 
 7667: sub putstore {
 7668:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7669:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7670:    if (!$uname) { $uname=$env{'user.name'}; }
 7671:    my $uhome=&homeserver($uname,$udomain);
 7672:    my $items='';
 7673:    foreach my $key (keys(%$storehash)) {
 7674:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7675:    }
 7676:    $items=~s/\&$//;
 7677:    my $esc_symb=&escape($symb);
 7678:    my $esc_v=&escape($version);
 7679:    my $reply =
 7680:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7681: 	      $uhome);
 7682:    if (($tolog) && ($reply eq 'ok')) {
 7683:        my $namevalue='';
 7684:        foreach my $key (keys(%{$storehash})) {
 7685:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7686:        }
 7687:        my $ip = &get_requestor_ip();
 7688:        $namevalue .= 'ip='.&escape($ip).
 7689:                      '&host='.&escape($perlvar{'lonHostID'}).
 7690:                      '&version='.$esc_v.
 7691:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7692:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7693:    }
 7694:    if ($reply eq 'unknown_cmd') {
 7695:        # gfall back to way things use to be done
 7696:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7697: 			    $uname);
 7698:    }
 7699:    return $reply;
 7700: }
 7701: 
 7702: sub old_putstore {
 7703:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7704:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7705:     if (!$uname) { $uname=$env{'user.name'}; }
 7706:     my $uhome=&homeserver($uname,$udomain);
 7707:     my %newstorehash;
 7708:     foreach my $item (keys(%$storehash)) {
 7709: 	my $key = $version.':'.&escape($symb).':'.$item;
 7710: 	$newstorehash{$key} = $storehash->{$item};
 7711:     }
 7712:     my $items='';
 7713:     my %allitems = ();
 7714:     foreach my $item (keys(%newstorehash)) {
 7715: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7716: 	    my $key = $1.':keys:'.$2;
 7717: 	    $allitems{$key} .= $3.':';
 7718: 	}
 7719: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7720:     }
 7721:     foreach my $item (keys(%allitems)) {
 7722: 	$allitems{$item} =~ s/\:$//;
 7723: 	$items.= $item.'='.$allitems{$item}.'&';
 7724:     }
 7725:     $items=~s/\&$//;
 7726:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7727: }
 7728: 
 7729: # ------------------------------------------------------ critical put interface
 7730: 
 7731: sub cput {
 7732:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7733:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7734:    if (!$uname) { $uname=$env{'user.name'}; }
 7735:    my $uhome=&homeserver($uname,$udomain);
 7736:    my $items='';
 7737:    foreach my $item (keys(%$storehash)) {
 7738:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7739:    }
 7740:    $items=~s/\&$//;
 7741:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7742: }
 7743: 
 7744: # -------------------------------------------------------------- eget interface
 7745: 
 7746: sub eget {
 7747:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7748:    my $items='';
 7749:    foreach my $item (@$storearr) {
 7750:        $items.=&escape($item).'&';
 7751:    }
 7752:    $items=~s/\&$//;
 7753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7754:    if (!$uname) { $uname=$env{'user.name'}; }
 7755:    my $uhome=&homeserver($uname,$udomain);
 7756:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7757:    my @pairs=split(/\&/,$rep);
 7758:    my %returnhash=();
 7759:    my $i=0;
 7760:    foreach my $item (@$storearr) {
 7761:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7762:       $i++;
 7763:    }
 7764:    return %returnhash;
 7765: }
 7766: 
 7767: # ------------------------------------------------------------ tmpput interface
 7768: sub tmpput {
 7769:     my ($storehash,$server,$context)=@_;
 7770:     my $items='';
 7771:     foreach my $item (keys(%$storehash)) {
 7772: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7773:     }
 7774:     $items=~s/\&$//;
 7775:     if (defined($context)) {
 7776:         $items .= ':'.&escape($context);
 7777:     }
 7778:     return &reply("tmpput:$items",$server);
 7779: }
 7780: 
 7781: # ------------------------------------------------------------ tmpget interface
 7782: sub tmpget {
 7783:     my ($token,$server)=@_;
 7784:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7785:     my $rep=&reply("tmpget:$token",$server);
 7786:     my %returnhash;
 7787:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7788:         return %returnhash;
 7789:     }
 7790:     foreach my $item (split(/\&/,$rep)) {
 7791: 	my ($key,$value)=split(/=/,$item);
 7792: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7793:     }
 7794:     return %returnhash;
 7795: }
 7796: 
 7797: # ------------------------------------------------------------ tmpdel interface
 7798: sub tmpdel {
 7799:     my ($token,$server)=@_;
 7800:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7801:     return &reply("tmpdel:$token",$server);
 7802: }
 7803: 
 7804: # ------------------------------------------------------------ get_timebased_id 
 7805: 
 7806: sub get_timebased_id {
 7807:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7808:         $maxtries) = @_;
 7809:     my ($newid,$error,$dellock);
 7810:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7811:         return ('','ok','invalid call to get suffix');
 7812:     }
 7813: 
 7814: # set defaults for any optional args for which values were not supplied
 7815:     if ($who eq '') {
 7816:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7817:     }
 7818:     if (!$locktries) {
 7819:         $locktries = 3;
 7820:     }
 7821:     if (!$maxtries) {
 7822:         $maxtries = 10;
 7823:     }
 7824:     
 7825:     if (($cdom eq '') || ($cnum eq '')) {
 7826:         if ($env{'request.course.id'}) {
 7827:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7828:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7829:         }
 7830:         if (($cdom eq '') || ($cnum eq '')) {
 7831:             return ('','ok','call to get suffix not in course context');
 7832:         }
 7833:     }
 7834: 
 7835: # construct locking item
 7836:     my $lockhash = {
 7837:                       $prefix."\0".'locked_'.$keyid => $who,
 7838:                    };
 7839:     my $tries = 0;
 7840: 
 7841: # attempt to get lock on nohist_$namespace file
 7842:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7843:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7844:         $tries ++;
 7845:         sleep 1;
 7846:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7847:     }
 7848: 
 7849: # attempt to get unique identifier, based on current timestamp
 7850:     if ($gotlock eq 'ok') {
 7851:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7852:         my $id = time;
 7853:         $newid = $id;
 7854:         if ($idtype eq 'addcode') {
 7855:             $newid .= &sixnum_code();
 7856:         }
 7857:         my $idtries = 0;
 7858:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7859:             if ($idtype eq 'concat') {
 7860:                 $newid = $id.$idtries;
 7861:             } elsif ($idtype eq 'addcode') {
 7862:                 $newid = $newid.&sixnum_code();
 7863:             } else {
 7864:                 $newid ++;
 7865:             }
 7866:             $idtries ++;
 7867:         }
 7868:         if (!exists($inuse{$prefix."\0".$newid})) {
 7869:             my %new_item =  (
 7870:                               $prefix."\0".$newid => $who,
 7871:                             );
 7872:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7873:                                                  $cdom,$cnum);
 7874:             if ($putresult ne 'ok') {
 7875:                 undef($newid);
 7876:                 $error = 'error saving new item: '.$putresult;
 7877:             }
 7878:         } else {
 7879:              undef($newid);
 7880:              $error = ('error: no unique suffix available for the new item ');
 7881:         }
 7882: #  remove lock
 7883:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7884:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7885:     } else {
 7886:         $error = "error: could not obtain lockfile\n";
 7887:         $dellock = 'ok';
 7888:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7889:             $dellock = 'nolock';
 7890:         }
 7891:     }
 7892:     return ($newid,$dellock,$error);
 7893: }
 7894: 
 7895: sub sixnum_code {
 7896:     my $code;
 7897:     for (0..6) {
 7898:         $code .= int( rand(9) );
 7899:     }
 7900:     return $code;
 7901: }
 7902: 
 7903: # -------------------------------------------------- portfolio access checking
 7904: 
 7905: sub portfolio_access {
 7906:     my ($requrl,$clientip) = @_;
 7907:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7908:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7909:     if ($result) {
 7910:         my %setters;
 7911:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7912:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7913:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7914:             if (($startblock && $endblock) || ($by_ip)) {
 7915:                 return 'B';
 7916:             }
 7917:         } else {
 7918:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7919:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7920:             if (($startblock && $endblock) || ($by_ip)) {
 7921:                 return 'B';
 7922:             }
 7923:         }
 7924:     }
 7925:     if ($result eq 'ok') {
 7926:        return 'F';
 7927:     } elsif ($result =~ /^[^:]+:guest_/) {
 7928:        return 'A';
 7929:     }
 7930:     return '';
 7931: }
 7932: 
 7933: sub get_portfolio_access {
 7934:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7935: 
 7936:     if (!ref($access_hash)) {
 7937: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7938: 	my %access_controls = &get_access_controls($current_perms,$group,
 7939: 						   $file_name);
 7940: 	$access_hash = $access_controls{$file_name};
 7941:     }
 7942: 
 7943:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7944:     my $now = time;
 7945:     if (ref($access_hash) eq 'HASH') {
 7946:         foreach my $key (keys(%{$access_hash})) {
 7947:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7948:             if ($start > $now) {
 7949:                 next;
 7950:             }
 7951:             if ($end && $end<$now) {
 7952:                 next;
 7953:             }
 7954:             if ($scope eq 'public') {
 7955:                 $public = $key;
 7956:                 last;
 7957:             } elsif ($scope eq 'guest') {
 7958:                 $guest = $key;
 7959:             } elsif ($scope eq 'domains') {
 7960:                 push(@domains,$key);
 7961:             } elsif ($scope eq 'users') {
 7962:                 push(@users,$key);
 7963:             } elsif ($scope eq 'course') {
 7964:                 push(@courses,$key);
 7965:             } elsif ($scope eq 'group') {
 7966:                 push(@groups,$key);
 7967:             } elsif ($scope eq 'ip') {
 7968:                 push(@ips,$key);
 7969:             }
 7970:         }
 7971:         if ($public) {
 7972:             return 'ok';
 7973:         } elsif (@ips > 0) {
 7974:             my $allowed;
 7975:             foreach my $ipkey (@ips) {
 7976:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7977:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7978:                         $allowed = 1;
 7979:                         last; 
 7980:                     }
 7981:                 }
 7982:             }
 7983:             if ($allowed) {
 7984:                 return 'ok';
 7985:             }
 7986:         }
 7987:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7988:             if ($guest) {
 7989:                 return $guest;
 7990:             }
 7991:         } else {
 7992:             if (@domains > 0) {
 7993:                 foreach my $domkey (@domains) {
 7994:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7995:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7996:                             return 'ok';
 7997:                         }
 7998:                     }
 7999:                 }
 8000:             }
 8001:             if (@users > 0) {
 8002:                 foreach my $userkey (@users) {
 8003:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 8004:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 8005:                             if (ref($item) eq 'HASH') {
 8006:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 8007:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 8008:                                     return 'ok';
 8009:                                 }
 8010:                             }
 8011:                         }
 8012:                     } 
 8013:                 }
 8014:             }
 8015:             my %roleshash;
 8016:             my @courses_and_groups = @courses;
 8017:             push(@courses_and_groups,@groups); 
 8018:             if (@courses_and_groups > 0) {
 8019:                 my (%allgroups,%allroles); 
 8020:                 my ($start,$end,$role,$sec,$group);
 8021:                 foreach my $envkey (%env) {
 8022:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8023:                         my $cid = $2.'_'.$3; 
 8024:                         if ($1 eq 'gr') {
 8025:                             $group = $4;
 8026:                             $allgroups{$cid}{$group} = $env{$envkey};
 8027:                         } else {
 8028:                             if ($4 eq '') {
 8029:                                 $sec = 'none';
 8030:                             } else {
 8031:                                 $sec = $4;
 8032:                             }
 8033:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8034:                         }
 8035:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8036:                         my $cid = $2.'_'.$3;
 8037:                         if ($4 eq '') {
 8038:                             $sec = 'none';
 8039:                         } else {
 8040:                             $sec = $4;
 8041:                         }
 8042:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8043:                     }
 8044:                 }
 8045:                 if (keys(%allroles) == 0) {
 8046:                     return;
 8047:                 }
 8048:                 foreach my $key (@courses_and_groups) {
 8049:                     my %content = %{$$access_hash{$key}};
 8050:                     my $cnum = $content{'number'};
 8051:                     my $cdom = $content{'domain'};
 8052:                     my $cid = $cdom.'_'.$cnum;
 8053:                     if (!exists($allroles{$cid})) {
 8054:                         next;
 8055:                     }    
 8056:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8057:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8058:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8059:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8060:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8061:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8062:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8063:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8064:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8065:                                         if (grep/^all$/,@sections) {
 8066:                                             return 'ok';
 8067:                                         } else {
 8068:                                             if (grep/^$sec$/,@sections) {
 8069:                                                 return 'ok';
 8070:                                             }
 8071:                                         }
 8072:                                     }
 8073:                                 }
 8074:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8075:                                     if (grep/^none$/,@groups) {
 8076:                                         return 'ok';
 8077:                                     }
 8078:                                 } else {
 8079:                                     if (grep/^all$/,@groups) {
 8080:                                         return 'ok';
 8081:                                     } 
 8082:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8083:                                         if (grep/^$group$/,@groups) {
 8084:                                             return 'ok';
 8085:                                         }
 8086:                                     }
 8087:                                 } 
 8088:                             }
 8089:                         }
 8090:                     }
 8091:                 }
 8092:             }
 8093:             if ($guest) {
 8094:                 return $guest;
 8095:             }
 8096:         }
 8097:     }
 8098:     return;
 8099: }
 8100: 
 8101: sub course_group_datechecker {
 8102:     my ($dates,$now,$status) = @_;
 8103:     my ($start,$end) = split(/\./,$dates);
 8104:     if (!$start && !$end) {
 8105:         return 'ok';
 8106:     }
 8107:     if (grep/^active$/,@{$status}) {
 8108:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8109:             return 'ok';
 8110:         }
 8111:     }
 8112:     if (grep/^previous$/,@{$status}) {
 8113:         if ($end > $now ) {
 8114:             return 'ok';
 8115:         }
 8116:     }
 8117:     if (grep/^future$/,@{$status}) {
 8118:         if ($start > $now) {
 8119:             return 'ok';
 8120:         }
 8121:     }
 8122:     return; 
 8123: }
 8124: 
 8125: sub parse_portfolio_url {
 8126:     my ($url) = @_;
 8127: 
 8128:     my ($type,$udom,$unum,$group,$file_name);
 8129:     
 8130:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8131: 	$type = 1;
 8132:         $udom = $1;
 8133:         $unum = $2;
 8134:         $file_name = $3;
 8135:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8136: 	$type = 2;
 8137:         $udom = $1;
 8138:         $unum = $2;
 8139:         $group = $3;
 8140:         $file_name = $3.'/'.$4;
 8141:     }
 8142:     if (wantarray) {
 8143: 	return ($type,$udom,$unum,$file_name,$group);
 8144:     }
 8145:     return $type;
 8146: }
 8147: 
 8148: sub is_portfolio_url {
 8149:     my ($url) = @_;
 8150:     return scalar(&parse_portfolio_url($url));
 8151: }
 8152: 
 8153: sub is_portfolio_file {
 8154:     my ($file) = @_;
 8155:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8156:         return 1;
 8157:     }
 8158:     return;
 8159: }
 8160: 
 8161: sub is_coursetool_logo {
 8162:     my ($uri) = @_;
 8163:     if ($env{'request.course.id'}) {
 8164:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8165:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8166:             return 1;
 8167:         }
 8168:     }
 8169:     return;
 8170: }
 8171: 
 8172: sub usertools_access {
 8173:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8174:     my ($access,%tools);
 8175:     if ($context eq '') {
 8176:         $context = 'tools';
 8177:     }
 8178:     if ($context eq 'requestcourses') {
 8179:         %tools = (
 8180:                       official   => 1,
 8181:                       unofficial => 1,
 8182:                       community  => 1,
 8183:                       textbook   => 1,
 8184:                       placement  => 1,
 8185:                       lti        => 1,
 8186:                  );
 8187:     } elsif ($context eq 'requestauthor') {
 8188:         %tools = (
 8189:                       requestauthor => 1,
 8190:                  );
 8191:     } else {
 8192:         %tools = (
 8193:                       aboutme   => 1,
 8194:                       blog      => 1,
 8195:                       webdav    => 1,
 8196:                       portfolio => 1,
 8197:                       timezone  => 1,
 8198:                  );
 8199:     }
 8200:     return if (!defined($tools{$tool}));
 8201: 
 8202:     if (($udom eq '') || ($uname eq '')) {
 8203:         $udom = $env{'user.domain'};
 8204:         $uname = $env{'user.name'};
 8205:     }
 8206: 
 8207:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8208:         if ($action ne 'reload') {
 8209:             if ($context eq 'requestcourses') {
 8210:                 return $env{'environment.canrequest.'.$tool};
 8211:             } elsif ($context eq 'requestauthor') {
 8212:                 return $env{'environment.canrequest.author'};
 8213:             } else {
 8214:                 return $env{'environment.availabletools.'.$tool};
 8215:             }
 8216:         }
 8217:     }
 8218: 
 8219:     my ($toolstatus,$inststatus,$envkey);
 8220:     if ($context eq 'requestauthor') {
 8221:         $envkey = $context; 
 8222:     } else {
 8223:         $envkey = $context.'.'.$tool;
 8224:     }
 8225: 
 8226:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8227:          ($action ne 'reload')) {
 8228:         $toolstatus = $env{'environment.'.$envkey};
 8229:         $inststatus = $env{'environment.inststatus'};
 8230:     } else {
 8231:         if (ref($userenvref) eq 'HASH') {
 8232:             $toolstatus = $userenvref->{$envkey};
 8233:             $inststatus = $userenvref->{'inststatus'};
 8234:         } else {
 8235:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8236:             $toolstatus = $userenv{$envkey};
 8237:             $inststatus = $userenv{'inststatus'};
 8238:         }
 8239:     }
 8240: 
 8241:     if ($toolstatus ne '') {
 8242:         if ($toolstatus) {
 8243:             $access = 1;
 8244:         } else {
 8245:             $access = 0;
 8246:         }
 8247:         return $access;
 8248:     }
 8249: 
 8250:     my ($is_adv,%domdef);
 8251:     if (ref($is_advref) eq 'HASH') {
 8252:         $is_adv = $is_advref->{'is_adv'};
 8253:     } else {
 8254:         $is_adv = &is_advanced_user($udom,$uname);
 8255:     }
 8256:     if (ref($domdefref) eq 'HASH') {
 8257:         %domdef = %{$domdefref};
 8258:     } else {
 8259:         %domdef = &get_domain_defaults($udom);
 8260:     }
 8261:     if (ref($domdef{$tool}) eq 'HASH') {
 8262:         if ($is_adv) {
 8263:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8264:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8265:                     $access = 1;
 8266:                 } else {
 8267:                     $access = 0;
 8268:                 }
 8269:                 return $access;
 8270:             }
 8271:         }
 8272:         if ($inststatus ne '') {
 8273:             my ($hasaccess,$hasnoaccess);
 8274:             foreach my $affiliation (split(/:/,$inststatus)) {
 8275:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8276:                     if ($domdef{$tool}{$affiliation}) {
 8277:                         $hasaccess = 1;
 8278:                     } else {
 8279:                         $hasnoaccess = 1;
 8280:                     }
 8281:                 }
 8282:             }
 8283:             if ($hasaccess || $hasnoaccess) {
 8284:                 if ($hasaccess) {
 8285:                     $access = 1;
 8286:                 } elsif ($hasnoaccess) {
 8287:                     $access = 0; 
 8288:                 }
 8289:                 return $access;
 8290:             }
 8291:         } else {
 8292:             if ($domdef{$tool}{'default'} ne '') {
 8293:                 if ($domdef{$tool}{'default'}) {
 8294:                     $access = 1;
 8295:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8296:                     $access = 0;
 8297:                 }
 8298:                 return $access;
 8299:             }
 8300:         }
 8301:     } else {
 8302:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8303:             $access = 1;
 8304:         } else {
 8305:             $access = 0;
 8306:         }
 8307:         return $access;
 8308:     }
 8309: }
 8310: 
 8311: sub is_course_owner {
 8312:     my ($cdom,$cnum,$udom,$uname) = @_;
 8313:     if (($udom eq '') || ($uname eq '')) {
 8314:         $udom = $env{'user.domain'};
 8315:         $uname = $env{'user.name'};
 8316:     }
 8317:     unless (($udom eq '') || ($uname eq '')) {
 8318:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8319:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8320:                 return 1;
 8321:             } else {
 8322:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8323:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8324:                     return 1;
 8325:                 }
 8326:             }
 8327:         }
 8328:     }
 8329:     return;
 8330: }
 8331: 
 8332: sub is_advanced_user {
 8333:     my ($udom,$uname,$nocache) = @_;
 8334:     my ($is_adv,$is_author,$use_cache,$hashid);
 8335:     if ($udom ne '' && $uname ne '') {
 8336:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8337:             if (wantarray) {
 8338:                 return ($env{'user.adv'},$env{'user.author'});
 8339:             } else {
 8340:                 return $env{'user.adv'};
 8341:             }
 8342:         } elsif (!$nocache) {
 8343:             $use_cache = 1;
 8344:             $hashid = "$udom:$uname";  
 8345:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8346:             if ($cached) {
 8347:                 ($is_adv,$is_author) = split(/:/,$info);
 8348:                 if (wantarray) {
 8349:                     return ($is_adv,$is_author);
 8350:                 }
 8351:                 return $is_adv; 
 8352:             }
 8353:         }
 8354:     }
 8355:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8356:     my %allroles;
 8357:     foreach my $role (keys(%roleshash)) {
 8358:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8359:         my $area = '/'.$tdomain.'/'.$trest;
 8360:         if ($sec ne '') {
 8361:             $area .= '/'.$sec;
 8362:         }
 8363:         if (($area ne '') && ($trole ne '')) {
 8364:             my $spec=$trole.'.'.$area;
 8365:             if ($trole =~ /^cr\//) {
 8366:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8367:             } elsif ($trole ne 'gr') {
 8368:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8369:             }
 8370:             if ($trole eq 'au') {
 8371:                 $is_author = 1;
 8372:             }
 8373:         }
 8374:     }
 8375:     foreach my $role (keys(%allroles)) {
 8376:         last if ($is_adv);
 8377:         foreach my $item (split(/:/,$allroles{$role})) {
 8378:             if ($item ne '') {
 8379:                 my ($privilege,$restrictions)=split(/&/,$item);
 8380:                 if ($privilege eq 'adv') {
 8381:                     $is_adv = 1;
 8382:                     last;
 8383:                 }
 8384:             }
 8385:         }
 8386:     }
 8387:     if ($use_cache) {
 8388:         my $cachetime = 600;
 8389:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8390:     }
 8391:     if (wantarray) {
 8392:         return ($is_adv,$is_author);
 8393:     }
 8394:     return $is_adv;
 8395: }
 8396: 
 8397: sub check_can_request {
 8398:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8399:     my $canreq = 0;
 8400:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8401:         $uname = $env{'user.name'};
 8402:         $udom = $env{'user.domain'};
 8403:     }
 8404:     my ($types,$typename) = &Apache::loncommon::course_types();
 8405:     my @options = ('approval','validate','autolimit');
 8406:     my $optregex = join('|',@options);
 8407:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8408:         my %willtrust;
 8409:         foreach my $type (@{$types}) {
 8410:             if (&usertools_access($uname,$udom,$type,undef,
 8411:                                   'requestcourses')) {
 8412:                 $canreq ++;
 8413:                 if (ref($request_domains) eq 'HASH') {
 8414:                     push(@{$request_domains->{$type}},$udom);
 8415:                 }
 8416:                 if ($dom eq $udom) {
 8417:                     $can_request->{$type} = 1;
 8418:                 }
 8419:             }
 8420:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8421:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8422:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8423:                 if (@curr > 0) {
 8424:                     foreach my $item (@curr) {
 8425:                         if (ref($request_domains) eq 'HASH') {
 8426:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8427:                             if ($otherdom ne '') {
 8428:                                 unless (exists($willtrust{$otherdom})) {
 8429:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8430:                                 }
 8431:                                 if ($willtrust{$otherdom}) {
 8432:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8433:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8434:                                             push(@{$request_domains->{$type}},$otherdom);
 8435:                                         }
 8436:                                     } else {
 8437:                                         push(@{$request_domains->{$type}},$otherdom);
 8438:                                     }
 8439:                                 }
 8440:                             }
 8441:                         }
 8442:                     }
 8443:                     unless ($dom eq $env{'user.domain'}) {
 8444:                         $canreq ++;
 8445:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8446:                             $can_request->{$type} = 1;
 8447:                         }
 8448:                     }
 8449:                 }
 8450:             }
 8451:         }
 8452:     }
 8453:     return $canreq;
 8454: }
 8455: 
 8456: # ---------------------------------------------- Custom access rule evaluation
 8457: 
 8458: sub customaccess {
 8459:     my ($priv,$uri)=@_;
 8460:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8461:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8462:     $udom = &LONCAPA::clean_domain($udom);
 8463:     $ucrs = &LONCAPA::clean_username($ucrs);
 8464:     my $access=0;
 8465:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8466: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8467: 	if ($type eq 'user') {
 8468: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8469: 		my ($tdom,$tuname)=split(m{/},$scope);
 8470: 		if ($tdom) {
 8471: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8472: 		}
 8473: 		if ($tuname) {
 8474: 		    if ($tuname ne $env{'user.name'}) { next; }
 8475: 		}
 8476: 		$access=($effect eq 'allow');
 8477: 		last;
 8478: 	    }
 8479: 	} else {
 8480: 	    if ($role) {
 8481: 		if ($role ne $urole) { next; }
 8482: 	    }
 8483: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8484: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8485: 		if ($tdom) {
 8486: 		    if ($tdom ne $udom) { next; }
 8487: 		}
 8488: 		if ($tcrs) {
 8489: 		    if ($tcrs ne $ucrs) { next; }
 8490: 		}
 8491: 		if ($tsec) {
 8492: 		    if ($tsec ne $usec) { next; }
 8493: 		}
 8494: 		$access=($effect eq 'allow');
 8495: 		last;
 8496: 	    }
 8497: 	    if ($realm eq '' && $role eq '') {
 8498: 		$access=($effect eq 'allow');
 8499: 	    }
 8500: 	}
 8501:     }
 8502:     return $access;
 8503: }
 8504: 
 8505: # ------------------------------------------------- Check for a user privilege
 8506: 
 8507: sub allowed {
 8508:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8509:     my $ver_orguri=$uri;
 8510:     $uri=&deversion($uri);
 8511:     my $orguri=$uri;
 8512:     $uri=&declutter($uri);
 8513: 
 8514:     if ($priv eq 'evb') {
 8515: # Evade communication block restrictions for specified role in a course or domain
 8516:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8517:             return $1;
 8518:         } else {
 8519:             return;
 8520:         }
 8521:     }
 8522: 
 8523:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8524: # Free bre access to adm and meta resources
 8525:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8526: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8527: 	&& ($priv eq 'bre')) {
 8528: 	return 'F';
 8529:     }
 8530: 
 8531: # Free bre access to user's own portfolio contents
 8532:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8533:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8534: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8535:         my %setters;
 8536:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8537:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8538:         if (($startblock && $endblock) || ($by_ip)) {
 8539:             return 'B';
 8540:         } else {
 8541:             return 'F';
 8542:         }
 8543:     }
 8544: 
 8545: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8546:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8547:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8548:         if (exists($env{'request.course.id'})) {
 8549:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8550:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8551:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8552:                 my $courseprivid=$env{'request.course.id'};
 8553:                 $courseprivid=~s/\_/\//;
 8554:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8555:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8556:                     return $1; 
 8557:                 } else {
 8558:                     if ($env{'request.course.sec'}) {
 8559:                         $courseprivid.='/'.$env{'request.course.sec'};
 8560:                     }
 8561:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8562:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8563:                         return $2;
 8564:                     }
 8565:                 }
 8566:             }
 8567:         }
 8568:     }
 8569: 
 8570: # Free bre to public access
 8571: 
 8572:     if ($priv eq 'bre') {
 8573:         my $copyright;
 8574:         unless ($uri =~ /ext\.tool/) {
 8575:             $copyright=&metadata($uri,'copyright');
 8576:         }
 8577: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8578:            return 'F'; 
 8579:         }
 8580:         if ($copyright eq 'priv') {
 8581:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8582: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8583: 		return '';
 8584:             }
 8585:         }
 8586:         if ($copyright eq 'domain') {
 8587:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8588: 	    unless (($env{'user.domain'} eq $1) ||
 8589:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8590: 		return '';
 8591:             }
 8592:         }
 8593:         if ($env{'request.role'}=~ /li\.\//) {
 8594:             # Library role, so allow browsing of resources in this domain.
 8595:             return 'F';
 8596:         }
 8597:         if ($copyright eq 'custom') {
 8598: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8599:         }
 8600:     }
 8601:     # Domain coordinator is trying to create a course
 8602:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8603:         # uri is the requested domain in this case.
 8604:         # comparison to 'request.role.domain' shows if the user has selected
 8605:         # a role of dc for the domain in question.
 8606:         return 'F' if ($uri eq $env{'request.role.domain'});
 8607:     }
 8608: 
 8609:     my $thisallowed='';
 8610:     my $statecond=0;
 8611:     my $courseprivid='';
 8612: 
 8613:     my $ownaccess;
 8614:     # Community Coordinator or Assistant Co-author browsing resource space.
 8615:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8616:         if ($uri eq '') {
 8617:             $ownaccess = 1;
 8618:         } else {
 8619:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8620:                 my $udom = $env{'user.domain'};
 8621:                 my $uname = $env{'user.name'};
 8622:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8623:                     $ownaccess = 1;
 8624:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8625:                     unless ($uri =~ m{\.\./}) {
 8626:                         $ownaccess = 1;
 8627:                     }
 8628:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8629:                     my $now = time;
 8630:                     if ($uri =~ m{^([^/]+)/?$}) {
 8631:                         my $adom = $1;
 8632:                         foreach my $key (keys(%env)) {
 8633:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8634:                                 my ($start,$end) = split(/\./,$env{$key});
 8635:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8636:                                     $ownaccess = 1;
 8637:                                     last;
 8638:                                 }
 8639:                             }
 8640:                         }
 8641:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8642:                         my $adom = $1;
 8643:                         my $aname = $2;
 8644:                         foreach my $role ('ca','aa') { 
 8645:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8646:                                 my ($start,$end) =
 8647:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8648:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8649:                                     $ownaccess = 1;
 8650:                                     last;
 8651:                                 }
 8652:                             }
 8653:                         }
 8654:                     }
 8655:                 }
 8656:             }
 8657:         }
 8658:     }
 8659: 
 8660: # Course
 8661: 
 8662:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8663:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8664:             $thisallowed.=$1;
 8665:         }
 8666:     }
 8667: 
 8668: # Domain
 8669: 
 8670:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8671:        =~/\Q$priv\E\&([^\:]*)/) {
 8672:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8673:             $thisallowed.=$1;
 8674:         }
 8675:     }
 8676: 
 8677: # User who is not author or co-author might still be able to edit
 8678: # resource of an author in the domain (e.g., if Domain Coordinator).
 8679:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8680:         (&allowed('mdc',$env{'request.course.id'}))) {
 8681:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8682:             $thisallowed.=$1;
 8683:         }
 8684:     }
 8685: 
 8686: # Course: uri itself is a course
 8687:     my $courseuri=$uri;
 8688:     $courseuri=~s/\_(\d)/\/$1/;
 8689:     $courseuri=~s/^([^\/])/\/$1/;
 8690: 
 8691:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8692:        =~/\Q$priv\E\&([^\:]*)/) {
 8693:         if ($priv eq 'mip') {
 8694:             my $rem = $1;
 8695:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8696:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8697:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8698:                 if ($cdom ne '') {
 8699:                     my %passwdconf = &get_passwdconf($cdom);
 8700:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8701:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8702:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8703:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8704:                                 unless (@inststatuses) {
 8705:                                     @inststatuses = ('default');
 8706:                                 }
 8707:                                 foreach my $status (@inststatuses) {
 8708:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8709:                                         $thisallowed.=$rem;
 8710:                                     }
 8711:                                 }
 8712:                             }
 8713:                         }
 8714:                     }
 8715:                 }
 8716:             }
 8717:         } else {
 8718:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8719:                 $thisallowed.=$1;
 8720:             }
 8721:         }
 8722:     }
 8723: 
 8724: # URI is an uploaded document for this course, default permissions don't matter
 8725: # not allowing 'edit' access (editupload) to uploaded course docs
 8726:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8727: 	$thisallowed='';
 8728:         my ($match)=&is_on_map($uri);
 8729:         if ($match) {
 8730:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8731:                   =~/\Q$priv\E\&([^\:]*)/) {
 8732:                 my $value = $1;
 8733:                 my $deeplinkblock;
 8734:                 unless ($nodeeplinkcheck) {
 8735:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8736:                 }
 8737:                 if ($deeplinkblock) {
 8738:                     $thisallowed='D';
 8739:                 } elsif ($noblockcheck) {
 8740:                     $thisallowed.=$value;
 8741:                 } else {
 8742:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8743:                     if (@blockers > 0) {
 8744:                         $thisallowed = 'B';
 8745:                     } else {
 8746:                         $thisallowed.=$value;
 8747:                     }
 8748:                 }
 8749:             }
 8750:         } else {
 8751:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8752:             if ($refuri) {
 8753:                 if ($refuri =~ m|^/adm/|) {
 8754:                     $thisallowed='F';
 8755:                 } else {
 8756:                     $refuri=&declutter($refuri);
 8757:                     my ($match) = &is_on_map($refuri);
 8758:                     if ($match) {
 8759:                         my $deeplinkblock;
 8760:                         unless ($nodeeplinkcheck) {
 8761:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8762:                         }
 8763:                         if ($deeplinkblock) {
 8764:                             $thisallowed='D';
 8765:                         } elsif ($noblockcheck) {
 8766:                             $thisallowed='F';
 8767:                         } else {
 8768:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8769:                             if (@blockers > 0) {
 8770:                                 $thisallowed = 'B';
 8771:                             } else {
 8772:                                 $thisallowed='F';
 8773:                             }
 8774:                         }
 8775:                     }
 8776:                 }
 8777:             }
 8778:         }
 8779:     }
 8780: 
 8781:     if ($priv eq 'bre'
 8782: 	&& $thisallowed ne 'F' 
 8783: 	&& $thisallowed ne '2'
 8784: 	&& &is_portfolio_url($uri)) {
 8785: 	$thisallowed = &portfolio_access($uri,$clientip);
 8786:     }
 8787: 
 8788: # Full access at system, domain or course-wide level? Exit.
 8789:     if ($thisallowed=~/F/) {
 8790: 	return 'F';
 8791:     }
 8792: 
 8793: # If this is generating or modifying users, exit with special codes
 8794: 
 8795:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8796: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8797: 	    my ($audom,$auname)=split('/',$uri);
 8798: # no author name given, so this just checks on the general right to make a co-author in this domain
 8799: 	    unless ($auname) { return $thisallowed; }
 8800: # an author name is given, so we are about to actually make a co-author for a certain account
 8801: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8802: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8803: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8804: 	}
 8805: 	return $thisallowed;
 8806:     }
 8807: #
 8808: # Gathered so far: system, domain and course wide privileges
 8809: #
 8810: # Course: See if uri or referer is an individual resource that is part of 
 8811: # the course
 8812: 
 8813:     if ($env{'request.course.id'}) {
 8814: 
 8815:         if ($priv eq 'bre') {
 8816:             if (&is_coursetool_logo($uri)) {
 8817:                 return 'F';
 8818:             }
 8819:         }
 8820: 
 8821: # If this is modifying password (internal auth) domains must match for user and user's role.
 8822: 
 8823:         if ($priv eq 'mip') {
 8824:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8825:                 return $thisallowed;
 8826:             } else {
 8827:                 return '';
 8828:             }
 8829:         }
 8830: 
 8831:        $courseprivid=$env{'request.course.id'};
 8832:        if ($env{'request.course.sec'}) {
 8833:           $courseprivid.='/'.$env{'request.course.sec'};
 8834:        }
 8835:        $courseprivid=~s/\_/\//;
 8836:        my $checkreferer=1;
 8837:        my ($match,$cond)=&is_on_map($uri);
 8838:        if ($match) {
 8839:            $statecond=$cond;
 8840:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8841:                =~/\Q$priv\E\&([^\:]*)/) {
 8842:                my $value = $1;
 8843:                if ($priv eq 'bre') {
 8844:                    my $deeplinkblock;
 8845:                    unless ($nodeeplinkcheck) {
 8846:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8847:                    }
 8848:                    if ($deeplinkblock) {
 8849:                        $thisallowed = 'D';
 8850:                    } elsif ($noblockcheck) {
 8851:                        $thisallowed.=$value;
 8852:                    } else {
 8853:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8854:                        if (@blockers > 0) {
 8855:                            $thisallowed = 'B';
 8856:                        } else {
 8857:                            $thisallowed.=$value;
 8858:                        }
 8859:                    }
 8860:                } else {
 8861:                    $thisallowed.=$value;
 8862:                }
 8863:                $checkreferer=0;
 8864:            }
 8865:        }
 8866: 
 8867:        if ($checkreferer) {
 8868: 	  my $refuri=$env{'httpref.'.$orguri};
 8869:             unless ($refuri) {
 8870:                 foreach my $key (keys(%env)) {
 8871: 		    if ($key=~/^httpref\..*\*/) {
 8872: 			my $pattern=$key;
 8873:                         $pattern=~s/^httpref\.\/res\///;
 8874:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8875:                         $pattern=~s/\//\\\//g;
 8876:                         if ($orguri=~/$pattern/) {
 8877: 			    $refuri=$env{$key};
 8878:                         }
 8879:                     }
 8880:                 }
 8881:             }
 8882: 
 8883:          if ($refuri) { 
 8884: 	  $refuri=&declutter($refuri);
 8885:           my ($match,$cond)=&is_on_map($refuri);
 8886:             if ($match) {
 8887:               my $refstatecond=$cond;
 8888:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8889:                   =~/\Q$priv\E\&([^\:]*)/) {
 8890:                   my $value = $1;
 8891:                   if ($priv eq 'bre') {
 8892:                       my $deeplinkblock;
 8893:                       unless ($nodeeplinkcheck) {
 8894:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8895:                       }
 8896:                       if ($deeplinkblock) {
 8897:                           $thisallowed = 'D';
 8898:                       } elsif ($noblockcheck) {
 8899:                           $thisallowed.=$value;
 8900:                       } else {
 8901:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8902:                           if (@blockers > 0) {
 8903:                               $thisallowed = 'B';
 8904:                           } else {
 8905:                               $thisallowed.=$value;
 8906:                           }
 8907:                       }
 8908:                   } else {
 8909:                       $thisallowed.=$value;
 8910:                   }
 8911:                   $uri=$refuri;
 8912:                   $statecond=$refstatecond;
 8913:               }
 8914:           }
 8915:         }
 8916:        }
 8917:    }
 8918: 
 8919: #
 8920: # Gathered now: all privileges that could apply, and condition number
 8921: # 
 8922: #
 8923: # Full or no access?
 8924: #
 8925: 
 8926:     if ($thisallowed=~/F/) {
 8927: 	return 'F';
 8928:     }
 8929: 
 8930:     unless ($thisallowed) {
 8931:         return '';
 8932:     }
 8933: 
 8934: # Restrictions exist, deal with them
 8935: #
 8936: #   C:according to course preferences
 8937: #   R:according to resource settings
 8938: #   L:unless locked
 8939: #   X:according to user session state
 8940: #
 8941: 
 8942: # Possibly locked functionality, check all courses
 8943: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8944: # Locks might take effect only after 10 minutes cache expiration for other
 8945: # courses, and 2 minutes for current course, in which user has st or ta role
 8946: # which is neither expired nor a future role (unless current course).
 8947: 
 8948:     my ($needlockcheck,$now,$crsonly);
 8949:     if ($thisallowed=~/L/) {
 8950:         $now = time;
 8951:         if ($priv eq 'bre') {
 8952:             if ($uri ne '') {
 8953:                 if ($orguri =~ m{^/+res/}) {
 8954:                     if ($uri =~ m{^lib/templates/}) {
 8955:                         if ($env{'request.course.id'}) {
 8956:                             $crsonly = 1;
 8957:                             $needlockcheck = 1;
 8958:                         }
 8959:                     } else {
 8960:                         $needlockcheck = 1;
 8961:                     }
 8962:                 } elsif ($env{'request.course.id'}) {
 8963:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8964:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8965:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8966:                         $crsonly = 1;
 8967:                     }
 8968:                     $needlockcheck = 1;
 8969:                 }
 8970:             }
 8971:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8972:             $needlockcheck = 1;
 8973:         }
 8974:     }
 8975:     if ($needlockcheck) {
 8976:         foreach my $envkey (keys(%env)) {
 8977:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8978:                my $courseid=$2;
 8979:                my $roleid=$1.'.'.$2;
 8980:                $courseid=~s/^\///;
 8981:                unless ($env{'request.role'} eq $roleid) {
 8982:                    my ($start,$end) = split(/\./,$env{$envkey});
 8983:                    next unless (($now >= $start) && (!$end || $end > $now));
 8984:                }
 8985:                my $expiretime=600;
 8986:                if ($env{'request.role'} eq $roleid) {
 8987: 		  $expiretime=120;
 8988:                }
 8989: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8990:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8991:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8992: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8993:                }
 8994:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8995:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8996: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8997:                        &log($env{'user.domain'},$env{'user.name'},
 8998:                             $env{'user.home'},
 8999:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 9000:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9001:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9002: 		       return '';
 9003:                    }
 9004:                }
 9005:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 9006:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 9007: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 9008:                        &log($env{'user.domain'},$env{'user.name'},
 9009:                             $env{'user.home'},
 9010:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 9011:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 9012:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 9013: 		       return '';
 9014:                    }
 9015:                }
 9016: 	   }
 9017:        }
 9018:     }
 9019: 
 9020: #
 9021: # Rest of the restrictions depend on selected course
 9022: #
 9023: 
 9024:     unless ($env{'request.course.id'}) {
 9025: 	if ($thisallowed eq 'A') {
 9026: 	    return 'A';
 9027:         } elsif ($thisallowed eq 'B') {
 9028:             return 'B';
 9029: 	} else {
 9030: 	    return '1';
 9031: 	}
 9032:     }
 9033: 
 9034: #
 9035: # Now user is definitely in a course
 9036: #
 9037: 
 9038: 
 9039: # Course preferences
 9040: 
 9041:    if ($thisallowed=~/C/) {
 9042:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9043:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9044:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9045: 	   =~/\Q$rolecode\E/) {
 9046: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9047: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9048: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9049: 			$env{'request.course.id'});
 9050: 	   }
 9051:            return '';
 9052:        }
 9053: 
 9054:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9055: 	   =~/\Q$unamedom\E/) {
 9056: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9057: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9058: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9059: 			$env{'request.course.id'});
 9060: 	   }
 9061:            return '';
 9062:        }
 9063:    }
 9064: 
 9065: # Resource preferences
 9066: 
 9067:    if ($thisallowed=~/R/) {
 9068:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9069:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9070: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9071: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9072: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9073: 	   }
 9074: 	   return '';
 9075:        }
 9076:    }
 9077: 
 9078: # Restricted for deeplinked session?
 9079: 
 9080:     if ($env{'request.deeplink.login'}) {
 9081:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9082:             if (!$symb) { $symb=&symbread($uri,1); }
 9083:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9084:                 return '';
 9085:             }
 9086:         }
 9087:     }
 9088: 
 9089: # Restricted by state or randomout?
 9090: 
 9091:    if ($thisallowed=~/X/) {
 9092:       if ($env{'acc.randomout'}) {
 9093: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9094:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9095:             return ''; 
 9096:          }
 9097:       }
 9098:       if (&condval($statecond)) {
 9099: 	 return '2';
 9100:       } else {
 9101:          return '';
 9102:       }
 9103:    }
 9104: 
 9105:     if ($thisallowed eq 'A') {
 9106: 	return 'A';
 9107:     } elsif ($thisallowed eq 'B') {
 9108:         return 'B';
 9109:     } elsif ($thisallowed eq 'D') {
 9110:         return 'D';
 9111:     }
 9112:    return 'F';
 9113: }
 9114: 
 9115: # ------------------------------------------- Check construction space access
 9116: 
 9117: sub constructaccess {
 9118:     my ($url,$setpriv)=@_;
 9119: 
 9120: # We do not allow editing of previous versions of files
 9121:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9122: 
 9123: # Get username and domain from URL
 9124:     my ($ownername,$ownerdomain,$ownerhome);
 9125: 
 9126:     ($ownerdomain,$ownername) =
 9127:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9128: 
 9129: # The URL does not really point to any authorspace, forget it
 9130:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9131: 
 9132: # Now we need to see if the user has access to the authorspace of
 9133: # $ownername at $ownerdomain
 9134: 
 9135:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9136: # Real author for this?
 9137:        $ownerhome = $env{'user.home'};
 9138:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9139:           return ($ownername,$ownerdomain,$ownerhome);
 9140:        }
 9141:     } elsif (&is_course($ownerdomain,$ownername)) {
 9142: # Course Authoring Space?
 9143:         if ($env{'request.course.id'}) {
 9144:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9145:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9146:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9147:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9148:                     return ($ownername,$ownerdomain,$ownerhome);
 9149:                 }
 9150:             }
 9151:         }
 9152:         return '';
 9153:     } else {
 9154: # Co-author for this?
 9155:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9156:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9157:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9158:             return ($ownername,$ownerdomain,$ownerhome);
 9159:         }
 9160:     }
 9161: 
 9162: # We don't have any access right now. If we are not possibly going to do anything about this,
 9163: # we might as well leave
 9164:    unless ($setpriv) { return ''; }
 9165: 
 9166: # Backdoor access?
 9167:     my $allowed=&allowed('eco',$ownerdomain);
 9168: # Nope
 9169:     unless ($allowed) { return ''; }
 9170: # Looks like we may have access, but could be locked by the owner of the construction space
 9171:     if ($allowed eq 'U') {
 9172:         my %blocked=&get('environment',['domcoord.author'],
 9173:                          $ownerdomain,$ownername);
 9174: # Is blocked by owner
 9175:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9176:     }
 9177:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9178: # Grant temporary access
 9179:         my $then=$env{'user.login.time'};
 9180:         my $update=$env{'user.update.time'};
 9181:         if (!$update) { $update = $then; }
 9182:         my $refresh=$env{'user.refresh.time'};
 9183:         if (!$refresh) { $refresh = $update; }
 9184:         my $now = time;
 9185:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9186:                            $now,'ca','constructaccess');
 9187:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9188:         return($ownername,$ownerdomain,$ownerhome);
 9189:     }
 9190: # No business here
 9191:     return '';
 9192: }
 9193: 
 9194: # ----------------------------------------------------------- Content Blocking
 9195: 
 9196: {
 9197: # Caches for faster Course Contents display where content blocking
 9198: # is in operation (i.e., interval param set) for timed quiz.
 9199: #
 9200: # User for whom data are being temporarily cached.
 9201: my $cacheduser='';
 9202: # Course for which data are being temporarily cached.
 9203: my $cachedcid='';
 9204: # Cached blockers for this user (a hash of blocking items). 
 9205: my %cachedblockers=();
 9206: # When the data were last cached.
 9207: my $cachedlast='';
 9208: 
 9209: sub load_all_blockers {
 9210:     my ($uname,$udom)=@_;
 9211:     if (($uname ne '') && ($udom ne '')) { 
 9212:         if (($cacheduser eq $uname.':'.$udom) &&
 9213:             ($cachedcid eq $env{'request.course.id'}) &&
 9214:             (abs($cachedlast-time)<5)) {
 9215:             return;
 9216:         }
 9217:     }
 9218:     $cachedlast=time;
 9219:     $cacheduser=$uname.':'.$udom;
 9220:     $cachedcid=$env{'request.course.id'};
 9221:     %cachedblockers = &get_commblock_resources();
 9222:     return;
 9223: }
 9224: 
 9225: sub get_comm_blocks {
 9226:     my ($cdom,$cnum) = @_;
 9227:     if ($cdom eq '' || $cnum eq '') {
 9228:         return unless ($env{'request.course.id'});
 9229:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9230:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9231:     }
 9232:     my %commblocks;
 9233:     my $hashid=$cdom.'_'.$cnum;
 9234:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9235:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9236:         %commblocks = %{$blocksref};
 9237:     } else {
 9238:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9239:         my $cachetime = 600;
 9240:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9241:     }
 9242:     return %commblocks;
 9243: }
 9244: 
 9245: sub get_commblock_resources {
 9246:     my ($blocks) = @_;
 9247:     my %blockers = ();
 9248:     return %blockers unless ($env{'request.course.id'});
 9249:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9250:     if ($env{'request.course.sec'}) {
 9251:         $courseurl .= '/'.$env{'request.course.sec'};
 9252:     }
 9253:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9254:     my %commblocks;
 9255:     if (ref($blocks) eq 'HASH') {
 9256:         %commblocks = %{$blocks};
 9257:     } else {
 9258:         %commblocks = &get_comm_blocks();
 9259:     }
 9260:     return %blockers unless (keys(%commblocks) > 0); 
 9261:     my $navmap = Apache::lonnavmaps::navmap->new();
 9262:     return %blockers unless (ref($navmap));
 9263:     my $now = time;
 9264:     foreach my $block (keys(%commblocks)) {
 9265:         if ($block =~ /^(\d+)____(\d+)$/) {
 9266:             my ($start,$end) = ($1,$2);
 9267:             if ($start <= $now && $end >= $now) {
 9268:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9269:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9270:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9271:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9272:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9273:                             }
 9274:                         }
 9275:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9276:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9277:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9278:                             }
 9279:                         }
 9280:                     }
 9281:                 }
 9282:             }
 9283:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9284:             my $item = $1;
 9285:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9286:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9287:                     my (@interval,$mapname);
 9288:                     my $type = 'map';
 9289:                     if ($item eq 'course') {
 9290:                         $type = 'course';
 9291:                         @interval=&EXT("resource.0.interval");
 9292:                     } else {
 9293:                         if ($item =~ /___\d+___/) {
 9294:                             $type = 'resource';
 9295:                             @interval=&EXT("resource.0.interval",$item);
 9296:                         } else {
 9297:                             $mapname = &deversion($item);
 9298:                             if (ref($navmap)) {
 9299:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9300:                                 @interval = ($timelimit,'map');
 9301:                             }
 9302:                         }
 9303:                     }
 9304:                     if ($interval[0] =~ /^(\d+)/) {
 9305:                         my $timelimit = $1; 
 9306:                         my $first_access;
 9307:                         if ($type eq 'resource') {
 9308:                             $first_access=&get_first_access($interval[1],$item);
 9309:                         } elsif ($type eq 'map') {
 9310:                             $first_access=&get_first_access($interval[1],undef,$item);
 9311:                         } else {
 9312:                             $first_access=&get_first_access($interval[1]);
 9313:                         }
 9314:                         if ($first_access) {
 9315:                             my $timesup = $first_access+$timelimit;
 9316:                             if ($timesup > $now) {
 9317:                                 my $activeblock;
 9318:                                 if ($type eq 'resource') {
 9319:                                     if (ref($navmap)) {
 9320:                                         my $res = $navmap->getBySymb($item);
 9321:                                         if ($res->answerable()) {
 9322:                                             $activeblock = 1;
 9323:                                         }
 9324:                                     }
 9325:                                 } elsif ($type eq 'map') {
 9326:                                     my $mapsymb = &symbread($mapname,1);
 9327:                                     if (($mapsymb) && (ref($navmap))) {
 9328:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9329:                                         if (ref($mapres)) {
 9330:                                             my $first = $mapres->map_start();
 9331:                                             my $finish = $mapres->map_finish();
 9332:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9333:                                             if (ref($it)) {
 9334:                                                 my $res;
 9335:                                                 while ($res = $it->next(undef,1)) {
 9336:                                                     next unless (ref($res));
 9337:                                                     my $symb = $res->symb();
 9338:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9339:                                                     @interval=&EXT("resource.0.interval",$symb);
 9340:                                                     if ($interval[1] eq 'map') {
 9341:                                                         if ($res->answerable()) {
 9342:                                                             $activeblock = 1;
 9343:                                                             last;
 9344:                                                         }
 9345:                                                     }
 9346:                                                 }
 9347:                                             }
 9348:                                         }
 9349:                                     }
 9350:                                 }
 9351:                                 if ($activeblock) {
 9352:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9353:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9354:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9355:                                          }
 9356:                                     }
 9357:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9358:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9359:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9360:                                         }
 9361:                                     }
 9362:                                 }
 9363:                             }
 9364:                         }
 9365:                     }
 9366:                 }
 9367:             }
 9368:         }
 9369:     }
 9370:     return %blockers;
 9371: }
 9372: 
 9373: sub has_comm_blocking {
 9374:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9375:     my @blockers;
 9376:     return unless ($env{'request.course.id'});
 9377:     return unless ($priv eq 'bre');
 9378:     return if ($env{'request.state'} eq 'construct');
 9379:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9380:     if ($env{'request.course.sec'}) {
 9381:         $courseurl .= '/'.$env{'request.course.sec'};
 9382:     }
 9383:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9384:     my %blockinfo;
 9385:     if (ref($blocks) eq 'HASH') {
 9386:         %blockinfo = &get_commblock_resources($blocks);
 9387:     } else {
 9388:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9389:         %blockinfo = %cachedblockers;
 9390:     }
 9391:     return unless (keys(%blockinfo) > 0);
 9392:     my (%possibles,@symbs);
 9393:     if (!$symb) {
 9394:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9395:     }
 9396:     if ($symb) {
 9397:         @symbs = ($symb);
 9398:     } elsif (keys(%possibles)) { 
 9399:         @symbs = keys(%possibles);
 9400:     }
 9401:     my $noblock;
 9402:     foreach my $symb (@symbs) {
 9403:         last if ($noblock);
 9404:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9405:         foreach my $block (keys(%blockinfo)) {
 9406:             if ($block =~ /^firstaccess____(.+)$/) {
 9407:                 my $item = $1;
 9408:                 unless ($blocked) {
 9409:                     if (($item eq $map) || ($item eq $symb)) {
 9410:                         $noblock = 1;
 9411:                         last;
 9412:                     }
 9413:                 }
 9414:             }
 9415:             if (ref($blockinfo{$block}) eq 'HASH') {
 9416:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9417:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9418:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9419:                             push(@blockers,$block);
 9420:                         }
 9421:                     }
 9422:                 }
 9423:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9424:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9425:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9426:                             push(@blockers,$block);
 9427:                         }
 9428:                     }
 9429:                 }
 9430:             }
 9431:         }
 9432:     }
 9433:     unless ($noblock) { 
 9434:         return @blockers;
 9435:     }
 9436:     return;
 9437: }
 9438: }
 9439: 
 9440: sub deeplink_check {
 9441:     my ($priv,$symb,$uri) = @_;
 9442:     return unless ($env{'request.course.id'});
 9443:     return unless ($priv eq 'bre');
 9444:     return if ($env{'request.state'} eq 'construct');
 9445:     return if ($env{'request.role.adv'});
 9446:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9447:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9448:     my (%possibles,@symbs);
 9449:     if (!$symb) {
 9450:         $symb = &symbread($uri,1,1,1,\%possibles);
 9451:     }
 9452:     if ($symb) {
 9453:         @symbs = ($symb);
 9454:     } elsif (keys(%possibles)) {
 9455:         @symbs = keys(%possibles);
 9456:     }
 9457: 
 9458:     my ($deeplink_symb,$allow);
 9459:     if ($env{'request.deeplink.login'}) {
 9460:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9461:     }
 9462:     foreach my $symb (@symbs) {
 9463:         last if ($allow);
 9464:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9465:         if ($deeplink eq '') {
 9466:             $allow = 1;
 9467:         } else {
 9468:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9469:             if ($state ne 'only') {
 9470:                 $allow = 1;
 9471:             } else {
 9472:                 my $check_deeplink_entry;
 9473:                 if ($protect ne 'none') {
 9474:                     my ($acctype,$item) = split(/:/,$protect);
 9475:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9476:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9477:                             $check_deeplink_entry = 1
 9478:                         }
 9479:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9480:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9481:                             $check_deeplink_entry = 1;
 9482:                         }
 9483:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9484:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9485:                             $check_deeplink_entry = 1;
 9486:                         }
 9487:                     }
 9488:                 }
 9489:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9490:                     if ($scope eq 'res') {
 9491:                         if ($symb eq $deeplink_symb) {
 9492:                             $allow = 1;
 9493:                         }
 9494:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9495:                         my ($map_from_symb,$map_from_login);
 9496:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9497:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9498:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9499:                         } else {
 9500:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9501:                         }
 9502:                         if (($map_from_symb) && ($map_from_login)) {
 9503:                             if ($map_from_symb eq $map_from_login) {
 9504:                                 $allow = 1;
 9505:                             } elsif ($scope eq 'rec') {
 9506:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9507:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9508:                                     $allow = 1;
 9509:                                 }
 9510:                             }
 9511:                         }
 9512:                     }
 9513:                 }
 9514:             }
 9515:         }
 9516:     }
 9517:     return if ($allow);
 9518:     return 1;
 9519: }
 9520: 
 9521: # -------------------------------- Deversion and split uri into path an filename   
 9522: 
 9523: #
 9524: #   Removes the version from a URI and
 9525: #   splits it in to its filename and path to the filename.
 9526: #   Seems like File::Basename could have done this more clearly.
 9527: #   Parameters:
 9528: #      $uri   - input URI
 9529: #   Returns:
 9530: #     Two element list consisting of 
 9531: #     $pathname  - the URI up to and excluding the trailing /
 9532: #     $filename  - The part of the URI following the last /
 9533: #  NOTE:
 9534: #    Another realization of this is simply:
 9535: #    use File::Basename;
 9536: #    ...
 9537: #    $uri = shift;
 9538: #    $filename = basename($uri);
 9539: #    $path     = dirname($uri);
 9540: #    return ($filename, $path);
 9541: #
 9542: #     The implementation below is probably faster however.
 9543: #
 9544: sub split_uri_for_cond {
 9545:     my $uri=&deversion(&declutter(shift));
 9546:     my @uriparts=split(/\//,$uri);
 9547:     my $filename=pop(@uriparts);
 9548:     my $pathname=join('/',@uriparts);
 9549:     return ($pathname,$filename);
 9550: }
 9551: # --------------------------------------------------- Is a resource on the map?
 9552: 
 9553: sub is_on_map {
 9554:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9555:     #Trying to find the conditional for the file
 9556:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9557: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9558:     if ($match) {
 9559: 	return (1,$1);
 9560:     } else {
 9561: 	return (0,0);
 9562:     }
 9563: }
 9564: 
 9565: # --------------------------------------------------------- Get symb from alias
 9566: 
 9567: sub get_symb_from_alias {
 9568:     my $symb=shift;
 9569:     my ($map,$resid,$url)=&decode_symb($symb);
 9570: # Already is a symb
 9571:     if ($url) { return $symb; }
 9572: # Must be an alias
 9573:     my $aliassymb='';
 9574:     my %bighash;
 9575:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9576:                             &GDBM_READER(),0640)) {
 9577:         my $rid=$bighash{'mapalias_'.$symb};
 9578: 	if ($rid) {
 9579: 	    my ($mapid,$resid)=split(/\./,$rid);
 9580: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9581: 				    $resid,$bighash{'src_'.$rid});
 9582: 	}
 9583:         untie %bighash;
 9584:     }
 9585:     return $aliassymb;
 9586: }
 9587: 
 9588: # ----------------------------------------------------------------- Define Role
 9589: 
 9590: sub definerole {
 9591:   if (allowed('mcr','/')) {
 9592:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9593:     foreach my $role (split(':',$sysrole)) {
 9594: 	my ($crole,$cqual)=split(/\&/,$role);
 9595:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9596:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9597: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9598:                return "refused:s:$crole&$cqual"; 
 9599:             }
 9600:         }
 9601:     }
 9602:     foreach my $role (split(':',$domrole)) {
 9603: 	my ($crole,$cqual)=split(/\&/,$role);
 9604:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9605:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9606: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9607:                return "refused:d:$crole&$cqual"; 
 9608:             }
 9609:         }
 9610:     }
 9611:     foreach my $role (split(':',$courole)) {
 9612: 	my ($crole,$cqual)=split(/\&/,$role);
 9613:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9614:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9615: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9616:                return "refused:c:$crole&$cqual"; 
 9617:             }
 9618:         }
 9619:     }
 9620:     my $uhome;
 9621:     if (($uname ne '') && ($udom ne '')) {
 9622:         $uhome = &homeserver($uname,$udom);
 9623:         return $uhome if ($uhome eq 'no_host');
 9624:     } else {
 9625:         $uname = $env{'user.name'};
 9626:         $udom = $env{'user.domain'};
 9627:         $uhome = $env{'user.home'};
 9628:     }
 9629:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9630:                 "$udom:$uname:rolesdef_$rolename=".
 9631:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9632:     return reply($command,$uhome);
 9633:   } else {
 9634:     return 'refused';
 9635:   }
 9636: }
 9637: 
 9638: # ---------------- Make a metadata query against the network of library servers
 9639: 
 9640: sub metadata_query {
 9641:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9642:     my %rhash;
 9643:     my %libserv = &all_library();
 9644:     my @server_list = (defined($server_array) ? @$server_array
 9645:                                               : keys(%libserv) );
 9646:     for my $server (@server_list) {
 9647:         my $domains = ''; 
 9648:         if (ref($domains_hash) eq 'HASH') {
 9649:             $domains = $domains_hash->{$server}; 
 9650:         }
 9651: 	unless ($custom or $customshow) {
 9652: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9653: 	    $rhash{$server}=$reply;
 9654: 	}
 9655: 	else {
 9656: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9657: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9658: 			     $server);
 9659: 	    $rhash{$server}=$reply;
 9660: 	}
 9661:     }
 9662:     return \%rhash;
 9663: }
 9664: 
 9665: # ----------------------------------------- Send log queries and wait for reply
 9666: 
 9667: sub log_query {
 9668:     my ($uname,$udom,$query,%filters)=@_;
 9669:     my $uhome=&homeserver($uname,$udom);
 9670:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9671:     my $uhost=&hostname($uhome);
 9672:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9673:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9674:                        $uhome);
 9675:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9676:     return get_query_reply($queryid);
 9677: }
 9678: 
 9679: # -------------------------- Update MySQL table for portfolio file
 9680: 
 9681: sub update_portfolio_table {
 9682:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9683:     if ($group ne '') {
 9684:         $file_name =~s /^\Q$group\E//;
 9685:     }
 9686:     my $homeserver = &homeserver($uname,$udom);
 9687:     my $queryid=
 9688:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9689:                ':'.&escape($file_name).':'.$action,$homeserver);
 9690:     my $reply = &get_query_reply($queryid);
 9691:     return $reply;
 9692: }
 9693: 
 9694: # -------------------------- Update MySQL allusers table
 9695: 
 9696: sub update_allusers_table {
 9697:     my ($uname,$udom,$names) = @_;
 9698:     my $homeserver = &homeserver($uname,$udom);
 9699:     my $queryid=
 9700:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9701:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9702:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9703:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9704:                'generation='.&escape($names->{'generation'}).'%%'.
 9705:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9706:                'id='.&escape($names->{'id'}),$homeserver);
 9707:     return;
 9708: }
 9709: 
 9710: # ------- Request retrieval of institutional classlists for course(s)
 9711: 
 9712: sub fetch_enrollment_query {
 9713:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9714:     my ($homeserver,$sleep,$loopmax);
 9715:     my $maxtries = 1;
 9716:     if ($context eq 'automated') {
 9717:         $homeserver = $perlvar{'lonHostID'};
 9718:         $sleep = 2;
 9719:         $loopmax = 100;
 9720:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9721:     } else {
 9722:         $homeserver = &homeserver($cnum,$dom);
 9723:     }
 9724:     my $host=&hostname($homeserver);
 9725:     my $cmd = '';
 9726:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9727:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9728:     }
 9729:     $cmd =~ s/%%$//;
 9730:     $cmd = &escape($cmd);
 9731:     my $query = 'fetchenrollment';
 9732:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9733:     unless ($queryid=~/^\Q$host\E\_/) { 
 9734:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9735:         return 'error: '.$queryid;
 9736:     }
 9737:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9738:     my $tries = 1;
 9739:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9740:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9741:         $tries ++;
 9742:     }
 9743:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9744:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9745:     } else {
 9746:         my @responses = split(/:/,$reply);
 9747:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9748:             foreach my $line (@responses) {
 9749:                 my ($key,$value) = split(/=/,$line,2);
 9750:                 $$replyref{$key} = $value;
 9751:             }
 9752:         } else {
 9753:             my $pathname = LONCAPA::tempdir();
 9754:             foreach my $line (@responses) {
 9755:                 my ($key,$value) = split(/=/,$line);
 9756:                 $$replyref{$key} = $value;
 9757:                 if ($value > 0) {
 9758:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9759:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9760:                         my $destname = $pathname.'/'.$filename;
 9761:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9762:                         if ($xml_classlist =~ /^error/) {
 9763:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9764:                         } else {
 9765:                             if ( open(FILE,">",$destname) ) {
 9766:                                 print FILE &unescape($xml_classlist);
 9767:                                 close(FILE);
 9768:                             } else {
 9769:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9770:                             }
 9771:                         }
 9772:                     }
 9773:                 }
 9774:             }
 9775:         }
 9776:         return 'ok';
 9777:     }
 9778:     return 'error';
 9779: }
 9780: 
 9781: sub get_query_reply {
 9782:     my ($queryid,$sleep,$loopmax) = @_;
 9783:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9784:         $sleep = 0.2;
 9785:     }
 9786:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9787:         $loopmax = 100;
 9788:     }
 9789:     my $replyfile=LONCAPA::tempdir().$queryid;
 9790:     my $reply='';
 9791:     for (1..$loopmax) {
 9792: 	sleep($sleep);
 9793:         if (-e $replyfile.'.end') {
 9794: 	    if (open(my $fh,"<",$replyfile)) {
 9795: 		$reply = join('',<$fh>);
 9796: 		close($fh);
 9797: 	   } else { return 'error: reply_file_error'; }
 9798:            return &unescape($reply);
 9799: 	}
 9800:     }
 9801:     return 'timeout:'.$queryid;
 9802: }
 9803: 
 9804: sub courselog_query {
 9805: #
 9806: # possible filters:
 9807: # url: url or symb
 9808: # username
 9809: # domain
 9810: # action: view, submit, grade
 9811: # start: timestamp
 9812: # end: timestamp
 9813: #
 9814:     my (%filters)=@_;
 9815:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9816:     if ($filters{'url'}) {
 9817: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9818:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9819:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9820:     }
 9821:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9822:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9823:     return &log_query($cname,$cdom,'courselog',%filters);
 9824: }
 9825: 
 9826: sub userlog_query {
 9827: #
 9828: # possible filters:
 9829: # action: log check role
 9830: # start: timestamp
 9831: # end: timestamp
 9832: #
 9833:     my ($uname,$udom,%filters)=@_;
 9834:     return &log_query($uname,$udom,'userlog',%filters);
 9835: }
 9836: 
 9837: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9838: 
 9839: sub auto_run {
 9840:     my ($cnum,$cdom) = @_;
 9841:     my $response = 0;
 9842:     my $settings;
 9843:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9844:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9845:         $settings = $domconfig{'autoenroll'};
 9846:         if ($settings->{'run'} eq '1') {
 9847:             $response = 1;
 9848:         }
 9849:     } else {
 9850:         my $homeserver;
 9851:         if (&is_course($cdom,$cnum)) {
 9852:             $homeserver = &homeserver($cnum,$cdom);
 9853:         } else {
 9854:             $homeserver = &domain($cdom,'primary');
 9855:         }
 9856:         if ($homeserver ne 'no_host') {
 9857:             $response = &reply('autorun:'.$cdom,$homeserver);
 9858:         }
 9859:     }
 9860:     return $response;
 9861: }
 9862: 
 9863: sub auto_get_sections {
 9864:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9865:     my $homeserver;
 9866:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9867:         $homeserver = &homeserver($cnum,$cdom);
 9868:     }
 9869:     if (!defined($homeserver)) { 
 9870:         if ($cdom =~ /^$match_domain$/) {
 9871:             $homeserver = &domain($cdom,'primary');
 9872:         }
 9873:     }
 9874:     my @secs;
 9875:     if (defined($homeserver)) {
 9876:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9877:         unless ($response eq 'refused') {
 9878:             @secs = split(/:/,$response);
 9879:         }
 9880:     }
 9881:     return @secs;
 9882: }
 9883: 
 9884: sub auto_new_course {
 9885:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9886:     my $homeserver = &homeserver($cnum,$cdom);
 9887:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9888:     return $response;
 9889: }
 9890: 
 9891: sub auto_validate_courseID {
 9892:     my ($cnum,$cdom,$inst_course_id) = @_;
 9893:     my $homeserver = &homeserver($cnum,$cdom);
 9894:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9895:     return $response;
 9896: }
 9897: 
 9898: sub auto_validate_instcode {
 9899:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9900:     my ($homeserver,$response);
 9901:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9902:         $homeserver = &homeserver($cnum,$cdom);
 9903:     }
 9904:     if (!defined($homeserver)) {
 9905:         if ($cdom =~ /^$match_domain$/) {
 9906:             $homeserver = &domain($cdom,'primary');
 9907:         }
 9908:     }
 9909:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9910:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9911:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9912:     return ($outcome,$description,$defaultcredits);
 9913: }
 9914: 
 9915: sub auto_validate_inst_crosslist {
 9916:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9917:     my ($homeserver,$response);
 9918:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9919:         $homeserver = &homeserver($cnum,$cdom);
 9920:     }
 9921:     if (!defined($homeserver)) {
 9922:         if ($cdom =~ /^$match_domain$/) {
 9923:             $homeserver = &domain($cdom,'primary');
 9924:         }
 9925:     }
 9926:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9927:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9928:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9929:                          &escape($coowner),$homeserver);
 9930:     }
 9931:     return $response;
 9932: }
 9933: 
 9934: sub auto_create_password {
 9935:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9936:     my ($homeserver,$response);
 9937:     my $create_passwd = 0;
 9938:     my $authchk = '';
 9939:     if ($udom =~ /^$match_domain$/) {
 9940:         $homeserver = &domain($udom,'primary');
 9941:     }
 9942:     if ($homeserver eq '') {
 9943:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9944:             $homeserver = &homeserver($cnum,$cdom);
 9945:         }
 9946:     }
 9947:     if ($homeserver eq '') {
 9948:         $authchk = 'nodomain';
 9949:     } else {
 9950:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9951:         if ($response eq 'refused') {
 9952:             $authchk = 'refused';
 9953:         } else {
 9954:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9955:         }
 9956:     }
 9957:     return ($authparam,$create_passwd,$authchk);
 9958: }
 9959: 
 9960: sub auto_photo_permission {
 9961:     my ($cnum,$cdom,$students) = @_;
 9962:     my $homeserver = &homeserver($cnum,$cdom);
 9963:     my ($outcome,$perm_reqd,$conditions) = 
 9964: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9965:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9966: 	return (undef,undef);
 9967:     }
 9968:     return ($outcome,$perm_reqd,$conditions);
 9969: }
 9970: 
 9971: sub auto_checkphotos {
 9972:     my ($uname,$udom,$pid) = @_;
 9973:     my $homeserver = &homeserver($uname,$udom);
 9974:     my ($result,$resulttype);
 9975:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9976: 				   &escape($uname).':'.&escape($pid),
 9977: 				   $homeserver));
 9978:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9979: 	return (undef,undef);
 9980:     }
 9981:     if ($outcome) {
 9982:         ($result,$resulttype) = split(/:/,$outcome);
 9983:     } 
 9984:     return ($result,$resulttype);
 9985: }
 9986: 
 9987: sub auto_photochoice {
 9988:     my ($cnum,$cdom) = @_;
 9989:     my $homeserver = &homeserver($cnum,$cdom);
 9990:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9991: 						       &escape($cdom),
 9992: 						       $homeserver)));
 9993:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9994: 	return (undef,undef);
 9995:     }
 9996:     return ($update,$comment);
 9997: }
 9998: 
 9999: sub auto_photoupdate {
10000:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
10001:     my $homeserver = &homeserver($cnum,$dom);
10002:     my $host=&hostname($homeserver);
10003:     my $cmd = '';
10004:     my $maxtries = 1;
10005:     foreach my $affiliate (keys(%{$affiliatesref})) {
10006:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
10007:     }
10008:     $cmd =~ s/%%$//;
10009:     $cmd = &escape($cmd);
10010:     my $query = 'institutionalphotos';
10011:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10012:     unless ($queryid=~/^\Q$host\E\_/) {
10013:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10014:         return 'error: '.$queryid;
10015:     }
10016:     my $reply = &get_query_reply($queryid);
10017:     my $tries = 1;
10018:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10019:         $reply = &get_query_reply($queryid);
10020:         $tries ++;
10021:     }
10022:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10023:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10024:     } else {
10025:         my @responses = split(/:/,$reply);
10026:         my $outcome = shift(@responses); 
10027:         foreach my $item (@responses) {
10028:             my ($key,$value) = split(/=/,$item);
10029:             $$photo{$key} = $value;
10030:         }
10031:         return $outcome;
10032:     }
10033:     return 'error';
10034: }
10035: 
10036: sub auto_instcode_format {
10037:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10038: 	$cat_order) = @_;
10039:     my $courses = '';
10040:     my @homeservers;
10041:     if ($caller eq 'global') {
10042: 	my %servers = &get_servers($codedom,'library');
10043: 	foreach my $tryserver (keys(%servers)) {
10044: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10045: 		push(@homeservers,$tryserver);
10046: 	    }
10047:         }
10048:     } elsif ($caller eq 'requests') {
10049:         if ($codedom =~ /^$match_domain$/) {
10050:             my $chome = &domain($codedom,'primary');
10051:             unless ($chome eq 'no_host') {
10052:                 push(@homeservers,$chome);
10053:             }
10054:         }
10055:     } else {
10056:         push(@homeservers,&homeserver($caller,$codedom));
10057:     }
10058:     foreach my $code (keys(%{$instcodes})) {
10059:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10060:     }
10061:     chop($courses);
10062:     my $ok_response = 0;
10063:     my $response;
10064:     while (@homeservers > 0 && $ok_response == 0) {
10065:         my $server = shift(@homeservers); 
10066:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10067:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10068:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10069: 		split(/:/,$response);
10070:             %{$codes} = (%{$codes},&str2hash($codes_str));
10071:             push(@{$codetitles},&str2array($codetitles_str));
10072:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10073:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10074:             $ok_response = 1;
10075:         }
10076:     }
10077:     if ($ok_response) {
10078:         return 'ok';
10079:     } else {
10080:         return $response;
10081:     }
10082: }
10083: 
10084: sub auto_instcode_defaults {
10085:     my ($domain,$returnhash,$code_order) = @_;
10086:     my @homeservers;
10087: 
10088:     my %servers = &get_servers($domain,'library');
10089:     foreach my $tryserver (keys(%servers)) {
10090: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10091: 	    push(@homeservers,$tryserver);
10092: 	}
10093:     }
10094: 
10095:     my $response;
10096:     foreach my $server (@homeservers) {
10097:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10098:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10099: 	
10100: 	foreach my $pair (split(/\&/,$response)) {
10101: 	    my ($name,$value)=split(/\=/,$pair);
10102: 	    if ($name eq 'code_order') {
10103: 		@{$code_order} = split(/\&/,&unescape($value));
10104: 	    } else {
10105: 		$returnhash->{&unescape($name)}=&unescape($value);
10106: 	    }
10107: 	}
10108: 	return 'ok';
10109:     }
10110: 
10111:     return $response;
10112: }
10113: 
10114: sub auto_possible_instcodes {
10115:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10116:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10117:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10118:         return;
10119:     }
10120:     my (@homeservers,$uhome);
10121:     if (defined(&domain($domain,'primary'))) {
10122:         $uhome=&domain($domain,'primary');
10123:         push(@homeservers,&domain($domain,'primary'));
10124:     } else {
10125:         my %servers = &get_servers($domain,'library');
10126:         foreach my $tryserver (keys(%servers)) {
10127:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10128:                 push(@homeservers,$tryserver);
10129:             }
10130:         }
10131:     }
10132:     my $response;
10133:     foreach my $server (@homeservers) {
10134:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10135:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10136:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10137:             split(':',$response);
10138:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10139:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10140:         foreach my $item (split('&',$cat_title)) {   
10141:             my ($name,$value)=split('=',$item);
10142:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10143:         }
10144:         foreach my $item (split('&',$cat_order)) {
10145:             my ($name,$value)=split('=',$item);
10146:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10147:         }
10148:         return 'ok';
10149:     }
10150:     return $response;
10151: }
10152: 
10153: sub auto_courserequest_checks {
10154:     my ($dom) = @_;
10155:     my ($homeserver,%validations);
10156:     if ($dom =~ /^$match_domain$/) {
10157:         $homeserver = &domain($dom,'primary');
10158:     }
10159:     unless ($homeserver eq 'no_host') {
10160:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10161:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10162:             my @items = split(/&/,$response);
10163:             foreach my $item (@items) {
10164:                 my ($key,$value) = split('=',$item);
10165:                 $validations{&unescape($key)} = &thaw_unescape($value);
10166:             }
10167:         }
10168:     }
10169:     return %validations; 
10170: }
10171: 
10172: sub auto_courserequest_validation {
10173:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10174:     my ($homeserver,$response);
10175:     if ($dom =~ /^$match_domain$/) {
10176:         $homeserver = &domain($dom,'primary');
10177:     }
10178:     unless ($homeserver eq 'no_host') {
10179:         my $customdata;
10180:         if (ref($custominfo) eq 'HASH') {
10181:             $customdata = &freeze_escape($custominfo);
10182:         }
10183:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10184:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10185:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10186:                                     $customdata,$homeserver));
10187:     }
10188:     return $response;
10189: }
10190: 
10191: sub auto_validate_class_sec {
10192:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10193:     my $homeserver = &homeserver($cnum,$cdom);
10194:     my $ownerlist;
10195:     if (ref($owners) eq 'ARRAY') {
10196:         $ownerlist = join(',',@{$owners});
10197:     } else {
10198:         $ownerlist = $owners;
10199:     }
10200:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10201:                         &escape($ownerlist).':'.$cdom,$homeserver);
10202:     return $response;
10203: }
10204: 
10205: sub auto_instsec_reformat {
10206:     my ($cdom,$action,$instsecref) = @_;
10207:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10208:     my @homeservers;
10209:     if (defined(&domain($cdom,'primary'))) {
10210:         push(@homeservers,&domain($cdom,'primary'));
10211:     } else {
10212:         my %servers = &get_servers($cdom,'library');
10213:         foreach my $tryserver (keys(%servers)) {
10214:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10215:                 push(@homeservers,$tryserver);
10216:             }
10217:         }
10218:     }
10219:     my $response;
10220:     my %reformatted = %{$instsecref};
10221:     foreach my $server (@homeservers) {
10222:         if (ref($instsecref) eq 'HASH') {
10223:             my $info = &freeze_escape($instsecref);
10224:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10225:                                 $action.':'.$info,$server);
10226:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10227:             my @items = split(/&/,$response);
10228:             foreach my $item (@items) {
10229:                 my ($key,$value) = split(/=/,$item);
10230:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10231:             }
10232:         }
10233:     }
10234:     return %reformatted;
10235: }
10236: 
10237: sub auto_validate_instclasses {
10238:     my ($cdom,$cnum,$owners,$classesref) = @_;
10239:     my ($homeserver,%validations);
10240:     $homeserver = &homeserver($cnum,$cdom);
10241:     unless ($homeserver eq 'no_host') {
10242:         my $ownerlist;
10243:         if (ref($owners) eq 'ARRAY') {
10244:             $ownerlist = join(',',@{$owners});
10245:         } else {
10246:             $ownerlist = $owners;
10247:         }
10248:         if (ref($classesref) eq 'HASH') {
10249:             my $classes = &freeze_escape($classesref);
10250:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10251:                                 ':'.$cdom.':'.$classes,$homeserver);
10252:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10253:                 my @items = split(/&/,$response);
10254:                 foreach my $item (@items) {
10255:                     my ($key,$value) = split('=',$item);
10256:                     $validations{&unescape($key)} = &thaw_unescape($value);
10257:                 }
10258:             }
10259:         }
10260:     }
10261:     return %validations;
10262: }
10263: 
10264: sub auto_crsreq_update {
10265:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10266:         $code,$accessstart,$accessend,$inbound) = @_;
10267:     my ($homeserver,%crsreqresponse);
10268:     if ($cdom =~ /^$match_domain$/) {
10269:         $homeserver = &domain($cdom,'primary');
10270:     }
10271:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10272:         my $info;
10273:         if (ref($inbound) eq 'HASH') {
10274:             $info = &freeze_escape($inbound);
10275:         }
10276:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10277:                             ':'.&escape($action).':'.&escape($ownername).':'.
10278:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10279:                             &escape($title).':'.&escape($code).':'.
10280:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10281:                             $homeserver);
10282:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10283:             my @items = split(/&/,$response);
10284:             foreach my $item (@items) {
10285:                 my ($key,$value) = split('=',$item);
10286:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10287:             }
10288:         }
10289:     }
10290:     return \%crsreqresponse;
10291: }
10292: 
10293: sub auto_export_grades {
10294:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10295:     my ($homeserver,%exportresponse);
10296:     if ($cdom =~ /^$match_domain$/) {
10297:         $homeserver = &domain($cdom,'primary');
10298:     }
10299:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10300:         my $info;
10301:         if (ref($inforef) eq 'HASH') {
10302:             $info = &freeze_escape($inforef);
10303:         }
10304:         if (ref($gradesref) eq 'HASH') {
10305:             my $grades = &freeze_escape($gradesref);
10306:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10307:                                 $info.':'.$grades,$homeserver);
10308:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10309:                 my @items = split(/&/,$response);
10310:                 foreach my $item (@items) {
10311:                     my ($key,$value) = split('=',$item);
10312:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10313:                 }
10314:             }
10315:         }
10316:     }
10317:     return \%exportresponse;
10318: }
10319: 
10320: sub check_instcode_cloning {
10321:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10322:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10323:         return;
10324:     }
10325:     my $canclone;
10326:     if (@{$code_order} > 0) {
10327:         my $instcoderegexp ='^';
10328:         my @clonecodes = split(/\&/,$cloner);
10329:         foreach my $item (@{$code_order}) {
10330:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10331:                 foreach my $pair (@clonecodes) {
10332:                     my ($key,$val) = split(/\=/,$pair,2);
10333:                     $val = &unescape($val);
10334:                     if ($key eq $item) {
10335:                         $instcoderegexp .= '('.$val.')';
10336:                         last;
10337:                     }
10338:                 }
10339:             } else {
10340:                 $instcoderegexp .= $codedefaults->{$item};
10341:             }
10342:         }
10343:         $instcoderegexp .= '$';
10344:         my (@from,@to);
10345:         eval {
10346:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10347:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10348:         };
10349:         if ((@from > 0) && (@to > 0)) {
10350:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10351:             if (!@diffs) {
10352:                 $canclone = 1;
10353:             }
10354:         }
10355:     }
10356:     return $canclone;
10357: }
10358: 
10359: sub default_instcode_cloning {
10360:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10361:     my (%codedefaults,@code_order,$canclone);
10362:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10363:         %codedefaults = %{$codedefaultsref};
10364:         @code_order = @{$codeorderref};
10365:     } elsif ($clonedom) {
10366:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10367:     }
10368:     if (($domdefclone) && (@code_order)) {
10369:         my @clonecodes = split(/\+/,$domdefclone);
10370:         my $instcoderegexp ='^';
10371:         foreach my $item (@code_order) {
10372:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10373:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10374:             } else {
10375:                 $instcoderegexp .= $codedefaults{$item};
10376:             }
10377:         }
10378:         $instcoderegexp .= '$';
10379:         my (@from,@to);
10380:         eval {
10381:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10382:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10383:         };
10384:         if ((@from > 0) && (@to > 0)) {
10385:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10386:             if (!@diffs) {
10387:                 $canclone = 1;
10388:             }
10389:         }
10390:     }
10391:     return $canclone;
10392: }
10393: 
10394: # ------------------------------------------------------- Course Group routines
10395: 
10396: sub get_coursegroups {
10397:     my ($cdom,$cnum,$group,$namespace) = @_;
10398:     return(&dump($namespace,$cdom,$cnum,$group));
10399: }
10400: 
10401: sub modify_coursegroup {
10402:     my ($cdom,$cnum,$groupsettings) = @_;
10403:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10404: }
10405: 
10406: sub toggle_coursegroup_status {
10407:     my ($cdom,$cnum,$group,$action) = @_;
10408:     my ($from_namespace,$to_namespace);
10409:     if ($action eq 'delete') {
10410:         $from_namespace = 'coursegroups';
10411:         $to_namespace = 'deleted_groups';
10412:     } else {
10413:         $from_namespace = 'deleted_groups';
10414:         $to_namespace = 'coursegroups';
10415:     }
10416:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10417:     if (my $tmp = &error(%curr_group)) {
10418:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10419:         return ('read error',$tmp);
10420:     } else {
10421:         my %savedsettings = %curr_group; 
10422:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10423:         my $deloutcome;
10424:         if ($result eq 'ok') {
10425:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10426:         } else {
10427:             return ('write error',$result);
10428:         }
10429:         if ($deloutcome eq 'ok') {
10430:             return 'ok';
10431:         } else {
10432:             return ('delete error',$deloutcome);
10433:         }
10434:     }
10435: }
10436: 
10437: sub modify_group_roles {
10438:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10439:         $othdomby,$requester) = @_;
10440:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10441:     my $role = 'gr/'.&escape($userprivs);
10442:     my ($uname,$udom) = split(/:/,$user);
10443:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10444:                              $othdomby,$requester);
10445:     if ($result eq 'ok') {
10446:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10447:     }
10448:     return $result;
10449: }
10450: 
10451: sub modify_coursegroup_membership {
10452:     my ($cdom,$cnum,$membership) = @_;
10453:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10454:     return $result;
10455: }
10456: 
10457: sub get_active_groups {
10458:     my ($udom,$uname,$cdom,$cnum) = @_;
10459:     my $now = time;
10460:     my %groups = ();
10461:     foreach my $key (keys(%env)) {
10462:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10463:             my ($start,$end) = split(/\./,$env{$key});
10464:             if (($end!=0) && ($end<$now)) { next; }
10465:             if (($start!=0) && ($start>$now)) { next; }
10466:             if ($1 eq $cdom && $2 eq $cnum) {
10467:                 $groups{$3} = $env{$key} ;
10468:             }
10469:         }
10470:     }
10471:     return %groups;
10472: }
10473: 
10474: sub get_group_membership {
10475:     my ($cdom,$cnum,$group) = @_;
10476:     return(&dump('groupmembership',$cdom,$cnum,$group));
10477: }
10478: 
10479: sub get_users_groups {
10480:     my ($udom,$uname,$courseid) = @_;
10481:     my @usersgroups;
10482:     my $cachetime=1800;
10483: 
10484:     my $hashid="$udom:$uname:$courseid";
10485:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10486:     if (defined($cached)) {
10487:         @usersgroups = split(/:/,$grouplist);
10488:     } else {  
10489:         $grouplist = '';
10490:         my $courseurl = &courseid_to_courseurl($courseid);
10491:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10492:         my $access_end = $env{'course.'.$courseid.
10493:                               '.default_enrollment_end_date'};
10494:         my $now = time;
10495:         foreach my $key (keys(%roleshash)) {
10496:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10497:                 my $group = $1;
10498:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10499:                     my $start = $2;
10500:                     my $end = $1;
10501:                     if ($start == -1) { next; } # deleted from group
10502:                     if (($start!=0) && ($start>$now)) { next; }
10503:                     if (($end!=0) && ($end<$now)) {
10504:                         if ($access_end && $access_end < $now) {
10505:                             if ($access_end - $end < 86400) {
10506:                                 push(@usersgroups,$group);
10507:                             }
10508:                         }
10509:                         next;
10510:                     }
10511:                     push(@usersgroups,$group);
10512:                 }
10513:             }
10514:         }
10515:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10516:         $grouplist = join(':',@usersgroups);
10517:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10518:     }
10519:     return @usersgroups;
10520: }
10521: 
10522: sub devalidate_getgroups_cache {
10523:     my ($udom,$uname,$cdom,$cnum)=@_;
10524:     my $courseid = $cdom.'_'.$cnum;
10525: 
10526:     my $hashid="$udom:$uname:$courseid";
10527:     &devalidate_cache_new('getgroups',$hashid);
10528: }
10529: 
10530: # ------------------------------------------------------------------ Plain Text
10531: 
10532: sub plaintext {
10533:     my ($short,$type,$cid,$forcedefault) = @_;
10534:     if ($short =~ m{^cr/}) {
10535: 	return (split('/',$short))[-1];
10536:     }
10537:     if (!defined($cid)) {
10538:         $cid = $env{'request.course.id'};
10539:     }
10540:     my %rolenames = (
10541:                       Course    => 'std',
10542:                       Community => 'alt1',
10543:                       Placement => 'std',
10544:                     );
10545:     if ($cid ne '') {
10546:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10547:             unless ($forcedefault) {
10548:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10549:                 &Apache::lonlocal::mt_escape(\$roletext);
10550:                 return &Apache::lonlocal::mt($roletext);
10551:             }
10552:         }
10553:     }
10554:     if ((defined($type)) && (defined($rolenames{$type})) &&
10555:         (defined($rolenames{$type})) && 
10556:         (defined($prp{$short}{$rolenames{$type}}))) {
10557:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10558:     } elsif ($cid ne '') {
10559:         my $crstype = $env{'course.'.$cid.'.type'};
10560:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10561:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10562:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10563:         }
10564:     }
10565:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10566: }
10567: 
10568: # ----------------------------------------------------------------- Assign Role
10569: 
10570: sub assignrole {
10571:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10572:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10573:     my $mrole;
10574:     if ($role =~ /^cr\//) {
10575:         my $cwosec=$url;
10576:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10577:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10578:             my $refused = 1;
10579:             if ($context eq 'requestcourses') {
10580:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10581:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10582:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10583:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10584:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10585:                             if ($crsenv{'internal.courseowner'} eq
10586:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10587:                                 $refused = '';
10588:                             }
10589:                         }
10590:                     }
10591:                 }
10592:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10593:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10594:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10595:                 my $key = "$uname:$udom:$role:$sec";
10596:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10597:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10598:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10599:                         $refused = '';
10600:                     }
10601:                 }
10602:             }
10603:             if ($refused) {
10604:                 &logthis('Refused custom assignrole: '.
10605:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10606:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10607:                 return 'refused';
10608:             }
10609:         }
10610:         $mrole='cr';
10611:     } elsif ($role =~ /^gr\//) {
10612:         my $cwogrp=$url;
10613:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10614:         if (!&allowed('mdg',$cwogrp)) {
10615:             my $refused = 1;
10616:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10617:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10618:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10619:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10620:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10621:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10622:                         $refused = '';
10623:                     }
10624:                 }
10625:             }
10626:             if ($refused) {
10627:                 &logthis('Refused group assignrole: '.
10628:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10629:                          $env{'user.name'}.' at '.$env{'user.domain'});
10630:                 return 'refused';
10631:             }
10632:         }
10633:         $mrole='gr';
10634:     } else {
10635:         my $cwosec=$url;
10636:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10637:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10638:             my $refused;
10639:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10640:                 if (!(&allowed('c'.$role,$url))) {
10641:                     $refused = 1;
10642:                 }
10643:             } else {
10644:                 $refused = 1;
10645:             }
10646:             if ($refused) {
10647:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10648:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10649:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10650:                     my %crsenv;
10651:                     if ($role eq 'cc' || $role eq 'co') {
10652:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10653:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10654:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10655:                                 if ($crsenv{'internal.courseowner'} eq 
10656:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10657:                                     $refused = '';
10658:                                 }
10659:                             }
10660:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10661:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10662:                                 if ($crsenv{'internal.courseowner'} eq 
10663:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10664:                                     $refused = '';
10665:                                 }
10666:                             }
10667:                         }
10668:                     }
10669:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10670:                     if ($role eq 'st') {
10671:                         $refused = '';
10672:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10673:                         $refused = '';
10674:                     }
10675:                 } elsif ($othdomby eq 'othdombyuser') {
10676:                     my ($key,%queuedrolereq);
10677:                     if ($context eq 'course') {
10678:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10679:                         $key = "$uname:$udom:$role:$sec";
10680:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10681:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10682:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10683:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10684:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10685:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10686:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10687:                                         $refused = '';
10688:                                     }
10689:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10690:                                     $refused = '';
10691:                                 }
10692:                             }
10693:                         }
10694:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10695:                         my $key = "$uname:$udom:$role"; 
10696:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10697:                         if (($audom ne '') && ($auname ne '')) {
10698:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10699:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10700:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10701:                                     $refused = '';
10702:                                 }
10703:                             }
10704:                         }
10705:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10706:                         my $key = "$uname:$udom:$role";
10707:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10708:                         if ($roledom ne '') {
10709:                             my $confname = $roledom.'-domainconfig';
10710:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10711:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10712:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10713:                                     $refused = '';
10714:                                 }
10715:                             }
10716:                         }
10717:                     }
10718:                 } elsif ($context eq 'requestcourses') {
10719:                     my @possroles = ('st','ta','ep','in','cc','co');
10720:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10721:                         my $wrongcc;
10722:                         if ($cnum =~ /^$match_community$/) {
10723:                             $wrongcc = 1 if ($role eq 'cc');
10724:                         } else {
10725:                             $wrongcc = 1 if ($role eq 'co');
10726:                         }
10727:                         unless ($wrongcc) {
10728:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10729:                             if ($crsenv{'internal.courseowner'} eq 
10730:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10731:                                 $refused = '';
10732:                             }
10733:                         }
10734:                     }
10735:                 } elsif ($context eq 'requestauthor') {
10736:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10737:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10738:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10739:                             $refused = '';
10740:                         } else {
10741:                             my %domdefaults = &get_domain_defaults($udom);
10742:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10743:                                 my $checkbystatus;
10744:                                 if ($env{'user.adv'}) { 
10745:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10746:                                     if ($disposition eq 'automatic') {
10747:                                         $refused = '';
10748:                                     } elsif ($disposition eq '') {
10749:                                         $checkbystatus = 1;
10750:                                     } 
10751:                                 } else {
10752:                                     $checkbystatus = 1;
10753:                                 }
10754:                                 if ($checkbystatus) {
10755:                                     if ($env{'environment.inststatus'}) {
10756:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10757:                                         foreach my $type (@inststatuses) {
10758:                                             if (($type ne '') &&
10759:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10760:                                                 $refused = '';
10761:                                             }
10762:                                         }
10763:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10764:                                         $refused = '';
10765:                                     }
10766:                                 }
10767:                             }
10768:                         }
10769:                     }
10770:                 }
10771:                 if ($refused) {
10772:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10773:                              ' '.$role.' '.$end.' '.$start.' by '.
10774: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10775:                     return 'refused';
10776:                 }
10777:             }
10778:         } elsif ($role eq 'au') {
10779:             if ($url ne '/'.$udom.'/') {
10780:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10781:                          ' to assign author role for '.$uname.':'.$udom.
10782:                          ' in domain: '.$url.' refused (wrong domain).');
10783:                 return 'refused';
10784:             }
10785:         }
10786:         $mrole=$role;
10787:     }
10788:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10789:                 "$udom:$uname:$url".'_'."$mrole=$role";
10790:     if ($end) { $command.='_'.$end; }
10791:     if ($start) {
10792: 	if ($end) { 
10793:            $command.='_'.$start; 
10794:         } else {
10795:            $command.='_0_'.$start;
10796:         }
10797:     }
10798:     my $origstart = $start;
10799:     my $origend = $end;
10800:     my $delflag;
10801: # actually delete
10802:     if ($deleteflag) {
10803: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10804: # modify command to delete the role
10805:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10806:                 "$udom:$uname:$url".'_'."$mrole";
10807: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10808: # set start and finish to negative values for userrolelog
10809:            $start=-1;
10810:            $end=-1;
10811:            $delflag = 1;
10812:         }
10813:     }
10814: # send command
10815:     my $answer=&reply($command,&homeserver($uname,$udom));
10816: # log new user role if status is ok
10817:     if ($answer eq 'ok') {
10818: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10819:         if (($role eq 'cc') || ($role eq 'in') ||
10820:             ($role eq 'ep') || ($role eq 'ad') ||
10821:             ($role eq 'ta') || ($role eq 'st') ||
10822:             ($role=~/^cr/) || ($role eq 'gr') ||
10823:             ($role eq 'co')) {
10824: # for course roles, perform group memberships changes triggered by role change.
10825:             unless ($role =~ /^gr/) {
10826:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10827:                                                  $origstart,$selfenroll,$context);
10828:             }
10829:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10830:                            $selfenroll,$context,$othdomby,$requester);
10831:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10832:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10833:                  ($role eq 'da')) {
10834:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10835:                            $context,$othdomby,$requester);
10836:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10837:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10838:                              $context,$othdomby,$requester); 
10839:         }
10840:         if ($role eq 'cc') {
10841:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10842:         }
10843:     }
10844:     return $answer;
10845: }
10846: 
10847: sub autoupdate_coowners {
10848:     my ($url,$end,$start,$uname,$udom) = @_;
10849:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10850:     if (($cdom ne '') && ($cnum ne '')) {
10851:         my $now = time;
10852:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10853:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10854:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10855:             my $instcode = $coursehash{'internal.coursecode'};
10856:             my $xlists = $coursehash{'internal.crosslistings'};
10857:             if ($instcode ne '') {
10858:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10859:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10860:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10861:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10862:                         unless ($result eq 'valid') {
10863:                             if ($xlists ne '') {
10864:                                 foreach my $xlist (split(',',$xlists)) {
10865:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10866:                                     $result =
10867:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10868:                                                                       $inst_crosslist,$uname.':'.$udom);
10869:                                     last if ($result eq 'valid');
10870:                                 }
10871:                             }
10872:                         }
10873:                         if ($result eq 'valid') {
10874:                             if ($coursehash{'internal.co-owners'}) {
10875:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10876:                                     push(@newcoowners,$coowner);
10877:                                 }
10878:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10879:                                     push(@newcoowners,$uname.':'.$udom);
10880:                                 }
10881:                                 @newcoowners = sort(@newcoowners);
10882:                             } else {
10883:                                 push(@newcoowners,$uname.':'.$udom);
10884:                             }
10885:                         } elsif ($coursehash{'internal.co-owners'}) {
10886:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10887:                                 unless ($coowner eq $uname.':'.$udom) {
10888:                                     push(@newcoowners,$coowner);
10889:                                 }
10890:                             }
10891:                             unless (@newcoowners > 0) {
10892:                                 $delcoowners = 1;
10893:                                 $coowners = '';
10894:                             }
10895:                         }
10896:                         if (@newcoowners || $delcoowners) {
10897:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10898:                                             $delcoowners,@newcoowners);
10899:                         }
10900:                     }
10901:                 }
10902:             }
10903:         }
10904:     }
10905: }
10906: 
10907: sub store_coowners {
10908:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10909:     my $cid = $cdom.'_'.$cnum;
10910:     my ($coowners,$delresult,$putresult);
10911:     if (@newcoowners) {
10912:         $coowners = join(',',@newcoowners);
10913:         my %coownershash = (
10914:                             'internal.co-owners' => $coowners,
10915:                            );
10916:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10917:         if ($putresult eq 'ok') {
10918:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10919:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10920:             }
10921:         }
10922:     }
10923:     if ($delcoowners) {
10924:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10925:         if ($delresult eq 'ok') {
10926:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10927:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10928:             }
10929:         }
10930:     }
10931:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10932:         my %crsinfo =
10933:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10934:         if (ref($crsinfo{$cid}) eq 'HASH') {
10935:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10936:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
10937:         }
10938:     }
10939: }
10940: 
10941: # -------------------------------------------------- Modify user authentication
10942: # Overrides without validation
10943: 
10944: sub modifyuserauth {
10945:     my ($udom,$uname,$umode,$upass)=@_;
10946:     my $uhome=&homeserver($uname,$udom);
10947:     my $allowed;
10948:     if (&allowed('mau',$udom)) {
10949:         $allowed = 1;
10950:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10951:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10952:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10953:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10954:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10955:         if (($cdom ne '') && ($cnum ne '')) {
10956:             my $is_owner = &is_course_owner($cdom,$cnum);
10957:             if ($is_owner) {
10958:                 $allowed = 1;
10959:             }
10960:         }
10961:     }
10962:     unless ($allowed) { return 'refused'; }
10963:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10964:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10965:              ' in domain '.$env{'request.role.domain'});  
10966:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10967: 		     &escape($upass),$uhome);
10968:     my $ip = &get_requestor_ip();
10969:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10970:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10971:          '(Remote '.$ip.'): '.$reply);
10972:     &log($udom,,$uname,$uhome,
10973:         'Authentication changed by '.$env{'user.domain'}.', '.
10974:                                      $env{'user.name'}.', '.$umode.
10975:          '(Remote '.$ip.'): '.$reply);
10976:     unless ($reply eq 'ok') {
10977:         &logthis('Authentication mode error: '.$reply);
10978: 	return 'error: '.$reply;
10979:     }   
10980:     return 'ok';
10981: }
10982: 
10983: # --------------------------------------------------------------- Modify a user
10984: 
10985: sub modifyuser {
10986:     my ($udom,    $uname, $uid,
10987:         $umode,   $upass, $first,
10988:         $middle,  $last,  $gene,
10989:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10990:     $udom= &LONCAPA::clean_domain($udom);
10991:     $uname=&LONCAPA::clean_username($uname);
10992:     my $showcandelete = 'none';
10993:     if (ref($candelete) eq 'ARRAY') {
10994:         if (@{$candelete} > 0) {
10995:             $showcandelete = join(', ',@{$candelete});
10996:         }
10997:     }
10998:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10999:              $umode.', '.$first.', '.$middle.', '.
11000: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
11001:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11002:                                      ' desiredhome not specified'). 
11003:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11004:              ' in domain '.$env{'request.role.domain'});
11005:     my $uhome=&homeserver($uname,$udom,'true');
11006:     my $newuser;
11007:     if ($uhome eq 'no_host') {
11008:         $newuser = 1;
11009:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11010:                 ($umode eq 'lti')) {
11011:             return 'error: more information needed to create new user';
11012:         }
11013:     }
11014: # ----------------------------------------------------------------- Create User
11015:     if (($uhome eq 'no_host') && 
11016: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
11017:         my $unhome='';
11018:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
11019:             $unhome = $desiredhome;
11020: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11021: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
11022:         } else { # load balancing routine for determining $unhome
11023:             my $loadm=10000000;
11024: 	    my %servers = &get_servers($udom,'library');
11025: 	    foreach my $tryserver (keys(%servers)) {
11026: 		my $answer=reply('load',$tryserver);
11027: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
11028: 		    $loadm=$answer;
11029: 		    $unhome=$tryserver;
11030: 		}
11031: 	    }
11032:         }
11033:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11034: 	    return 'error: unable to find a home server for '.$uname.
11035:                    ' in domain '.$udom;
11036:         }
11037:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11038:                          &escape($upass),$unhome);
11039: 	unless ($reply eq 'ok') {
11040:             return 'error: '.$reply;
11041:         }   
11042:         $uhome=&homeserver($uname,$udom,'true');
11043:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11044: 	    return 'error: unable verify users home machine.';
11045:         }
11046:     }   # End of creation of new user
11047: # ---------------------------------------------------------------------- Add ID
11048:     if ($uid) {
11049:        $uid=~tr/A-Z/a-z/;
11050:        my %uidhash=&idrget($udom,$uname);
11051:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11052:          && (!$forceid)) {
11053: 	  unless ($uid eq $uidhash{$uname}) {
11054: 	      return 'error: user id "'.$uid.'" does not match '.
11055:                   'current user id "'.$uidhash{$uname}.'".';
11056:           }
11057:        } else {
11058: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11059:        }
11060:     }
11061: # -------------------------------------------------------------- Add names, etc
11062:     my @tmp=&get('environment',
11063: 		   ['firstname','middlename','lastname','generation','id',
11064:                     'permanentemail','inststatus'],
11065: 		   $udom,$uname);
11066:     my (%names,%oldnames);
11067:     if ($tmp[0] =~ m/^error:.*/) { 
11068:         %names=(); 
11069:     } else {
11070:         %names = @tmp;
11071:         %oldnames = %names;
11072:     }
11073: #
11074: # If name, email and/or uid are blank (e.g., because an uploaded file
11075: # of users did not contain them), do not overwrite existing values
11076: # unless field is in $candelete array ref.  
11077: #
11078: 
11079:     my @fields = ('firstname','middlename','lastname','generation',
11080:                   'permanentemail','id');
11081:     my %newvalues;
11082:     if (ref($candelete) eq 'ARRAY') {
11083:         foreach my $field (@fields) {
11084:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11085:                 if ($field eq 'firstname') {
11086:                     $names{$field} = $first;
11087:                 } elsif ($field eq 'middlename') {
11088:                     $names{$field} = $middle;
11089:                 } elsif ($field eq 'lastname') {
11090:                     $names{$field} = $last;
11091:                 } elsif ($field eq 'generation') { 
11092:                     $names{$field} = $gene;
11093:                 } elsif ($field eq 'permanentemail') {
11094:                     $names{$field} = $email;
11095:                 } elsif ($field eq 'id') {
11096:                     $names{$field}  = $uid;
11097:                 }
11098:             }
11099:         }
11100:     }
11101:     if ($first)  { $names{'firstname'}  = $first; }
11102:     if (defined($middle)) { $names{'middlename'} = $middle; }
11103:     if ($last)   { $names{'lastname'}   = $last; }
11104:     if (defined($gene))   { $names{'generation'} = $gene; }
11105:     if ($email) {
11106:        $email=~s/[^\w\@\.\-\,]//gs;
11107:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11108:     }
11109:     if ($uid) { $names{'id'}  = $uid; }
11110:     if (defined($inststatus)) {
11111:         $names{'inststatus'} = '';
11112:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11113:         if (ref($usertypes) eq 'HASH') {
11114:             my @okstatuses; 
11115:             foreach my $item (split(/:/,$inststatus)) {
11116:                 if (defined($usertypes->{$item})) {
11117:                     push(@okstatuses,$item);  
11118:                 }
11119:             }
11120:             if (@okstatuses) {
11121:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11122:             }
11123:         }
11124:     }
11125:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11126:                  $umode.', '.$first.', '.$middle.', '.
11127:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11128:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11129:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11130:     } else {
11131:         $logmsg .= ' during self creation';
11132:     }
11133:     my $changed;
11134:     if ($newuser) {
11135:         $changed = 1;
11136:     } else {
11137:         foreach my $field (@fields) {
11138:             if ($names{$field} ne $oldnames{$field}) {
11139:                 $changed = 1;
11140:                 last;
11141:             }
11142:         }
11143:     }
11144:     unless ($changed) {
11145:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11146:         &logthis($logmsg);
11147:         return 'ok';
11148:     }
11149:     my $reply = &put('environment', \%names, $udom,$uname);
11150:     if ($reply ne 'ok') { 
11151:         return 'error: '.$reply;
11152:     }
11153:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11154:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11155:     }
11156:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11157:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11158:     $logmsg = 'Success modifying user '.$logmsg;
11159:     &logthis($logmsg);
11160:     return 'ok';
11161: }
11162: 
11163: # -------------------------------------------------------------- Modify student
11164: 
11165: sub modifystudent {
11166:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11167:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11168:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11169:     if (!$cid) {
11170: 	unless ($cid=$env{'request.course.id'}) {
11171: 	    return 'not_in_class';
11172: 	}
11173:     }
11174: # --------------------------------------------------------------- Make the user
11175:     my $reply=&modifyuser
11176: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11177:          $desiredhome,$email,$inststatus);
11178:     unless ($reply eq 'ok') { return $reply; }
11179:     # This will cause &modify_student_enrollment to get the uid from the
11180:     # student's environment
11181:     $uid = undef if (!$forceid);
11182:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11183:                                         $gene,$usec,$end,$start,$type,$locktype,
11184:                                         $cid,$selfenroll,$context,$credits,$instsec);
11185:     return $reply;
11186: }
11187: 
11188: sub modify_student_enrollment {
11189:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11190:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11191:     my ($cdom,$cnum,$chome);
11192:     if (!$cid) {
11193: 	unless ($cid=$env{'request.course.id'}) {
11194: 	    return 'not_in_class';
11195: 	}
11196: 	$cdom=$env{'course.'.$cid.'.domain'};
11197: 	$cnum=$env{'course.'.$cid.'.num'};
11198:     } else {
11199: 	($cdom,$cnum)=split(/_/,$cid);
11200:     }
11201:     $chome=$env{'course.'.$cid.'.home'};
11202:     if (!$chome) {
11203: 	$chome=&homeserver($cnum,$cdom);
11204:     }
11205:     if (!$chome) { return 'unknown_course'; }
11206:     # Make sure the user exists
11207:     my $uhome=&homeserver($uname,$udom);
11208:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11209: 	return 'error: no such user';
11210:     }
11211:     # Get student data if we were not given enough information
11212:     if (!defined($first)  || $first  eq '' || 
11213:         !defined($last)   || $last   eq '' || 
11214:         !defined($uid)    || $uid    eq '' || 
11215:         !defined($middle) || $middle eq '' || 
11216:         !defined($gene)   || $gene   eq '') {
11217:         # They did not supply us with enough data to enroll the student, so
11218:         # we need to pick up more information.
11219:         my %tmp = &get('environment',
11220:                        ['firstname','middlename','lastname', 'generation','id']
11221:                        ,$udom,$uname);
11222: 
11223:         #foreach my $key (keys(%tmp)) {
11224:         #    &logthis("key $key = ".$tmp{$key});
11225:         #}
11226:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11227:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11228:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11229:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11230:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11231:     }
11232:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11233:     my $user = "$uname:$udom";
11234:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11235:     my $reply=cput('classlist',
11236: 		   {$user => 
11237: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11238: 		   $cdom,$cnum);
11239:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11240:         &devalidate_getsection_cache($udom,$uname,$cid);
11241:     } else { 
11242: 	return 'error: '.$reply;
11243:     }
11244:     # Add student role to user
11245:     my $uurl='/'.$cid;
11246:     $uurl=~s/\_/\//g;
11247:     if ($usec) {
11248: 	$uurl.='/'.$usec;
11249:     }
11250:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11251:                              $selfenroll,$context,$othdomby,$requester);
11252:     if ($result ne 'ok') {
11253:         if ($old_entry{$user} ne '') {
11254:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11255:         } else {
11256:             $reply = &del('classlist',[$user],$cdom,$cnum);
11257:         }
11258:     }
11259:     return $result; 
11260: }
11261: 
11262: sub format_name {
11263:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11264:     my $name;
11265:     if ($first ne 'lastname') {
11266: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11267:     } else {
11268: 	if ($lastname=~/\S/) {
11269: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11270: 	    $name=~s/\s+,/,/;
11271: 	} else {
11272: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11273: 	}
11274:     }
11275:     $name=~s/^\s+//;
11276:     $name=~s/\s+$//;
11277:     $name=~s/\s+/ /g;
11278:     return $name;
11279: }
11280: 
11281: # ------------------------------------------------- Write to course preferences
11282: 
11283: sub writecoursepref {
11284:     my ($courseid,%prefs)=@_;
11285:     $courseid=~s/^\///;
11286:     $courseid=~s/\_/\//g;
11287:     my ($cdomain,$cnum)=split(/\//,$courseid);
11288:     my $chome=homeserver($cnum,$cdomain);
11289:     if (($chome eq '') || ($chome eq 'no_host')) { 
11290: 	return 'error: no such course';
11291:     }
11292:     my $cstring='';
11293:     foreach my $pref (keys(%prefs)) {
11294: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11295:     }
11296:     $cstring=~s/\&$//;
11297:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11298: }
11299: 
11300: # ---------------------------------------------------------- Make/modify course
11301: 
11302: sub createcourse {
11303:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11304:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11305:     $url=&declutter($url);
11306:     my $cid='';
11307:     if ($context eq 'requestcourses') {
11308:         my $can_create = 0;
11309:         my ($ownername,$ownerdom) = split(':',$course_owner);
11310:         if ($udom eq $ownerdom) {
11311:             my $reload;
11312:             if (($callercontext eq 'auto') &&
11313:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11314:                 $reload = 'reload';
11315:             }
11316:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11317:                                   $context)) {
11318:                 $can_create = 1;
11319:             }
11320:         } else {
11321:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11322:                                            $category);
11323:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11324:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11325:                 if (@curr > 0) {
11326:                     my @options = qw(approval validate autolimit);
11327:                     my $optregex = join('|',@options);
11328:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11329:                         $can_create = 1;
11330:                     }
11331:                 }
11332:             }
11333:         }
11334:         if ($can_create) {
11335:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11336:                 unless (&allowed('ccc',$udom)) {
11337:                     return 'refused'; 
11338:                 }
11339:             }
11340:         } else {
11341:             return 'refused';
11342:         }
11343:     } elsif (!&allowed('ccc',$udom)) {
11344:         return 'refused';
11345:     }
11346: # --------------------------------------------------------------- Get Unique ID
11347:     my $uname;
11348:     if ($cnum =~ /^$match_courseid$/) {
11349:         my $chome=&homeserver($cnum,$udom,'true');
11350:         if (($chome eq '') || ($chome eq 'no_host')) {
11351:             $uname = $cnum;
11352:         } else {
11353:             $uname = &generate_coursenum($udom,$crstype);
11354:         }
11355:     } else {
11356:         $uname = &generate_coursenum($udom,$crstype);
11357:     }
11358:     return $uname if ($uname =~ /^error/);
11359: # -------------------------------------------------- Check supplied server name
11360:     if (!defined($course_server)) {
11361:         if (defined(&domain($udom,'primary'))) {
11362:             $course_server = &domain($udom,'primary');
11363:         } else {
11364:             $course_server = $env{'user.home'}; 
11365:         }
11366:     }
11367:     my %host_servers =
11368:         &get_servers($udom,'library');
11369:     unless ($host_servers{$course_server}) {
11370:         return 'error: invalid home server for course: '.$course_server;
11371:     }
11372: # ------------------------------------------------------------- Make the course
11373:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11374:                       $course_server);
11375:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11376:     my $uhome=&homeserver($uname,$udom,'true');
11377:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11378: 	return 'error: no such course';
11379:     }
11380: # ----------------------------------------------------------------- Course made
11381: # log existence
11382:     my $now = time;
11383:     my $newcourse = {
11384:                     $udom.'_'.$uname => {
11385:                                      description => $description,
11386:                                      inst_code   => $inst_code,
11387:                                      owner       => $course_owner,
11388:                                      type        => $crstype,
11389:                                      creator     => $env{'user.name'}.':'.
11390:                                                     $env{'user.domain'},
11391:                                      created     => $now,
11392:                                      context     => $context,
11393:                                                 },
11394:                     };
11395:     &courseidput($udom,$newcourse,$uhome,'notime');
11396: # set toplevel url
11397:     my $topurl=$url;
11398:     unless ($nonstandard) {
11399: # ------------------------------------------ For standard courses, make top url
11400:         my $mapurl=&clutter($url);
11401:         if ($mapurl eq '/res/') { $mapurl=''; }
11402:         $env{'form.initmap'}=(<<ENDINITMAP);
11403: <map>
11404: <resource id="1" type="start"></resource>
11405: <resource id="2" src="$mapurl"></resource>
11406: <resource id="3" type="finish"></resource>
11407: <link index="1" from="1" to="2"></link>
11408: <link index="2" from="2" to="3"></link>
11409: </map>
11410: ENDINITMAP
11411:         $topurl=&declutter(
11412:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11413:                           );
11414:     }
11415: # ----------------------------------------------------------- Write preferences
11416:     &writecoursepref($udom.'_'.$uname,
11417:                      ('description'              => $description,
11418:                       'url'                      => $topurl,
11419:                       'internal.creator'         => $env{'user.name'}.':'.
11420:                                                     $env{'user.domain'},
11421:                       'internal.created'         => $now,
11422:                       'internal.creationcontext' => $context)
11423:                     );
11424:     return '/'.$udom.'/'.$uname;
11425: }
11426: 
11427: # ------------------------------------------------------------------- Create ID
11428: sub generate_coursenum {
11429:     my ($udom,$crstype) = @_;
11430:     my $domdesc = &domain($udom);
11431:     return 'error: invalid domain' if ($domdesc eq '');
11432:     my $first;
11433:     if ($crstype eq 'Community') {
11434:         $first = '0';
11435:     } else {
11436:         $first = int(1+rand(9)); 
11437:     } 
11438:     my $uname=$first.
11439:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11440:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11441:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11442: # ----------------------------------------------- Make sure that does not exist
11443:     my $uhome=&homeserver($uname,$udom,'true');
11444:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11445:         if ($crstype eq 'Community') {
11446:             $first = '0';
11447:         } else {
11448:             $first = int(1+rand(9));
11449:         }
11450:         $uname=$first.
11451:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11452:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11453:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11454:         $uhome=&homeserver($uname,$udom,'true');
11455:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11456:             return 'error: unable to generate unique course-ID';
11457:         }
11458:     }
11459:     return $uname;
11460: }
11461: 
11462: sub is_course {
11463:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11464:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11465: 
11466:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11467:     my $uhome=&homeserver($cnum,$cdom);
11468:     my $iscourse;
11469:     if (grep { $_ eq $uhome } current_machine_ids()) {
11470:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11471:     } else {
11472:         my $hashid = $cdom.':'.$cnum;
11473:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11474:         unless (defined($cached)) {
11475:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11476:                                         $cnum,undef,undef,'.');
11477:             $iscourse = 0;
11478:             if (exists($courses{$cdom.'_'.$cnum})) {
11479:                 $iscourse = 1;
11480:             }
11481:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11482:         }
11483:     }
11484:     return unless ($iscourse);
11485:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11486: }
11487: 
11488: sub store_userdata {
11489:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11490:     my $result;
11491:     if ($datakey ne '') {
11492:         if (ref($storehash) eq 'HASH') {
11493:             if ($udom eq '' || $uname eq '') {
11494:                 $udom = $env{'user.domain'};
11495:                 $uname = $env{'user.name'};
11496:             }
11497:             my $uhome=&homeserver($uname,$udom);
11498:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11499:                 $result = 'error: no_host';
11500:             } else {
11501:                 $storehash->{'ip'} = &get_requestor_ip();
11502:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11503: 
11504:                 my $namevalue='';
11505:                 foreach my $key (keys(%{$storehash})) {
11506:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11507:                 }
11508:                 $namevalue=~s/\&$//;
11509:                 unless ($namespace eq 'courserequests') {
11510:                     $datakey = &escape($datakey);
11511:                 }
11512:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11513:                                   $namevalue,$uhome);
11514:             }
11515:         } else {
11516:             $result = 'error: data to store was not a hash reference'; 
11517:         }
11518:     } else {
11519:         $result= 'error: invalid requestkey'; 
11520:     }
11521:     return $result;
11522: }
11523: 
11524: # ---------------------------------------------------------- Assign Custom Role
11525: 
11526: sub assigncustomrole {
11527:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11528:         $selfenroll,$context,$othdomby,$requester)=@_;
11529:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11530:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11531:                        $requester);
11532: }
11533: 
11534: # ----------------------------------------------------------------- Revoke Role
11535: 
11536: sub revokerole {
11537:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11538:     my $now=time;
11539:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11540: }
11541: 
11542: # ---------------------------------------------------------- Revoke Custom Role
11543: 
11544: sub revokecustomrole {
11545:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11546:     my $now=time;
11547:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11548:            $deleteflag,$selfenroll,$context);
11549: }
11550: 
11551: # ------------------------------------------------------------ Disk usage
11552: sub diskusage {
11553:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11554:     $directorypath =~ s/\/$//;
11555:     my $listing=&reply('du2:'.&escape($directorypath).':'
11556:                        .&escape($getpropath).':'.&escape($uname).':'
11557:                        .&escape($udom),homeserver($uname,$udom));
11558:     if ($listing eq 'unknown_cmd') {
11559:         if ($getpropath) {
11560:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11561:         }
11562:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11563:     }
11564:     return $listing;
11565: }
11566: 
11567: sub is_locked {
11568:     my ($file_name, $domain, $user, $which) = @_;
11569:     my @check;
11570:     my $is_locked;
11571:     push (@check,$file_name);
11572:     my %locked = &get('file_permissions',\@check,
11573: 		      $env{'user.domain'},$env{'user.name'});
11574:     my ($tmp)=keys(%locked);
11575:     if ($tmp=~/^error:/) { undef(%locked); }
11576:     
11577:     if (ref($locked{$file_name}) eq 'ARRAY') {
11578:         $is_locked = 'false';
11579:         foreach my $entry (@{$locked{$file_name}}) {
11580:            if (ref($entry) eq 'ARRAY') {
11581:                $is_locked = 'true';
11582:                if (ref($which) eq 'ARRAY') {
11583:                    push(@{$which},$entry);
11584:                } else {
11585:                    last;
11586:                }
11587:            }
11588:        }
11589:     } else {
11590:         $is_locked = 'false';
11591:     }
11592:     return $is_locked;
11593: }
11594: 
11595: sub declutter_portfile {
11596:     my ($file) = @_;
11597:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11598:     return $file;
11599: }
11600: 
11601: # ------------------------------------------------------------- Mark as Read Only
11602: 
11603: sub mark_as_readonly {
11604:     my ($domain,$user,$files,$what) = @_;
11605:     my %current_permissions = &dump('file_permissions',$domain,$user);
11606:     my ($tmp)=keys(%current_permissions);
11607:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11608:     foreach my $file (@{$files}) {
11609: 	$file = &declutter_portfile($file);
11610:         push(@{$current_permissions{$file}},$what);
11611:     }
11612:     &put('file_permissions',\%current_permissions,$domain,$user);
11613:     return;
11614: }
11615: 
11616: # ------------------------------------------------------------Save Selected Files
11617: 
11618: sub save_selected_files {
11619:     my ($user, $path, @files) = @_;
11620:     my $filename = $user."savedfiles";
11621:     my @other_files = &files_not_in_path($user, $path);
11622:     open (OUT,'>',LONCAPA::tempdir().$filename);
11623:     foreach my $file (@files) {
11624:         print (OUT $env{'form.currentpath'}.$file."\n");
11625:     }
11626:     foreach my $file (@other_files) {
11627:         print (OUT $file."\n");
11628:     }
11629:     close (OUT);
11630:     return 'ok';
11631: }
11632: 
11633: sub clear_selected_files {
11634:     my ($user) = @_;
11635:     my $filename = $user."savedfiles";
11636:     open (OUT,'>',LONCAPA::tempdir().$filename);
11637:     print (OUT undef);
11638:     close (OUT);
11639:     return ("ok");    
11640: }
11641: 
11642: sub files_in_path {
11643:     my ($user, $path) = @_;
11644:     my $filename = $user."savedfiles";
11645:     my %return_files;
11646:     open (IN,'<',LONCAPA::tempdir().$filename);
11647:     while (my $line_in = <IN>) {
11648:         chomp ($line_in);
11649:         my @paths_and_file = split (m!/!, $line_in);
11650:         my $file_part = pop (@paths_and_file);
11651:         my $path_part = join ('/', @paths_and_file);
11652:         $path_part.='/';
11653:         my $path_and_file = $path_part.$file_part;
11654:         if ($path_part eq $path) {
11655:             $return_files{$file_part}= 'selected';
11656:         }
11657:     }
11658:     close (IN);
11659:     return (\%return_files);
11660: }
11661: 
11662: # called in portfolio select mode, to show files selected NOT in current directory
11663: sub files_not_in_path {
11664:     my ($user, $path) = @_;
11665:     my $filename = $user."savedfiles";
11666:     my @return_files;
11667:     my $path_part;
11668:     open(IN, '<',LONCAPA::tempdir().$filename);
11669:     while (my $line = <IN>) {
11670:         #ok, I know it's clunky, but I want it to work
11671:         my @paths_and_file = split(m|/|, $line);
11672:         my $file_part = pop(@paths_and_file);
11673:         chomp($file_part);
11674:         my $path_part = join('/', @paths_and_file);
11675:         $path_part .= '/';
11676:         my $path_and_file = $path_part.$file_part;
11677:         if ($path_part ne $path) {
11678:             push(@return_files, ($path_and_file));
11679:         }
11680:     }
11681:     close(OUT);
11682:     return (@return_files);
11683: }
11684: 
11685: #------------------------------Submitted/Handedback Portfolio Files Versioning
11686:  
11687: sub portfiles_versioning {
11688:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11689:     my $portfolio_root = '/userfiles/portfolio';
11690:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11691:     foreach my $file (@{$portfiles}) {
11692:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11693:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11694:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11695:         my $getpropath = 1;
11696:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11697:                                              $stu_name,$getpropath);
11698:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11699:         my $new_answer = 
11700:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11701:         if ($new_answer ne 'problem getting file') {
11702:             push(@{$versioned_portfiles}, $directory.$new_answer);
11703:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11704:                               [$symb,$env{'request.course.id'},'graded']);
11705:         }
11706:     }
11707: }
11708: 
11709: sub get_next_version {
11710:     my ($answer_name, $answer_ext, $dir_list) = @_;
11711:     my $version;
11712:     if (ref($dir_list) eq 'ARRAY') {
11713:         foreach my $row (@{$dir_list}) {
11714:             my ($file) = split(/\&/,$row,2);
11715:             my ($file_name,$file_version,$file_ext) =
11716:                 &file_name_version_ext($file);
11717:             if (($file_name eq $answer_name) &&
11718:                 ($file_ext eq $answer_ext)) {
11719:                      # gets here if filename and extension match,
11720:                      # regardless of version
11721:                 if ($file_version ne '') {
11722:                     # a versioned file is found  so save it for later
11723:                     if ($file_version > $version) {
11724:                         $version = $file_version;
11725:                     }
11726:                 }
11727:             }
11728:         }
11729:     }
11730:     $version ++;
11731:     return($version);
11732: }
11733: 
11734: sub version_selected_portfile {
11735:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11736:     my ($answer_name,$answer_ver,$answer_ext) =
11737:         &file_name_version_ext($file_name);
11738:     my $new_answer;
11739:     $env{'form.copy'} =
11740:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11741:     if($env{'form.copy'} eq '-1') {
11742:         $new_answer = 'problem getting file';
11743:     } else {
11744:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11745:         my $copy_result = 
11746:             &finishuserfileupload($stu_name,$domain,'copy',
11747:                                   '/portfolio'.$directory.$new_answer);
11748:     }
11749:     undef($env{'form.copy'});
11750:     return ($new_answer);
11751: }
11752: 
11753: sub file_name_version_ext {
11754:     my ($file)=@_;
11755:     my @file_parts = split(/\./, $file);
11756:     my ($name,$version,$ext);
11757:     if (@file_parts > 1) {
11758:         $ext=pop(@file_parts);
11759:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11760:             $version=pop(@file_parts);
11761:         }
11762:         $name=join('.',@file_parts);
11763:     } else {
11764:         $name=join('.',@file_parts);
11765:     }
11766:     return($name,$version,$ext);
11767: }
11768: 
11769: #----------------------------------------------Get portfolio file permissions
11770: 
11771: sub get_portfile_permissions {
11772:     my ($domain,$user) = @_;
11773:     my %current_permissions = &dump('file_permissions',$domain,$user);
11774:     my ($tmp)=keys(%current_permissions);
11775:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11776:     return \%current_permissions;
11777: }
11778: 
11779: #---------------------------------------------Get portfolio file access controls
11780: 
11781: sub get_access_controls {
11782:     my ($current_permissions,$group,$file) = @_;
11783:     my %access;
11784:     my $real_file = $file;
11785:     $file =~ s/\.meta$//;
11786:     if (defined($file)) {
11787:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11788:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11789:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11790:             }
11791:         }
11792:     } else {
11793:         foreach my $key (keys(%{$current_permissions})) {
11794:             if ($key =~ /\0accesscontrol$/) {
11795:                 if (defined($group)) {
11796:                     if ($key !~ m-^\Q$group\E/-) {
11797:                         next;
11798:                     }
11799:                 }
11800:                 my ($fullpath) = split(/\0/,$key);
11801:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11802:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11803:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11804:                     }
11805:                 }
11806:             }
11807:         }
11808:     }
11809:     return %access;
11810: }
11811: 
11812: sub modify_access_controls {
11813:     my ($file_name,$changes,$domain,$user)=@_;
11814:     my ($outcome,$deloutcome);
11815:     my %store_permissions;
11816:     my %new_values;
11817:     my %new_control;
11818:     my %translation;
11819:     my @deletions = ();
11820:     my $now = time;
11821:     if (exists($$changes{'activate'})) {
11822:         if (ref($$changes{'activate'}) eq 'HASH') {
11823:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11824:             my $numnew = scalar(@newitems);
11825:             for (my $i=0; $i<$numnew; $i++) {
11826:                 my $newkey = $newitems[$i];
11827:                 my $newid = &Apache::loncommon::get_cgi_id();
11828:                 if ($newkey =~ /^\d+:/) { 
11829:                     $newkey =~ s/^(\d+)/$newid/;
11830:                     $translation{$1} = $newid;
11831:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11832:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11833:                     $translation{$1} = $newid;
11834:                 }
11835:                 $new_values{$file_name."\0".$newkey} = 
11836:                                           $$changes{'activate'}{$newitems[$i]};
11837:                 $new_control{$newkey} = $now;
11838:             }
11839:         }
11840:     }
11841:     my %todelete;
11842:     my %changed_items;
11843:     foreach my $action ('delete','update') {
11844:         if (exists($$changes{$action})) {
11845:             if (ref($$changes{$action}) eq 'HASH') {
11846:                 foreach my $key (keys(%{$$changes{$action}})) {
11847:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11848:                     if ($action eq 'delete') { 
11849:                         $todelete{$itemnum} = 1;
11850:                     } else {
11851:                         $changed_items{$itemnum} = $key;
11852:                     }
11853:                 }
11854:             }
11855:         }
11856:     }
11857:     # get lock on access controls for file.
11858:     my $lockhash = {
11859:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11860:                                                        ':'.$env{'user.domain'},
11861:                    }; 
11862:     my $tries = 0;
11863:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11864:    
11865:     while (($gotlock ne 'ok') && $tries < 10) {
11866:         $tries ++;
11867:         sleep(0.1);
11868:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11869:     }
11870:     if ($gotlock eq 'ok') {
11871:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11872:         my ($tmp)=keys(%curr_permissions);
11873:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11874:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11875:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11876:             if (ref($curr_controls) eq 'HASH') {
11877:                 foreach my $control_item (keys(%{$curr_controls})) {
11878:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11879:                     if (defined($todelete{$itemnum})) {
11880:                         push(@deletions,$file_name."\0".$control_item);
11881:                     } else {
11882:                         if (defined($changed_items{$itemnum})) {
11883:                             $new_control{$changed_items{$itemnum}} = $now;
11884:                             push(@deletions,$file_name."\0".$control_item);
11885:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11886:                         } else {
11887:                             $new_control{$control_item} = $$curr_controls{$control_item};
11888:                         }
11889:                     }
11890:                 }
11891:             }
11892:         }
11893:         my ($group);
11894:         if (&is_course($domain,$user)) {
11895:             ($group,my $file) = split(/\//,$file_name,2);
11896:         }
11897:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11898:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11899:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11900:         #  remove lock
11901:         my @del_lock = ($file_name."\0".'locked_access_records');
11902:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11903:         my $sqlresult =
11904:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11905:                                     $group);
11906:     } else {
11907:         $outcome = "error: could not obtain lockfile\n";  
11908:     }
11909:     return ($outcome,$deloutcome,\%new_values,\%translation);
11910: }
11911: 
11912: sub make_public_indefinitely {
11913:     my (@requrl) = @_;
11914:     return &automated_portfile_access('public',\@requrl);
11915: }
11916: 
11917: sub automated_portfile_access {
11918:     my ($accesstype,$addsref,$delsref,$info) = @_;
11919:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11920:         return 'invalid';
11921:     }
11922:     my %urls;
11923:     if (ref($addsref) eq 'ARRAY') {
11924:         foreach my $requrl (@{$addsref}) {
11925:             if (&is_portfolio_url($requrl)) {
11926:                 unless (exists($urls{$requrl})) {
11927:                     $urls{$requrl} = 'add';
11928:                 }
11929:             }
11930:         }
11931:     }
11932:     if (ref($delsref) eq 'ARRAY') {
11933:         foreach my $requrl (@{$delsref}) { 
11934:             if (&is_portfolio_url($requrl)) {
11935:                 unless (exists($urls{$requrl})) {
11936:                     $urls{$requrl} = 'delete'; 
11937:                 }
11938:             }
11939:         }
11940:     }
11941:     unless (keys(%urls)) {
11942:         return 'invalid';
11943:     }
11944:     my $ip;
11945:     if ($accesstype eq 'ip') {
11946:         if (ref($info) eq 'HASH') {
11947:             if ($info->{'ip'} ne '') {
11948:                 $ip = $info->{'ip'};
11949:             }
11950:         }
11951:         if ($ip eq '') {
11952:             return 'invalid';
11953:         }
11954:     }
11955:     my $errors;
11956:     my $now = time;
11957:     my %current_perms;
11958:     foreach my $requrl (sort(keys(%urls))) {
11959:         my $action;
11960:         if ($urls{$requrl} eq 'add') {
11961:             $action = 'activate';
11962:         } else {
11963:             $action = 'none';
11964:         }
11965:         my $aclnum = 0;
11966:         my (undef,$udom,$unum,$file_name,$group) =
11967:             &parse_portfolio_url($requrl);
11968:         unless (exists($current_perms{$unum.':'.$udom})) {
11969:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11970:         }
11971:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11972:                                                    $group,$file_name);
11973:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11974:             my ($num,$scope,$end,$start) = 
11975:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11976:             if ($scope eq $accesstype) {
11977:                 if (($start <= $now) && ($end == 0)) {
11978:                     if ($accesstype eq 'ip') {
11979:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11980:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11981:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11982:                                     if ($urls{$requrl} eq 'add') {
11983:                                         $action = 'none';
11984:                                         last;
11985:                                     } else {
11986:                                         $action = 'delete';
11987:                                         $aclnum = $num;
11988:                                         last;
11989:                                     }
11990:                                 }
11991:                             }
11992:                         }
11993:                     } elsif ($accesstype eq 'public') {
11994:                         if ($urls{$requrl} eq 'add') {
11995:                             $action = 'none';
11996:                             last;
11997:                         } else {
11998:                             $action = 'delete';
11999:                             $aclnum = $num;
12000:                             last;
12001:                         }
12002:                     }
12003:                 } elsif ($accesstype eq 'public') {
12004:                     $action = 'update';
12005:                     $aclnum = $num;
12006:                     last;
12007:                 }
12008:             }
12009:         }
12010:         if ($action eq 'none') {
12011:             next;
12012:         } else {
12013:             my %changes;
12014:             my $newend = 0;
12015:             my $newstart = $now;
12016:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
12017:             $changes{$action}{$newkey} = {
12018:                 type => $accesstype,
12019:                 time => {
12020:                     start => $newstart,
12021:                     end   => $newend,
12022:                 },
12023:             };
12024:             if ($accesstype eq 'ip') {
12025:                 $changes{$action}{$newkey}{'ip'} = [$ip];
12026:             }
12027:             my ($outcome,$deloutcome,$new_values,$translation) =
12028:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
12029:             unless ($outcome eq 'ok') {
12030:                 $errors .= $outcome.' ';
12031:             }
12032:         }
12033:     }
12034:     if ($errors) {
12035:         $errors =~ s/\s$//;
12036:         return $errors;
12037:     } else {
12038:         return 'ok';
12039:     }
12040: }
12041: 
12042: #------------------------------------------------------Get Marked as Read Only
12043: 
12044: sub get_marked_as_readonly {
12045:     my ($domain,$user,$what,$group) = @_;
12046:     my $current_permissions = &get_portfile_permissions($domain,$user);
12047:     my @readonly_files;
12048:     my $cmp1=$what;
12049:     if (ref($what)) { $cmp1=join('',@{$what}) };
12050:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12051:         if (defined($group)) {
12052:             if ($file_name !~ m-^\Q$group\E/-) {
12053:                 next;
12054:             }
12055:         }
12056:         if (ref($value) eq "ARRAY"){
12057:             foreach my $stored_what (@{$value}) {
12058:                 my $cmp2=$stored_what;
12059:                 if (ref($stored_what) eq 'ARRAY') {
12060:                     $cmp2=join('',@{$stored_what});
12061:                 }
12062:                 if ($cmp1 eq $cmp2) {
12063:                     push(@readonly_files, $file_name);
12064:                     last;
12065:                 } elsif (!defined($what)) {
12066:                     push(@readonly_files, $file_name);
12067:                     last;
12068:                 }
12069:             }
12070:         }
12071:     }
12072:     return @readonly_files;
12073: }
12074: #-----------------------------------------------------------Get Marked as Read Only Hash
12075: 
12076: sub get_marked_as_readonly_hash {
12077:     my ($current_permissions,$group,$what) = @_;
12078:     my %readonly_files;
12079:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12080:         if (defined($group)) {
12081:             if ($file_name !~ m-^\Q$group\E/-) {
12082:                 next;
12083:             }
12084:         }
12085:         if (ref($value) eq "ARRAY"){
12086:             foreach my $stored_what (@{$value}) {
12087:                 if (ref($stored_what) eq 'ARRAY') {
12088:                     foreach my $lock_descriptor(@{$stored_what}) {
12089:                         if ($lock_descriptor eq 'graded') {
12090:                             $readonly_files{$file_name} = 'graded';
12091:                         } elsif ($lock_descriptor eq 'handback') {
12092:                             $readonly_files{$file_name} = 'handback';
12093:                         } else {
12094:                             if (!exists($readonly_files{$file_name})) {
12095:                                 $readonly_files{$file_name} = 'locked';
12096:                             }
12097:                         }
12098:                     }
12099:                 } 
12100:             }
12101:         } 
12102:     }
12103:     return %readonly_files;
12104: }
12105: # ------------------------------------------------------------ Unmark as Read Only
12106: 
12107: sub unmark_as_readonly {
12108:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12109:     # for portfolio submissions, $what contains [$symb,$crsid] 
12110:     my ($domain,$user,$what,$file_name,$group) = @_;
12111:     $file_name = &declutter_portfile($file_name);
12112:     my $symb_crs = $what;
12113:     if (ref($what)) { $symb_crs=join('',@$what); }
12114:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12115:     my ($tmp)=keys(%current_permissions);
12116:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12117:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12118:     foreach my $file (@readonly_files) {
12119: 	my $clean_file = &declutter_portfile($file);
12120: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12121: 	my $current_locks = $current_permissions{$file};
12122:         my @new_locks;
12123:         my @del_keys;
12124:         if (ref($current_locks) eq "ARRAY"){
12125:             foreach my $locker (@{$current_locks}) {
12126:                 my $compare=$locker;
12127:                 if (ref($locker) eq 'ARRAY') {
12128:                     $compare=join('',@{$locker});
12129:                     if ($compare ne $symb_crs) {
12130:                         push(@new_locks, $locker);
12131:                     }
12132:                 }
12133:             }
12134:             if (scalar(@new_locks) > 0) {
12135:                 $current_permissions{$file} = \@new_locks;
12136:             } else {
12137:                 push(@del_keys, $file);
12138:                 &del('file_permissions',\@del_keys, $domain, $user);
12139:                 delete($current_permissions{$file});
12140:             }
12141:         }
12142:     }
12143:     &put('file_permissions',\%current_permissions,$domain,$user);
12144:     return;
12145: }
12146: 
12147: # ------------------------------------------------------------ Directory lister
12148: 
12149: sub dirlist {
12150:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12151:     $uri=~s/^\///;
12152:     $uri=~s/\/$//;
12153:     my ($udom, $uname);
12154:     if ($getuserdir) {
12155:         $udom = $userdomain;
12156:         $uname = $username;
12157:     } else {
12158:         (undef,$udom,$uname)=split(/\//,$uri);
12159:         if(defined($userdomain)) {
12160:             $udom = $userdomain;
12161:         }
12162:         if(defined($username)) {
12163:             $uname = $username;
12164:         }
12165:     }
12166:     my ($dirRoot,$listing,@listing_results);
12167: 
12168:     $dirRoot = $perlvar{'lonDocRoot'};
12169:     if (defined($getpropath)) {
12170:         $dirRoot = &propath($udom,$uname);
12171:         $dirRoot =~ s/\/$//;
12172:     } elsif (defined($getuserdir)) {
12173:         my $subdir=$uname.'__';
12174:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12175:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12176:                    ."/$udom/$subdir/$uname";
12177:     } elsif (defined($alternateRoot)) {
12178:         $dirRoot = $alternateRoot;
12179:     }
12180: 
12181:     if($udom) {
12182:         if($uname) {
12183:             my $uhome = &homeserver($uname,$udom);
12184:             if ($uhome eq 'no_host') {
12185:                 return ([],'no_host');
12186:             }
12187:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12188:                               .$getuserdir.':'.&escape($dirRoot)
12189:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12190:             if ($listing eq 'unknown_cmd') {
12191:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12192:             } else {
12193:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12194:             }
12195:             if ($listing eq 'unknown_cmd') {
12196:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12197:                 @listing_results = split(/:/,$listing);
12198:             } else {
12199:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12200:             }
12201:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12202:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12203:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12204:                 return ([],$listing);
12205:             } else {
12206:                 return (\@listing_results);
12207:             }
12208:         } elsif(!$alternateRoot) {
12209:             my (%allusers,%listerror);
12210: 	    my %servers = &get_servers($udom,'library');
12211:  	    foreach my $tryserver (keys(%servers)) {
12212:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12213:                                   &escape($udom),$tryserver);
12214:                 if ($listing eq 'unknown_cmd') {
12215: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12216: 				      $udom, $tryserver);
12217:                 } else {
12218:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12219:                 }
12220: 		if ($listing eq 'unknown_cmd') {
12221: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12222: 				      $udom, $tryserver);
12223: 		    @listing_results = split(/:/,$listing);
12224: 		} else {
12225: 		    @listing_results =
12226: 			map { &unescape($_); } split(/:/,$listing);
12227: 		}
12228:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12229:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12230:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12231:                     $listerror{$tryserver} = $listing;
12232:                 } else {
12233: 		    foreach my $line (@listing_results) {
12234: 			my ($entry) = split(/&/,$line,2);
12235: 			$allusers{$entry} = 1;
12236: 		    }
12237: 		}
12238:             }
12239:             my @alluserslist=();
12240:             foreach my $user (sort(keys(%allusers))) {
12241:                 push(@alluserslist,$user.'&user');
12242:             }
12243: 
12244:             if (!%listerror) {
12245:                 # no errors
12246:                 return (\@alluserslist);
12247:             } elsif (scalar(keys(%servers)) == 1) {
12248:                 # one library server, one error 
12249:                 my ($key) = keys(%listerror);
12250:                 return (\@alluserslist, $listerror{$key});
12251:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12252:                 # con_lost indicates that we might miss data from at least one
12253:                 # library server
12254:                 return (\@alluserslist, 'con_lost');
12255:             } else {
12256:                 # multiple library servers and no con_lost -> data should be
12257:                 # complete. 
12258:                 return (\@alluserslist);
12259:             }
12260: 
12261:         } else {
12262:             return ([],'missing username');
12263:         }
12264:     } elsif(!defined($getpropath)) {
12265:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12266:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12267:         return (\@all_domains);
12268:     } else {
12269:         return ([],'missing domain');
12270:     }
12271: }
12272: 
12273: # --------------------------------------------- GetFileTimestamp
12274: # This function utilizes dirlist and returns the date stamp for
12275: # when it was last modified.  It will also return an error of -1
12276: # if an error occurs
12277: 
12278: sub GetFileTimestamp {
12279:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12280:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12281:     $studentName   = &LONCAPA::clean_username($studentName);
12282:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12283:                                     undef,$getuserdir);
12284:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12285:         return -1;
12286:     }
12287:     if (ref($fileref) eq 'ARRAY') {
12288:         my @stats = split('&',$fileref->[0]);
12289:         # @stats contains first the filename, then the stat output
12290:         return $stats[10]; # so this is 10 instead of 9.
12291:     } else {
12292:         return -1;
12293:     }
12294: }
12295: 
12296: sub stat_file {
12297:     my ($uri) = @_;
12298:     $uri = &clutter_with_no_wrapper($uri);
12299: 
12300:     my ($udom,$uname,$file);
12301:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12302: 	($udom,$uname,$file) =
12303: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12304: 	$file = 'userfiles/'.$file;
12305:     }
12306:     if ($uri =~ m-^/res/-) {
12307: 	($udom,$uname) = 
12308: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12309: 	$file = $uri;
12310:     }
12311: 
12312:     if (!$udom || !$uname || !$file) {
12313: 	# unable to handle the uri
12314: 	return ();
12315:     }
12316:     my $getpropath;
12317:     if ($file =~ /^userfiles\//) {
12318:         $getpropath = 1;
12319:     }
12320:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12321:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12322:         return ();
12323:     } else {
12324:         if (ref($listref) eq 'ARRAY') {
12325:             my @stats = split('&',$listref->[0]);
12326: 	    shift(@stats); #filename is first
12327: 	    return @stats;
12328:         }
12329:     }
12330:     return ();
12331: }
12332: 
12333: # --------------------------------------------------------- recursedirs
12334: # Recursive function to traverse either a specific user's Authoring Space
12335: # or corresponding Published Resource Space, and populate the hash ref:
12336: # $dirhashref with URLs of all directories, and if $filehashref hash
12337: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12338: # or .rights files in resource space, and .meta, .save, .log, .bak and
12339: # .rights files in Authoring Space.
12340: #
12341: # Inputs:
12342: #
12343: # $is_home - true if current server is home server for user's space
12344: # $recurse - if true will also traverse subdirectories recursively
12345: # $include - reference to hash containing allowed file extensions.  If provided,
12346: #             files which do not have a matching extension will be ignored.
12347: # $exclude - reference to hash containing excluded file extensions.  If provided,
12348: #             files which have a matching extension will be ignored.
12349: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12350: #             directory with first file found (with acceptable extension).
12351: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12352: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12353: # $relpath - Current path (relative to top level).
12354: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12355: # $filehashref - reference to hash to populate with URLs of files (Optional)
12356: #
12357: # Returns: nothing
12358: #
12359: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12360: #
12361: # Currently used by interface/londocs.pm to create linked select boxes for
12362: # directory and filename to import a Course "Author" resource into a course, and
12363: # also to create linked select boxes for Authoring Space and Directory to choose
12364: # save location for creation of a new "standard" problem from the Course Editor.
12365: #
12366: 
12367: sub recursedirs {
12368:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12369:     return unless (ref($dirhashref) eq 'HASH');
12370:     my $docroot = $perlvar{'lonDocRoot'};
12371:     my $currpath = $docroot.$toppath;
12372:     if ($relpath ne '') {
12373:         $currpath .= "/$relpath";
12374:     }
12375:     my ($savefile,$checkinc,$checkexc);
12376:     if (ref($filehashref)) {
12377:         $savefile = 1;
12378:     }
12379:     if (ref($include) eq 'HASH') {
12380:         $checkinc = 1;
12381:     }
12382:     if (ref($exclude) eq 'HASH') {
12383:         $checkexc = 1;
12384:     }
12385:     if ($is_home) {
12386:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12387:             my $filecount = 0;
12388:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12389:                 next if ($item eq '');
12390:                 if (-d "$currpath/$item") {
12391:                     my $newpath;
12392:                     if ($relpath ne '') {
12393:                         $newpath = "$relpath/$item";
12394:                     } else {
12395:                         $newpath = $item;
12396:                     }
12397:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12398:                     if ($recurse) {
12399:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12400:                     }
12401:                 } elsif (($savefile) || ($relpath eq '')) {
12402:                     next if ($nonemptydir && $filecount);
12403:                     if ($checkinc || $checkexc) {
12404:                         my ($extension) = ($item =~ /\.(\w+)$/);
12405:                         if ($checkinc) {
12406:                             next unless ($extension && $include->{$extension});
12407:                         }
12408:                         if ($checkexc) {
12409:                             next if ($extension && $exclude->{$extension});
12410:                         }
12411:                     }
12412:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12413:                         $dirhashref->{'/'} = 1;
12414:                     }
12415:                     if ($savefile) {
12416:                         if ($relpath eq '') {
12417:                             $filehashref->{'/'}{$item} = 1;
12418:                         } else {
12419:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12420:                         }
12421:                     }
12422:                     $filecount ++;
12423:                 }
12424:             }
12425:             closedir($dirh);
12426:         }
12427:     } else {
12428:         my ($dirlistref,$listerror) =
12429:             &dirlist($toppath.$relpath);
12430:         my @dir_lines;
12431:         my $dirptr=16384;
12432:         if (ref($dirlistref) eq 'ARRAY') {
12433:             my $filecount = 0;
12434:             foreach my $dir_line (sort
12435:                               {
12436:                                   my ($afile)=split('&',$a,2);
12437:                                   my ($bfile)=split('&',$b,2);
12438:                                   return (lc($afile) cmp lc($bfile));
12439:                               } (@{$dirlistref})) {
12440:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12441:                     split(/\&/,$dir_line,16);
12442:                 $item =~ s/\s+$//;
12443:                 next if (($item =~ /^\.\.?$/) || ($obs));
12444:                 if ($dirptr&$testdir) {
12445:                     my $newpath;
12446:                     if ($relpath) {
12447:                         $newpath = "$relpath/$item";
12448:                     } else {
12449:                         $newpath = $item;
12450:                     }
12451:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12452:                     if ($recurse) {
12453:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12454:                     }
12455:                 } elsif (($savefile) || ($relpath eq '')) {
12456:                     next if ($nonemptydir && $filecount);
12457:                     if ($checkinc || $checkexc) {
12458:                         my $extension;
12459:                         if ($checkinc) {
12460:                             next unless ($extension && $include->{$extension});
12461:                         }
12462:                         if ($checkexc) {
12463:                             next if ($extension && $exclude->{$extension});
12464:                         }
12465:                     }
12466:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12467:                         $dirhashref->{'/'} = 1;
12468:                     }
12469:                     if ($savefile) {
12470:                         if ($relpath eq '') {
12471:                             $filehashref->{'/'}{$item} = 1;
12472:                         } else {
12473:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12474:                         }
12475:                     }
12476:                     $filecount ++; 
12477:                 }
12478:             }
12479:         }
12480:     }
12481:     if ($addtopdir) {
12482:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12483:             $dirhashref->{'/'} = 1;
12484:         }
12485:     }
12486:     return;
12487: }
12488: 
12489: sub priv_exclude {
12490:     return {
12491:              meta => 1,
12492:              save => 1,
12493:              log => 1,
12494:              bak => 1,
12495:              rights => 1,
12496:              DS_Store => 1,
12497:            };
12498: }
12499: 
12500: # -------------------------------------------------------- Value of a Condition
12501: 
12502: # gets the value of a specific preevaluated condition
12503: #    stored in the string  $env{user.state.<cid>}
12504: # or looks up a condition reference in the bighash and if if hasn't
12505: # already been evaluated recurses into docondval to get the value of
12506: # the condition, then memoizing it to 
12507: #   $env{user.state.<cid>.<condition>}
12508: sub directcondval {
12509:     my $number=shift;
12510:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12511: 	&Apache::lonuserstate::evalstate();
12512:     }
12513:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12514: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12515:     } elsif ($number =~ /^_/) {
12516: 	my $sub_condition;
12517: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12518: 		&GDBM_READER(),0640)) {
12519: 	    $sub_condition=$bighash{'conditions'.$number};
12520: 	    untie(%bighash);
12521: 	}
12522: 	my $value = &docondval($sub_condition);
12523: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12524: 	return $value;
12525:     }
12526:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12527:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12528:     } else {
12529:        return 2;
12530:     }
12531: }
12532: 
12533: # get the collection of conditions for this resource
12534: sub condval {
12535:     my $condidx=shift;
12536:     my $allpathcond='';
12537:     foreach my $cond (split(/\|/,$condidx)) {
12538: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12539: 	    $allpathcond.=
12540: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12541: 	}
12542:     }
12543:     $allpathcond=~s/\|$//;
12544:     return &docondval($allpathcond);
12545: }
12546: 
12547: #evaluates an expression of conditions
12548: sub docondval {
12549:     my ($allpathcond) = @_;
12550:     my $result=0;
12551:     if ($env{'request.course.id'}
12552: 	&& defined($allpathcond)) {
12553: 	my $operand='|';
12554: 	my @stack;
12555: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12556: 	    if ($chunk eq '(') {
12557: 		push @stack,($operand,$result);
12558: 	    } elsif ($chunk eq ')') {
12559: 		my $before=pop @stack;
12560: 		if (pop @stack eq '&') {
12561: 		    $result=$result>$before?$before:$result;
12562: 		} else {
12563: 		    $result=$result>$before?$result:$before;
12564: 		}
12565: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12566: 		$operand=$chunk;
12567: 	    } else {
12568: 		my $new=directcondval($chunk);
12569: 		if ($operand eq '&') {
12570: 		    $result=$result>$new?$new:$result;
12571: 		} else {
12572: 		    $result=$result>$new?$result:$new;
12573: 		}
12574: 	    }
12575: 	}
12576:     }
12577:     return $result;
12578: }
12579: 
12580: # ---------------------------------------------------- Devalidate courseresdata
12581: 
12582: sub devalidatecourseresdata {
12583:     my ($coursenum,$coursedomain)=@_;
12584:     my $hashid=$coursenum.':'.$coursedomain;
12585:     &devalidate_cache_new('courseres',$hashid);
12586: }
12587: 
12588: 
12589: # --------------------------------------------------- Course Resourcedata Query
12590: #
12591: #  Parameters:
12592: #      $coursenum    - Number of the course.
12593: #      $coursedomain - Domain at which the course was created.
12594: #  Returns:
12595: #     A hash of the course parameters along (I think) with timestamps
12596: #     and version info.
12597: 
12598: sub get_courseresdata {
12599:     my ($coursenum,$coursedomain)=@_;
12600:     my $coursehom=&homeserver($coursenum,$coursedomain);
12601:     my $hashid=$coursenum.':'.$coursedomain;
12602:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12603:     my %dumpreply;
12604:     unless (defined($cached)) {
12605: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12606: 	$result=\%dumpreply;
12607: 	my ($tmp) = keys(%dumpreply);
12608: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12609: 	    &do_cache_new('courseres',$hashid,$result,600);
12610: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12611: 	    return $tmp;
12612: 	} elsif ($tmp =~ /^(error)/) {
12613: 	    $result=undef;
12614: 	    &do_cache_new('courseres',$hashid,$result,600);
12615: 	}
12616:     }
12617:     return $result;
12618: }
12619: 
12620: sub devalidateuserresdata {
12621:     my ($uname,$udom)=@_;
12622:     my $hashid="$udom:$uname";
12623:     &devalidate_cache_new('userres',$hashid);
12624: }
12625: 
12626: sub get_userresdata {
12627:     my ($uname,$udom)=@_;
12628:     #most student don\'t have any data set, check if there is some data
12629:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12630: 
12631:     my $hashid="$udom:$uname";
12632:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12633:     if (!defined($cached)) {
12634: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12635: 	$result=\%resourcedata;
12636: 	&do_cache_new('userres',$hashid,$result,600);
12637:     }
12638:     my ($tmp)=keys(%$result);
12639:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12640: 	return $result;
12641:     }
12642:     #error 2 occurs when the .db doesn't exist
12643:     if ($tmp!~/error: 2 /) {
12644:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12645: 	    &logthis("<font color=\"blue\">WARNING:".
12646: 		     " Trying to get resource data for ".
12647: 		     $uname." at ".$udom.": ".
12648: 		     $tmp."</font>");
12649:         }
12650:     } elsif ($tmp=~/error: 2 /) {
12651: 	#&EXT_cache_set($udom,$uname);
12652: 	&do_cache_new('userres',$hashid,undef,600);
12653: 	undef($tmp); # not really an error so don't send it back
12654:     }
12655:     return $tmp;
12656: }
12657: #----------------------------------------------- resdata - return resource data
12658: #  Purpose:
12659: #    Return resource data for either users or for a course.
12660: #  Parameters:
12661: #     $name      - Course/user name.
12662: #     $domain    - Name of the domain the user/course is registered on.
12663: #     $type      - Type of thing $name is (must be 'course' or 'user')
12664: #     $mapp      - decluttered URL of enclosing map  
12665: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12666: #     $recurseup - Ref to array of map URLs, starting with map containing
12667: #                  $mapp up through hierarchy of nested maps to top level map.  
12668: #     $courseid  - CourseID (first part of param identifier).
12669: #     $modifier  - Middle part of param identifier.
12670: #     $what      - Last part of param identifier.
12671: #     @which     - Array of names of resources desired.
12672: #  Returns:
12673: #     The value of the first reasource in @which that is found in the
12674: #     resource hash.
12675: #  Exceptional Conditions:
12676: #     If the $type passed in is not valid (not the string 'course' or 
12677: #     'user', an undefined  reference is returned.
12678: #     If none of the resources are found, an undef is returned
12679: sub resdata {
12680:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12681:         $modifier,$what,@which)=@_;
12682:     my $result;
12683:     if ($type eq 'course') {
12684: 	$result=&get_courseresdata($name,$domain);
12685:     } elsif ($type eq 'user') {
12686: 	$result=&get_userresdata($name,$domain);
12687:     }
12688:     if (!ref($result)) { return $result; }    
12689:     foreach my $item (@which) {
12690:         if ($item->[1] eq 'course') {
12691:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12692:                 unless ($$recursed) {
12693:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12694:                     $$recursed = 1;
12695:                 }
12696:                 foreach my $item (@${recurseup}) {
12697:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12698:                     last if (defined($result->{$norecursechk}));
12699:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12700:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12701:                 }
12702:             }
12703:         }
12704:         if (defined($result->{$item->[0]})) {
12705: 	    return [$result->{$item->[0]},$item->[1]];
12706: 	}
12707:     }
12708:     return undef;
12709: }
12710: 
12711: sub get_domain_lti {
12712:     my ($cdom,$context) = @_;
12713:     my ($name,$cachename,%lti);
12714:     if ($context eq 'consumer') {
12715:         $name = 'ltitools';
12716:     } elsif ($context eq 'provider') {
12717:         $name = 'lti';
12718:     } elsif ($context eq 'linkprot') {
12719:         $name = 'ltisec';
12720:     } else {
12721:         return %lti;
12722:     }
12723:     if ($context eq 'linkprot') {
12724:         $cachename = $context;
12725:     } else {
12726:         $cachename = $name;
12727:     }
12728:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12729:     if (defined($cached)) {
12730:         if (ref($result) eq 'HASH') {
12731:             %lti = %{$result};
12732:         }
12733:     } else {
12734:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12735:         if (ref($domconfig{$name}) eq 'HASH') {
12736:             if ($context eq 'linkprot') {
12737:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12738:                     %lti = %{$domconfig{$name}{'linkprot'}};
12739:                 }
12740:             } else {
12741:                 %lti = %{$domconfig{$name}};
12742:             }
12743:         }
12744:         my $cachetime = 24*60*60;
12745:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12746:     }
12747:     return %lti;
12748: }
12749: 
12750: sub get_course_lti {
12751:     my ($cnum,$cdom,$context) = @_;
12752:     my ($name,$cachename,%lti);
12753:     if ($context eq 'consumer') {
12754:         $name = 'ltitools';
12755:         $cachename = 'courseltitools';
12756:     } elsif ($context eq 'provider') {
12757:         $name = 'lti';
12758:         $cachename = 'courselti';
12759:     } else {
12760:         return %lti;
12761:     }
12762:     my $hashid=$cdom.'_'.$cnum;
12763:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12764:     if (defined($cached)) {
12765:         if (ref($result) eq 'HASH') {
12766:             %lti = %{$result};
12767:         }
12768:     } else {
12769:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12770:         my $cachetime = 24*60*60;
12771:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12772:     }
12773:     return %lti;
12774: }
12775: 
12776: sub courselti_itemid {
12777:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12778:     my ($chome,$itemid);
12779:     $chome = &homeserver($cnum,$cdom);
12780:     return if ($chome eq 'no_host');
12781:     if (ref($params) eq 'HASH') {
12782:         my $rep;
12783:         if (grep { $_ eq $chome } current_machine_ids()) {
12784:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12785:         } else {
12786:             my $escurl = &escape($url);
12787:             my $escmethod = &escape($method);
12788:             my $items = &freeze_escape($params);
12789:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12790:         }
12791:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12792:                 ($rep eq 'unknown_cmd')) {
12793:             $itemid = $rep;
12794:         }
12795:     }
12796:     return $itemid;
12797: }
12798: 
12799: sub domainlti_itemid {
12800:     my ($cdom,$url,$method,$params,$context) = @_;
12801:     my ($primary_id,$itemid);
12802:     $primary_id = &domain($cdom,'primary');
12803:     return if ($primary_id eq '');
12804:     if (ref($params) eq 'HASH') {
12805:         my $rep;
12806:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12807:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12808:         } else {
12809:             my $cnum = '';
12810:             my $escurl = &escape($url);
12811:             my $escmethod = &escape($method);
12812:             my $items = &freeze_escape($params);
12813:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12814:         }
12815:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12816:                 ($rep eq 'unknown_cmd')) {
12817:             $itemid = $rep;
12818:         }
12819:     }
12820:     return $itemid;
12821: }
12822: 
12823: sub get_ltitools_id {
12824:     my ($context,$cdom,$cnum,$title) = @_;
12825:     my ($lockhash,$tries,$gotlock,$id,$error);
12826: 
12827:     # get lock on ltitools db
12828:     $lockhash = {
12829:                    lock => $env{'user.name'}.
12830:                            ':'.$env{'user.domain'},
12831:                 };
12832:     $tries = 0;
12833:     if ($context eq 'domain') {
12834:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12835:     } else {
12836:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12837:     }
12838:     while (($gotlock ne 'ok') && ($tries<10)) {
12839:         $tries ++;
12840:         sleep (0.1);
12841:         if ($context eq 'domain') {
12842:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12843:         } else {
12844:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12845:         }
12846:     }
12847:     if ($gotlock eq 'ok') {
12848:         my %currids;
12849:         if ($context eq 'domain') {
12850:             %currids = &dump_dom('ltitools',$cdom);
12851:         } else {
12852:             %currids = &dump('ltitools',$cdom,$cnum);
12853:         }
12854:         if ($currids{'lock'}) {
12855:             delete($currids{'lock'});
12856:             if (keys(%currids)) {
12857:                 my @curr = sort { $a <=> $b } keys(%currids);
12858:                 if ($curr[-1] =~ /^\d+$/) {
12859:                     $id = 1 + $curr[-1];
12860:                 }
12861:             } else {
12862:                 $id = 1;
12863:             }
12864:             if ($id) {
12865:                 if ($context eq 'domain') {
12866:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12867:                         $error = 'nostore';
12868:                     }
12869:                 } else {
12870:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12871:                         $error = 'nostore';
12872:                     }
12873:                 }
12874:             } else {
12875:                 $error = 'nonumber';
12876:             }
12877:         }
12878:         my $dellockoutcome;
12879:         if ($context eq 'domain') {
12880:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12881:         } else {
12882:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12883:         }
12884:     } else {
12885:         $error = 'nolock';
12886:     }
12887:     return ($id,$error);
12888: }
12889: 
12890: sub count_supptools {
12891:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
12892:     my $hashid=$cnum.':'.$cdom;
12893:     my ($numexttools,$cached);
12894:     unless ($ignorecache) {
12895:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12896:     }
12897:     unless (defined($cached)) {
12898:         my $chome=&homeserver($cnum,$cdom);
12899:         $numexttools = 0;
12900:         unless ($chome eq 'no_host') {
12901:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12902:             if (ref($supplemental) eq 'HASH') {
12903:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12904:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12905:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12906:                             $numexttools ++;
12907:                         }
12908:                     }
12909:                 }
12910:             }
12911:         }
12912:         &do_cache_new('supptools',$hashid,$numexttools,600);
12913:     }
12914:     return $numexttools;
12915: }
12916: 
12917: sub has_unhidden_suppfiles {
12918:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12919:     my $hashid=$cnum.':'.$cdom;
12920:     my ($showsupp,$cached);
12921:     unless ($ignorecache) {
12922:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
12923:     }
12924:     unless (defined($cached)) {
12925:         my $chome=&homeserver($cnum,$cdom);
12926:         unless ($chome eq 'no_host') {
12927:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
12928:             if (ref($supplemental) eq 'HASH') {
12929:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12930:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12931:                         next if ($key =~ /\.sequence$/);
12932:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12933:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12934:                                 unless ($supplemental->{'hidden'}->{$id}) {
12935:                                     $showsupp = 1;
12936:                                     last;
12937:                                 }
12938:                             }
12939:                         }
12940:                         last if ($showsupp);
12941:                     }
12942:                 }
12943:             }
12944:         }
12945:         &do_cache_new('showsupp',$hashid,$showsupp,600);
12946:     }
12947:     return $showsupp;
12948: }
12949: 
12950: #
12951: # EXT resource caching routines
12952: #
12953: 
12954: {
12955: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12956: #
12957: # The course for which we cache
12958: my $cachedmapkey='';
12959: # The cached recursive maps for this course
12960: my %cachedmaps=();
12961: # When this was last done
12962: my $cachedmaptime='';
12963: 
12964: sub clear_EXT_cache_status {
12965:     &delenv('cache.EXT.');
12966: }
12967: 
12968: sub EXT_cache_status {
12969:     my ($target_domain,$target_user) = @_;
12970:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12971:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12972:         # We know already the user has no data
12973:         return 1;
12974:     } else {
12975:         return 0;
12976:     }
12977: }
12978: 
12979: sub EXT_cache_set {
12980:     my ($target_domain,$target_user) = @_;
12981:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12982:     #&appenv({$cachename => time});
12983: }
12984: 
12985: # --------------------------------------------------------- Value of a Variable
12986: sub EXT {
12987: 
12988:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12989:     unless ($varname) { return ''; }
12990:     #get real user name/domain, courseid and symb
12991:     my $courseid;
12992:     my $publicuser;
12993:     if ($symbparm) {
12994: 	$symbparm=&get_symb_from_alias($symbparm);
12995:     }
12996:     if (!($uname && $udom)) {
12997:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12998:       if (!$symbparm) {	$symbparm=$cursymb; }
12999:     } else {
13000: 	$courseid=$env{'request.course.id'};
13001:     }
13002:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13003:     my $rest;
13004:     if (defined($therest[0])) {
13005:        $rest=join('.',@therest);
13006:     } else {
13007:        $rest='';
13008:     }
13009: 
13010:     my $qualifierrest=$qualifier;
13011:     if ($rest) { $qualifierrest.='.'.$rest; }
13012:     my $spacequalifierrest=$space;
13013:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
13014:     if ($realm eq 'user') {
13015: # --------------------------------------------------------------- user.resource
13016: 	if ($space eq 'resource') {
13017: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
13018: 		  || defined($Apache::lonhomework::parsing_a_task))
13019: 		 &&
13020: 		 ($symbparm eq &symbread()) ) {
13021: 		# if we are in the middle of processing the resource the
13022: 		# get the value we are planning on committing
13023:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
13024:                     return $Apache::lonhomework::results{$qualifierrest};
13025:                 } else {
13026:                     return $Apache::lonhomework::history{$qualifierrest};
13027:                 }
13028: 	    } else {
13029: 		my %restored;
13030: 		if ($publicuser || $env{'request.state'} eq 'construct') {
13031: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13032: 		} else {
13033: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13034: 		}
13035: 		return $restored{$qualifierrest};
13036: 	    }
13037: # ----------------------------------------------------------------- user.access
13038:         } elsif ($space eq 'access') {
13039: 	    # FIXME - not supporting calls for a specific user
13040:             return &allowed($qualifier,$rest);
13041: # ------------------------------------------ user.preferences, user.environment
13042:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13043: 	    if (($uname eq $env{'user.name'}) &&
13044: 		($udom eq $env{'user.domain'})) {
13045: 		return $env{join('.',('environment',$qualifierrest))};
13046: 	    } else {
13047: 		my %returnhash;
13048: 		if (!$publicuser) {
13049: 		    %returnhash=&userenvironment($udom,$uname,
13050: 						 $qualifierrest);
13051: 		}
13052: 		return $returnhash{$qualifierrest};
13053: 	    }
13054: # ----------------------------------------------------------------- user.course
13055:         } elsif ($space eq 'course') {
13056: 	    # FIXME - not supporting calls for a specific user
13057:             return $env{join('.',('request.course',$qualifier))};
13058: # ------------------------------------------------------------------- user.role
13059:         } elsif ($space eq 'role') {
13060: 	    # FIXME - not supporting calls for a specific user
13061:             my ($role,$where)=split(/\./,$env{'request.role'});
13062:             if ($qualifier eq 'value') {
13063: 		return $role;
13064:             } elsif ($qualifier eq 'extent') {
13065:                 return $where;
13066:             }
13067: # ----------------------------------------------------------------- user.domain
13068:         } elsif ($space eq 'domain') {
13069:             return $udom;
13070: # ------------------------------------------------------------------- user.name
13071:         } elsif ($space eq 'name') {
13072:             return $uname;
13073: # ---------------------------------------------------- Any other user namespace
13074:         } else {
13075: 	    my %reply;
13076: 	    if (!$publicuser) {
13077: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13078: 	    }
13079: 	    return $reply{$qualifierrest};
13080:         }
13081:     } elsif ($realm eq 'query') {
13082: # ---------------------------------------------- pull stuff out of query string
13083:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13084: 						[$spacequalifierrest]);
13085: 	return $env{'form.'.$spacequalifierrest}; 
13086:    } elsif ($realm eq 'request') {
13087: # ------------------------------------------------------------- request.browser
13088:         if ($space eq 'browser') {
13089:             return $env{'browser.'.$qualifier};
13090: # ------------------------------------------------------------ request.filename
13091:         } else {
13092:             return $env{'request.'.$spacequalifierrest};
13093:         }
13094:     } elsif ($realm eq 'course') {
13095: # ---------------------------------------------------------- course.description
13096:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13097:     } elsif ($realm eq 'resource') {
13098: 
13099: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13100: 	    if (!$symbparm) { $symbparm=&symbread(); }
13101: 	}
13102: 
13103:         if ($qualifier eq '') {
13104: 	    if ($space eq 'title') {
13105: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13106: 	        return &gettitle($symbparm);
13107: 	    }
13108: 	
13109: 	    if ($space eq 'map') {
13110: 	        my ($map) = &decode_symb($symbparm);
13111: 	        return &symbread($map);
13112: 	    }
13113:             if ($space eq 'maptitle') {
13114:                 my ($map) = &decode_symb($symbparm);
13115:                 return &gettitle($map);
13116:             }
13117: 	    if ($space eq 'filename') {
13118: 	        if ($symbparm) {
13119: 		    return &clutter((&decode_symb($symbparm))[2]);
13120: 	        }
13121: 	        return &hreflocation('',$env{'request.filename'});
13122: 	    }
13123: 
13124:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13125:                 if ($space eq 'visibleparts') {
13126:                     my $navmap = Apache::lonnavmaps::navmap->new();
13127:                     my $item;
13128:                     if (ref($navmap)) {
13129:                         my $res = $navmap->getBySymb($symbparm);
13130:                         my $parts = $res->parts();
13131:                         if (ref($parts) eq 'ARRAY') {
13132:                             $item = join(',',@{$parts});
13133:                         }
13134:                         undef($navmap);
13135:                     }
13136:                     return $item;
13137:                 }
13138:             }
13139:         }
13140: 
13141: 	my ($section, $group, @groups, @recurseup, $recursed);
13142:         if (ref($recurseupref) eq 'ARRAY') {
13143:             @recurseup = @{$recurseupref};
13144:             $recursed = 1;
13145:         }
13146: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13147:         if (($courseid eq '') && ($cid)) {
13148:             $courseid = $cid;
13149:         }
13150: 	if (($symbparm && $courseid) && 
13151: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13152: 
13153: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13154: 
13155: # ----------------------------------------------------- Cascading lookup scheme
13156: 	    my $symbp=$symbparm;
13157: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13158: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13159:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13160: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13161: 	    if (($env{'user.name'} eq $uname) &&
13162: 		($env{'user.domain'} eq $udom)) {
13163: 		$section=$env{'request.course.sec'};
13164:                 @groups = split(/:/,$env{'request.course.groups'});  
13165:                 @groups=&sort_course_groups($courseid,@groups); 
13166: 	    } else {
13167: 		if (! defined($usection)) {
13168: 		    $section=&getsection($udom,$uname,$courseid);
13169: 		} else {
13170: 		    $section = $usection;
13171: 		}
13172:                 @groups = &get_users_groups($udom,$uname,$courseid);
13173: 	    }
13174: 
13175: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13176: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13177:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13178: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13179: 
13180: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13181: 	    my $courselevelr=$courseid.'.'.$symbparm;
13182:             $courseleveli=$courseid.'.'.$recurseparm;
13183: 	    $courselevelm=$courseid.'.'.$mapparm;
13184: 
13185: # ----------------------------------------------------------- first, check user
13186: 
13187: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13188:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13189: 				       ([$courselevelr,'resource'],
13190: 					[$courselevelm,'map'     ],
13191:                                         [$courseleveli,'map'     ],
13192: 					[$courselevel, 'course'  ]));
13193: 	    if (defined($userreply)) { return &get_reply($userreply); }
13194: 
13195: # ------------------------------------------------ second, check some of course
13196:             my $coursereply;
13197:             if (@groups > 0) {
13198:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13199:                                        $recurseparm,$mapparm,$spacequalifierrest,
13200:                                        $mapp,\$recursed,\@recurseup);
13201:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13202:             }
13203: 
13204: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13205: 				  $env{'course.'.$courseid.'.domain'},
13206: 				  'course',$mapp,\$recursed,\@recurseup,
13207:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13208: 				  ([$seclevelr,   'resource'],
13209: 				   [$seclevelm,   'map'     ],
13210:                                    [$secleveli,   'map'     ],
13211: 				   [$seclevel,    'course'  ],
13212: 				   [$courselevelr,'resource']));
13213: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13214: 
13215: # ------------------------------------------------------ third, check map parms
13216: 	    my %parmhash=();
13217: 	    my $thisparm='';
13218: 	    if (tie(%parmhash,'GDBM_File',
13219: 		    $env{'request.course.fn'}.'_parms.db',
13220: 		    &GDBM_READER(),0640)) {
13221: 		$thisparm=$parmhash{$symbparm};
13222: 		untie(%parmhash);
13223: 	    }
13224: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13225: 	}
13226: # ------------------------------------------ fourth, look in resource metadata
13227:  
13228:         my $what = $spacequalifierrest;
13229: 	$what=~s/\./\_/;
13230: 	my $filename;
13231: 	if (!$symbparm) { $symbparm=&symbread(); }
13232: 	if ($symbparm) {
13233: 	    $filename=(&decode_symb($symbparm))[2];
13234: 	} else {
13235: 	    $filename=$env{'request.filename'};
13236: 	}
13237:         my $toolsymb;
13238:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13239:             $toolsymb = $symbparm;
13240:         }
13241: 	my $metadata=&metadata($filename,$what,$toolsymb);
13242: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13243: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13244: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13245: 
13246: # ----------------------------------------------- fifth, look in rest of course
13247: 	if ($symbparm && defined($courseid) && 
13248: 	    $courseid eq $env{'request.course.id'}) {
13249: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13250: 				     $env{'course.'.$courseid.'.domain'},
13251: 				     'course',$mapp,\$recursed,\@recurseup,
13252:                                      $courseid,'.',$spacequalifierrest,
13253: 				     ([$courselevelm,'map'   ],
13254:                                       [$courseleveli,'map'   ],
13255: 				      [$courselevel, 'course']));
13256: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13257: 	}
13258: # ------------------------------------------------------------------ Cascade up
13259: 	unless ($space eq '0') {
13260: 	    my @parts=split(/_/,$space);
13261: 	    my $id=pop(@parts);
13262: 	    my $part=join('_',@parts);
13263: 	    if ($part eq '') { $part='0'; }
13264: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13265: 				 $symbparm,$udom,$uname,$section,1);
13266: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13267: 	}
13268: 	if ($recurse) { return undef; }
13269: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13270: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13271: # ---------------------------------------------------- Any other user namespace
13272:     } elsif ($realm eq 'environment') {
13273: # ----------------------------------------------------------------- environment
13274: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13275: 	    return $env{'environment.'.$spacequalifierrest};
13276: 	} else {
13277: 	    if ($uname eq 'anonymous' && $udom eq '') {
13278: 		return '';
13279: 	    }
13280: 	    my %returnhash=&userenvironment($udom,$uname,
13281: 					    $spacequalifierrest);
13282: 	    return $returnhash{$spacequalifierrest};
13283: 	}
13284:     } elsif ($realm eq 'system') {
13285: # ----------------------------------------------------------------- system.time
13286: 	if ($space eq 'time') {
13287: 	    return time;
13288:         }
13289:     } elsif ($realm eq 'server') {
13290: # ----------------------------------------------------------------- system.time
13291: 	if ($space eq 'name') {
13292: 	    return $ENV{'SERVER_NAME'};
13293:         }
13294:     } elsif ($realm eq 'client') {
13295:         if ($space eq 'remote_addr') {
13296:             return &get_requestor_ip();
13297:         }
13298:     }
13299:     return '';
13300: }
13301: 
13302: sub get_reply {
13303:     my ($reply_value) = @_;
13304:     if (ref($reply_value) eq 'ARRAY') {
13305:         if (wantarray) {
13306: 	    return @$reply_value;
13307:         }
13308:         return $reply_value->[0];
13309:     } else {
13310:         return $reply_value;
13311:     }
13312: }
13313: 
13314: sub check_group_parms {
13315:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13316:         $recursed,$recurseupref) = @_;
13317:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13318:                   [$what,'course']);
13319:     my $coursereply;
13320:     foreach my $group (@{$groups}) {
13321:         my @groupitems = ();
13322:         foreach my $level (@levels) {
13323:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13324:              push(@groupitems,[$item,$level->[1]]);
13325:         }
13326:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13327:                                    $env{'course.'.$courseid.'.domain'},
13328:                                    'course',$mapp,$recursed,$recurseupref,
13329:                                    $courseid,'.['.$group.'].',$what,
13330:                                    @groupitems);
13331:         last if (defined($coursereply));
13332:     }
13333:     return $coursereply;
13334: }
13335: 
13336: sub get_map_hierarchy {
13337:     my ($mapname,$courseid) = @_;
13338:     my @recurseup = ();
13339:     if ($mapname) {
13340:         if (($cachedmapkey eq $courseid) &&
13341:             (abs($cachedmaptime-time)<5)) {
13342:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13343:                 return @{$cachedmaps{$mapname}};
13344:             }
13345:         }
13346:         my $navmap = Apache::lonnavmaps::navmap->new();
13347:         if (ref($navmap)) {
13348:             @recurseup = $navmap->recurseup_maps($mapname);
13349:             undef($navmap);
13350:             $cachedmaps{$mapname} = \@recurseup;
13351:             $cachedmaptime=time;
13352:             $cachedmapkey=$courseid;
13353:         }
13354:     }
13355:     return @recurseup;
13356: }
13357: 
13358: }
13359: 
13360: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13361:     my ($courseid,@groups) = @_;
13362:     @groups = sort(@groups);
13363:     return @groups;
13364: }
13365: 
13366: sub packages_tab_default {
13367:     my ($uri,$varname,$toolsymb)=@_;
13368:     my (undef,$part,$name)=split(/\./,$varname);
13369: 
13370:     my (@extension,@specifics,$do_default);
13371:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13372: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13373: 	if ($pack_type eq 'default') {
13374: 	    $do_default=1;
13375: 	} elsif ($pack_type eq 'extension') {
13376: 	    push(@extension,[$package,$pack_type,$pack_part]);
13377: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13378: 	    # only look at packages defaults for packages that this id is
13379: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13380: 	}
13381:     }
13382:     # first look for a package that matches the requested part id
13383:     foreach my $package (@specifics) {
13384: 	my (undef,$pack_type,$pack_part)=@{$package};
13385: 	next if ($pack_part ne $part);
13386: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13387: 	    return $packagetab{"$pack_type&$name&default"};
13388: 	}
13389:     }
13390:     # look for any possible matching non extension_ package
13391:     foreach my $package (@specifics) {
13392: 	my (undef,$pack_type,$pack_part)=@{$package};
13393: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13394: 	    return $packagetab{"$pack_type&$name&default"};
13395: 	}
13396: 	if ($pack_type eq 'part') { $pack_part='0'; }
13397: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13398: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13399: 	}
13400:     }
13401:     # look for any posible extension_ match
13402:     foreach my $package (@extension) {
13403: 	my ($package,$pack_type)=@{$package};
13404: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13405: 	    return $packagetab{"$pack_type&$name&default"};
13406: 	}
13407: 	if (defined($packagetab{$package."&$name&default"})) {
13408: 	    return $packagetab{$package."&$name&default"};
13409: 	}
13410:     }
13411:     # look for a global default setting
13412:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13413: 	return $packagetab{"default&$name&default"};
13414:     }
13415:     return undef;
13416: }
13417: 
13418: sub add_prefix_and_part {
13419:     my ($prefix,$part)=@_;
13420:     my $keyroot;
13421:     if (defined($prefix) && $prefix !~ /^__/) {
13422: 	# prefix that has a part already
13423: 	$keyroot=$prefix;
13424:     } elsif (defined($prefix)) {
13425: 	# prefix that is missing a part
13426: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13427:     } else {
13428: 	# no prefix at all
13429: 	if (defined($part)) { $keyroot='_'.$part; }
13430:     }
13431:     return $keyroot;
13432: }
13433: 
13434: # ---------------------------------------------------------------- Get metadata
13435: 
13436: my %metaentry;
13437: my %importedpartids;
13438: my %importedrespids;
13439: sub metadata {
13440:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13441:     $uri=&declutter($uri);
13442:     # if it is a non metadata possible uri return quickly
13443:     if (($uri eq '') || 
13444: 	(($uri =~ m|^/*adm/|) && 
13445: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13446:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13447: 	return undef;
13448:     }
13449:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13450: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13451: 	return undef;
13452:     }
13453:     my $filename=$uri;
13454:     $uri=~s/\.meta$//;
13455: #
13456: # Is the metadata already cached?
13457: # Look at timestamp of caching
13458: # Everything is cached by the main uri, libraries are never directly cached
13459: #
13460:     if (!defined($liburi)) {
13461: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13462: 	if (defined($cached)) { return $result->{':'.$what}; }
13463:     }
13464: 
13465: #
13466: # If the uri is for an external tool the file from
13467: # which metadata should be retrieved depends on whether
13468: # the tool had been configured to be gradable (set in the Course
13469: # Editor or Resource Editor).
13470: #
13471: # If a valid symb has been included as the third arg in the call
13472: # to &metadata() that can be used to retrieve the value of
13473: # parameter_0_gradable set for the resource, and included in the
13474: # uploaded map containing the tool. The value is retrieved via
13475: # &EXT(), if a valid symb is available.  Otherwise the value of
13476: # gradable in the exttool_$marker.db file for the tool instance
13477: # is retrieved via &get().
13478: #
13479: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13480: # hiddenresource and encrypturl (during course initialization)
13481: # the map-level parameter for resource.0.gradable included in the 
13482: # uploaded map containing the tool will not yet have been stored
13483: # in the user_course_parms.db file for the user's session, so in 
13484: # this case fall back to retrieving gradable status from the
13485: # exttool_$marker.db file.
13486: #
13487: # In order to avoid an infinite loop, &metadata() will return
13488: # before a call to &EXT(), if the uri is for an external tool
13489: # and the $what for which metadata is being requested is
13490: # parameter_0_gradable or 0_gradable.
13491: #
13492: 
13493:     if ($uri =~ /ext\.tool$/) {
13494:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13495:             return;
13496:         } else {
13497:             my ($checked,$use_passback);
13498:             if ($toolsymb ne '') {
13499:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13500:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13501:                     $checked = 1;
13502:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13503:                         $use_passback = 1;
13504:                     }
13505:                 }
13506:             }
13507:             unless ($checked) {
13508:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13509:                 $marker=~s/\D//g;
13510:                 if ($marker) {
13511:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13512:                     $use_passback = $toolsettings{'gradable'};
13513:                 }
13514:             }
13515:             if ($use_passback) {
13516:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13517:             } else {
13518:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13519:             }
13520:         }
13521:     }
13522: 
13523:     {
13524: # Imported parts would go here
13525:         my @origfiletagids=();
13526:         my $importedparts=0;
13527: 
13528: # Imported responseids would go here
13529:         my $importedresponses=0;
13530: #
13531: # Is this a recursive call for a library?
13532: #
13533: #	if (! exists($metacache{$uri})) {
13534: #	    $metacache{$uri}={};
13535: #	}
13536: 	my $cachetime = 60*60;
13537:         if ($liburi) {
13538: 	    $liburi=&declutter($liburi);
13539:             $filename=$liburi;
13540:         } else {
13541: 	    &devalidate_cache_new('meta',$uri);
13542: 	    undef(%metaentry);
13543: 	}
13544:         my %metathesekeys=();
13545:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13546: 	my $metastring;
13547: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13548: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13549: 	    $metastring = 
13550: 		&Apache::lonnet::ssi_body($which,
13551: 					  ('grade_target' => 'meta'));
13552: 	    $cachetime = 1; # only want this cached in the child not long term
13553: 	} elsif (($uri !~ m -^(editupload)/-) && 
13554:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13555: 	    my $file=&filelocation('',&clutter($filename));
13556: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13557: 	    $metastring=&getfile($file);
13558: 	}
13559:         my $parser=HTML::LCParser->new(\$metastring);
13560:         my $token;
13561:         undef %metathesekeys;
13562:         while ($token=$parser->get_token) {
13563: 	    if ($token->[0] eq 'S') {
13564: 		if (defined($token->[2]->{'package'})) {
13565: #
13566: # This is a package - get package info
13567: #
13568: 		    my $package=$token->[2]->{'package'};
13569: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13570: 		    if (defined($token->[2]->{'id'})) { 
13571: 			$keyroot.='_'.$token->[2]->{'id'}; 
13572: 		    }
13573: 		    if ($metaentry{':packages'}) {
13574: 			$metaentry{':packages'}.=','.$package.$keyroot;
13575: 		    } else {
13576: 			$metaentry{':packages'}=$package.$keyroot;
13577: 		    }
13578: 		    foreach my $pack_entry (keys(%packagetab)) {
13579: 			my $part=$keyroot;
13580: 			$part=~s/^\_//;
13581: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13582: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13583: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13584: 			    # ignore package.tab specified default values
13585:                             # here &package_tab_default() will fetch those
13586: 			    if ($subp eq 'default') { next; }
13587: 			    my $value=$packagetab{$pack_entry};
13588: 			    my $unikey;
13589: 			    if ($pack =~ /_0$/) {
13590: 				$unikey='parameter_0_'.$name;
13591: 				$part=0;
13592: 			    } else {
13593: 				$unikey='parameter'.$keyroot.'_'.$name;
13594: 			    }
13595: 			    if ($subp eq 'display') {
13596: 				$value.=' [Part: '.$part.']';
13597: 			    }
13598: 			    $metaentry{':'.$unikey.'.part'}=$part;
13599: 			    $metathesekeys{$unikey}=1;
13600: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13601: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13602: 			    }
13603: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13604: 				$metaentry{':'.$unikey}=
13605: 				    $metaentry{':'.$unikey.'.default'};
13606: 			    }
13607: 			}
13608: 		    }
13609: 		} else {
13610: #
13611: # This is not a package - some other kind of start tag
13612: #
13613: 		    my $entry=$token->[1];
13614: 		    my $unikey='';
13615: 
13616: 		    if ($entry eq 'import') {
13617: #
13618: # Importing a library here
13619: #
13620:                         my $location=$parser->get_text('/import');
13621:                         my $dir=$filename;
13622:                         $dir=~s|[^/]*$||;
13623:                         $location=&filelocation($dir,$location);
13624: 
13625:                         my $importid=$token->[2]->{'id'};
13626:                         my $importmode=$token->[2]->{'importmode'};
13627: #
13628: # Check metadata for imported file to
13629: # see if it contained response items
13630: #
13631:                         my ($origfile,@libfilekeys);
13632:                         my %currmetaentry = %metaentry;
13633:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13634:                                                            $depthcount+1));
13635:                         if (grep(/^responseorder$/,@libfilekeys)) {
13636:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13637:                                                              undef,$depthcount+1);
13638:                             if ($libresponseorder ne '') {
13639:                                 if ($#origfiletagids<0) {
13640:                                     undef(%importedrespids);
13641:                                     undef(%importedpartids);
13642:                                 }
13643:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13644:                                 if (@respids) {
13645:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13646:                                 }
13647:                                 if ($importedrespids{$importid} ne '') {
13648:                                     $importedresponses = 1;
13649: # We need to get the original file and the imported file to get the response order correct
13650: # Load and inspect original file
13651:                                     if ($#origfiletagids<0) {
13652:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13653:                                         $origfile=&getfile($origfilelocation);
13654:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13655:                                     }
13656:                                 }
13657:                             }
13658:                         }
13659: # Do not overwrite contents of %metaentry hash for resource itself with 
13660: # hash populated for imported library file
13661:                         %metaentry = %currmetaentry;
13662:                         undef(%currmetaentry);
13663:                         if ($importmode eq 'part') {
13664: # Import as part(s)
13665:                            $importedparts=1;
13666: # We need to get the original file and the imported file to get the part order correct
13667: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13668: # Load and inspect original file if we didn't do that already
13669:                            if ($#origfiletagids<0) {
13670:                                undef(%importedrespids);
13671:                                undef(%importedpartids);
13672:                                if ($origfile eq '') {
13673:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13674:                                    $origfile=&getfile($origfilelocation);
13675:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13676:                                }
13677:                            }
13678:                            my @impfilepartids;
13679: # If <partorder> tag is included in metadata for the imported file
13680: # get the parts in the imported file from that.
13681:                            if (grep(/^partorder$/,@libfilekeys)) {
13682:                                %currmetaentry = %metaentry;
13683:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13684:                                                             $depthcount+1);
13685:                                %metaentry = %currmetaentry;
13686:                                undef(%currmetaentry);
13687:                                if ($libpartorder ne '') {
13688:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13689:                                }
13690:                            } else {
13691: # If no <partorder> tag available, load and inspect imported file
13692:                                my $impfile=&getfile($location);
13693:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13694:                            }
13695:                            if ($#impfilepartids>=0) {
13696: # This problem had parts
13697:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13698:                            } else {
13699: # Importing by turning a single problem into a problem part
13700: # It gets the import-tags ID as part-ID
13701:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13702:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13703:                            }
13704:                         } else {
13705: # Import as problem or as normal import
13706:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13707:                             unless ($importmode eq 'problem') {
13708: # Normal import
13709:                                 if (defined($token->[2]->{'id'})) {
13710:                                     $unikey.='_'.$token->[2]->{'id'};
13711:                                 }
13712:                             }
13713: # Check metadata for imported file to
13714: # see if it contained parts
13715:                             if (grep(/^partorder$/,@libfilekeys)) {
13716:                                 %currmetaentry = %metaentry;
13717:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13718:                                                              $depthcount+1);
13719:                                 %metaentry = %currmetaentry;
13720:                                 undef(%currmetaentry);
13721:                                 if ($libpartorder ne '') {
13722:                                     $importedparts = 1;
13723:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13724:                                 }
13725:                             }
13726:                         }
13727: 			if ($depthcount<20) {
13728: 			    my $metadata = 
13729: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13730: 					  $depthcount+1);
13731: 			    foreach my $meta (split(',',$metadata)) {
13732: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13733: 				$metathesekeys{$meta}=1;
13734: 			    }
13735:                         }
13736: 		    } else {
13737: #
13738: # Not importing, some other kind of non-package, non-library start tag
13739: # 
13740:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13741:                         if (defined($token->[2]->{'id'})) {
13742:                             $unikey.='_'.$token->[2]->{'id'};
13743:                         }
13744: 			if (defined($token->[2]->{'name'})) { 
13745: 			    $unikey.='_'.$token->[2]->{'name'}; 
13746: 			}
13747: 			$metathesekeys{$unikey}=1;
13748: 			foreach my $param (@{$token->[3]}) {
13749: 			    $metaentry{':'.$unikey.'.'.$param} =
13750: 				$token->[2]->{$param};
13751: 			}
13752: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13753: 			my $default=$metaentry{':'.$unikey.'.default'};
13754: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13755: 		 # only ws inside the tag, and not in default, so use default
13756: 		 # as value
13757: 			    $metaentry{':'.$unikey}=$default;
13758: 			} elsif ( $internaltext =~ /\S/ ) {
13759: 		  # something interesting inside the tag
13760: 			    $metaentry{':'.$unikey}=$internaltext;
13761: 			} else {
13762: 		  # no interesting values, don't set a default
13763: 			}
13764: # end of not-a-package not-a-library import
13765: 		    }
13766: # end of not-a-package start tag
13767: 		}
13768: # the next is the end of "start tag"
13769: 	    }
13770: 	}
13771: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13772: 	$extension = lc($extension);
13773: 	if ($extension eq 'htm') { $extension='html'; }
13774: 
13775: 	foreach my $key (keys(%packagetab)) {
13776: 	    #no specific packages #how's our extension
13777: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13778: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13779: 					 \%metathesekeys);
13780: 	}
13781: 
13782: 	if (!exists($metaentry{':packages'})
13783: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13784: 	    foreach my $key (keys(%packagetab)) {
13785: 		#no specific packages well let's get default then
13786: 		if ($key!~/^default&/) { next; }
13787: 		&metadata_create_package_def($uri,$key,'default',
13788: 					     \%metathesekeys);
13789: 	    }
13790: 	}
13791: # are there custom rights to evaluate
13792: 	if ($metaentry{':copyright'} eq 'custom') {
13793: 
13794:     #
13795:     # Importing a rights file here
13796:     #
13797: 	    unless ($depthcount) {
13798: 		my $location=$metaentry{':customdistributionfile'};
13799: 		my $dir=$filename;
13800: 		$dir=~s|[^/]*$||;
13801: 		$location=&filelocation($dir,$location);
13802: 		my $rights_metadata =
13803: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13804: 			      $depthcount+1);
13805: 		foreach my $rights (split(',',$rights_metadata)) {
13806: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13807: 		    $metathesekeys{$rights}=1;
13808: 		}
13809: 	    }
13810: 	}
13811: 	# uniqifiy package listing
13812: 	my %seen;
13813: 	my @uniq_packages =
13814: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13815: 	$metaentry{':packages'} = join(',',@uniq_packages);
13816: 
13817:         if (($importedresponses) || ($importedparts)) {
13818:             if ($importedparts) {
13819: # We had imported parts and need to rebuild partorder
13820:                 $metaentry{':partorder'}='';
13821:                 $metathesekeys{'partorder'}=1;
13822:             }
13823:             if ($importedresponses) {
13824: # We had imported responses and need to rebuil responseorder
13825:                 $metaentry{':responseorder'}='';
13826:                 $metathesekeys{'responseorder'}=1;
13827:             }
13828:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13829:                 my $origid = $origfiletagids[$index+1];
13830:                 if ($origfiletagids[$index] eq 'part') {
13831: # Original part, part of the problem
13832:                     if ($importedparts) {
13833:                         $metaentry{':partorder'}.=','.$origid;
13834:                     }
13835:                 } elsif ($origfiletagids[$index] eq 'import') {
13836:                     if ($importedparts) {
13837: # We have imported parts at this position
13838:                         if ($importedpartids{$origid} ne '') {
13839:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13840:                         }
13841:                     }
13842:                     if ($importedresponses) {
13843: # We have imported responses at this position
13844:                         if ($importedrespids{$origid} ne '') {
13845:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13846:                         }
13847:                     }
13848:                 } else {
13849: # Original response item, part of the problem
13850:                     if ($importedresponses) {
13851:                         $metaentry{':responseorder'}.=','.$origid;
13852:                     }
13853:                 }
13854:             }
13855:             if ($importedparts) {
13856:                 $metaentry{':partorder'}=~s/^\,//;
13857:             }
13858:             if ($importedresponses) {
13859:                 $metaentry{':responseorder'}=~s/^\,//;
13860:             }
13861:         }
13862: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13863: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13864: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13865:         unless ($liburi) {
13866: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13867:         }
13868: # this is the end of "was not already recently cached
13869:     }
13870:     return $metaentry{':'.$what};
13871: }
13872: 
13873: sub metadata_create_package_def {
13874:     my ($uri,$key,$package,$metathesekeys)=@_;
13875:     my ($pack,$name,$subp)=split(/\&/,$key);
13876:     if ($subp eq 'default') { next; }
13877:     
13878:     if (defined($metaentry{':packages'})) {
13879: 	$metaentry{':packages'}.=','.$package;
13880:     } else {
13881: 	$metaentry{':packages'}=$package;
13882:     }
13883:     my $value=$packagetab{$key};
13884:     my $unikey;
13885:     $unikey='parameter_0_'.$name;
13886:     $metaentry{':'.$unikey.'.part'}=0;
13887:     $$metathesekeys{$unikey}=1;
13888:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13889: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13890:     }
13891:     if (defined($metaentry{':'.$unikey.'.default'})) {
13892: 	$metaentry{':'.$unikey}=
13893: 	    $metaentry{':'.$unikey.'.default'};
13894:     }
13895: }
13896: 
13897: sub metadata_generate_part0 {
13898:     my ($metadata,$metacache,$uri) = @_;
13899:     my %allnames;
13900:     foreach my $metakey (keys(%$metadata)) {
13901: 	if ($metakey=~/^parameter\_(.*)/) {
13902: 	  my $part=$$metacache{':'.$metakey.'.part'};
13903: 	  my $name=$$metacache{':'.$metakey.'.name'};
13904: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13905: 	    $allnames{$name}=$part;
13906: 	  }
13907: 	}
13908:     }
13909:     foreach my $name (keys(%allnames)) {
13910:       $$metadata{"parameter_0_$name"}=1;
13911:       my $key=":parameter_0_$name";
13912:       $$metacache{"$key.part"}='0';
13913:       $$metacache{"$key.name"}=$name;
13914:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13915: 					   $allnames{$name}.'_'.$name.
13916: 					   '.type'};
13917:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13918: 			     '.display'};
13919:       my $expr='[Part: '.$allnames{$name}.']';
13920:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13921:       $$metacache{"$key.display"}=$olddis;
13922:     }
13923: }
13924: 
13925: # ------------------------------------------------------ Devalidate title cache
13926: 
13927: sub devalidate_title_cache {
13928:     my ($url)=@_;
13929:     if (!$env{'request.course.id'}) { return; }
13930:     my $symb=&symbread($url);
13931:     if (!$symb) { return; }
13932:     my $key=$env{'request.course.id'}."\0".$symb;
13933:     &devalidate_cache_new('title',$key);
13934: }
13935: 
13936: # ------------------------------------------------- Get the title of a course
13937: 
13938: sub current_course_title {
13939:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13940: }
13941: # ------------------------------------------------- Get the title of a resource
13942: 
13943: sub gettitle {
13944:     my $urlsymb=shift;
13945:     my $symb=&symbread($urlsymb);
13946:     if ($symb) {
13947: 	my $key=$env{'request.course.id'}."\0".$symb;
13948: 	my ($result,$cached)=&is_cached_new('title',$key);
13949: 	if (defined($cached)) { 
13950: 	    return $result;
13951: 	}
13952: 	my ($map,$resid,$url)=&decode_symb($symb);
13953: 	my $title='';
13954: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13955: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13956: 	} else {
13957: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13958: 		    &GDBM_READER(),0640)) {
13959: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13960: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13961: 		untie(%bighash);
13962: 	    }
13963: 	}
13964: 	$title=~s/\&colon\;/\:/gs;
13965: 	if ($title) {
13966: # Remember both $symb and $title for dynamic metadata
13967:             $accesshash{$symb.'___crstitle'}=$title;
13968:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13969: # Cache this title and then return it
13970: 	    return &do_cache_new('title',$key,$title,600);
13971: 	}
13972: 	$urlsymb=$url;
13973:     }
13974:     my $title=&metadata($urlsymb,'title');
13975:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13976:     return $title;
13977: }
13978: 
13979: sub get_slot {
13980:     my ($which,$cnum,$cdom)=@_;
13981:     if (!$cnum || !$cdom) {
13982: 	(undef,my $courseid)=&whichuser();
13983: 	$cdom=$env{'course.'.$courseid.'.domain'};
13984: 	$cnum=$env{'course.'.$courseid.'.num'};
13985:     }
13986:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13987:     my %slotinfo;
13988:     if (exists($remembered{$key})) {
13989: 	$slotinfo{$which} = $remembered{$key};
13990:     } else {
13991: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13992: 	&Apache::lonhomework::showhash(%slotinfo);
13993: 	my ($tmp)=keys(%slotinfo);
13994: 	if ($tmp=~/^error:/) { return (); }
13995: 	$remembered{$key} = $slotinfo{$which};
13996:     }
13997:     if (ref($slotinfo{$which}) eq 'HASH') {
13998: 	return %{$slotinfo{$which}};
13999:     }
14000:     return $slotinfo{$which};
14001: }
14002: 
14003: sub get_reservable_slots {
14004:     my ($cnum,$cdom,$uname,$udom) = @_;
14005:     my $now = time;
14006:     my $reservable_info;
14007:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14008:     if (exists($remembered{$key})) {
14009:         $reservable_info = $remembered{$key};
14010:     } else {
14011:         my %resv;
14012:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14013:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14014:         $reservable_info = \%resv;
14015:         $remembered{$key} = $reservable_info;
14016:     }
14017:     return $reservable_info;
14018: }
14019: 
14020: sub get_course_slots {
14021:     my ($cnum,$cdom) = @_;
14022:     my $hashid=$cnum.':'.$cdom;
14023:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
14024:     if (defined($cached)) {
14025:         if (ref($result) eq 'HASH') {
14026:             return %{$result};
14027:         }
14028:     } else {
14029:         my %slots=&dump('slots',$cdom,$cnum);
14030:         my ($tmp) = keys(%slots);
14031:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14032:             &do_cache_new('allslots',$hashid,\%slots,600);
14033:             return %slots;
14034:         }
14035:     }
14036:     return;
14037: }
14038: 
14039: sub devalidate_slots_cache {
14040:     my ($cnum,$cdom)=@_;
14041:     my $hashid=$cnum.':'.$cdom;
14042:     &devalidate_cache_new('allslots',$hashid);
14043: }
14044: 
14045: sub get_coursechange {
14046:     my ($cdom,$cnum) = @_;
14047:     if ($cdom eq '' || $cnum eq '') {
14048:         return unless ($env{'request.course.id'});
14049:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14050:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14051:     }
14052:     my $hashid=$cdom.'_'.$cnum;
14053:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14054:     if ((defined($cached)) && ($change ne '')) {
14055:         return $change;
14056:     } else {
14057:         my %crshash;
14058:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14059:         if ($crshash{'internal.contentchange'} eq '') {
14060:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14061:             if ($change eq '') {
14062:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14063:                 $change = $crshash{'internal.created'};
14064:             }
14065:         } else {
14066:             $change = $crshash{'internal.contentchange'};
14067:         }
14068:         my $cachetime = 600;
14069:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14070:     }
14071:     return $change;
14072: }
14073: 
14074: sub devalidate_coursechange_cache {
14075:     my ($cdom,$cnum)=@_;
14076:     my $hashid=$cdom.'_'.$cnum;
14077:     &devalidate_cache_new('crschange',$hashid);
14078: }
14079: 
14080: sub get_suppchange {
14081:     my ($cdom,$cnum) = @_;
14082:     if ($cdom eq '' || $cnum eq '') {
14083:         return unless ($env{'request.course.id'});
14084:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14085:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14086:     }
14087:     my $hashid=$cdom.'_'.$cnum;
14088:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14089:     if ((defined($cached)) && ($change ne '')) {
14090:         return $change;
14091:     } else {
14092:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14093:         if ($crshash{'internal.supplementalchange'} eq '') {
14094:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14095:             if ($change eq '') {
14096:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14097:                 $change = $crshash{'internal.created'};
14098:             }
14099:         } else {
14100:             $change = $crshash{'internal.supplementalchange'};
14101:         }
14102:         my $cachetime = 600;
14103:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14104:     }
14105:     return $change;
14106: }
14107: 
14108: sub devalidate_suppchange_cache {
14109:     my ($cdom,$cnum)=@_;
14110:     my $hashid=$cdom.'_'.$cnum;
14111:     &devalidate_cache_new('suppchange',$hashid);
14112: }
14113: 
14114: sub update_supp_caches {
14115:     my ($cdom,$cnum) = @_;
14116:     my %servers = &internet_dom_servers($cdom);
14117:     my @ids=&current_machine_ids();
14118:     foreach my $server (keys(%servers)) {
14119:         next if (grep(/^\Q$server\E$/,@ids));
14120:         my $hashid=$cnum.':'.$cdom;
14121:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14122:         &remote_devalidate_cache($server,[$cachekey]);
14123:     }
14124:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14125:     &count_supptools($cnum,$cdom,1);
14126:     my $now = time;
14127:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14128:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14129:     }
14130:     &put('environment',{'internal.supplementalchange' => $now},
14131:          $cdom,$cnum);
14132:     &Apache::lonnet::appenv(
14133:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14134:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14135: }
14136: 
14137: # ------------------------------------------------- Update symbolic store links
14138: 
14139: sub symblist {
14140:     my ($mapname,%newhash)=@_;
14141:     $mapname=&deversion(&declutter($mapname));
14142:     my %hash;
14143:     if (($env{'request.course.fn'}) && (%newhash)) {
14144:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14145:                       &GDBM_WRCREAT(),0640)) {
14146: 	    foreach my $url (keys(%newhash)) {
14147: 		next if ($url eq 'last_known'
14148: 			 && $env{'form.no_update_last_known'});
14149: 		$hash{declutter($url)}=&encode_symb($mapname,
14150: 						    $newhash{$url}->[1],
14151: 						    $newhash{$url}->[0]);
14152:             }
14153:             if (untie(%hash)) {
14154: 		return 'ok';
14155:             }
14156:         }
14157:     }
14158:     return 'error';
14159: }
14160: 
14161: # --------------------------------------------------------------- Verify a symb
14162: 
14163: sub symbverify {
14164:     my ($symb,$thisurl,$encstate)=@_;
14165:     my $thisfn=$thisurl;
14166:     $thisfn=&declutter($thisfn);
14167: # direct jump to resource in page or to a sequence - will construct own symbs
14168:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14169: # check URL part
14170:     my ($map,$resid,$url)=&decode_symb($symb);
14171: 
14172:     unless ($url eq $thisfn) { return 0; }
14173: 
14174:     $symb=&symbclean($symb);
14175:     $thisurl=&deversion($thisurl);
14176:     $thisfn=&deversion($thisfn);
14177: 
14178:     my %bighash;
14179:     my $okay=0;
14180: 
14181:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14182:                             &GDBM_READER(),0640)) {
14183:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14184:             $thisurl =~ s/\?.+$//;
14185:             if ($map =~ m{^uploaded/.+\.page$}) {
14186:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14187:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14188:             }
14189:         }
14190:         my $ids;
14191:         if ($map =~ m{^uploaded/.+\.page$}) {
14192:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14193:         } else {
14194:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14195:         }
14196:         unless ($ids) {
14197:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14198:             $ids=$bighash{$idkey};
14199:         }
14200:         if ($ids) {
14201: # ------------------------------------------------------------------- Has ID(s)
14202:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14203:                 $symb =~ s/\?.+$//;
14204:             }
14205: 	    foreach my $id (split(/\,/,$ids)) {
14206: 	       my ($mapid,$resid)=split(/\./,$id);
14207:                if (
14208:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14209:    eq $symb) {
14210:                    if (ref($encstate)) {
14211:                        $$encstate = $bighash{'encrypted_'.$id};
14212:                    }
14213: 		   if (($env{'request.role.adv'}) ||
14214: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14215:                        ($thisurl eq '/adm/navmaps')) {
14216: 		       $okay=1;
14217:                        last;
14218: 		   }
14219: 	       }
14220: 	   }
14221:         }
14222: 	untie(%bighash);
14223:     }
14224:     return $okay;
14225: }
14226: 
14227: # --------------------------------------------------------------- Clean-up symb
14228: 
14229: sub symbclean {
14230:     my $symb=shift;
14231:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14232: # remove version from map
14233:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14234: 
14235: # remove version from URL
14236:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14237: 
14238: # remove wrapper
14239: 
14240:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14241:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14242:     return $symb;
14243: }
14244: 
14245: # ---------------------------------------------- Split symb to find map and url
14246: 
14247: sub encode_symb {
14248:     my ($map,$resid,$url)=@_;
14249:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14250: }
14251: 
14252: sub decode_symb {
14253:     my $symb=shift;
14254:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14255:     my ($map,$resid,$url)=split(/___/,$symb);
14256:     return (&fixversion($map),$resid,&fixversion($url));
14257: }
14258: 
14259: sub fixversion {
14260:     my $fn=shift;
14261:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14262:     my %bighash;
14263:     my $uri=&clutter($fn);
14264:     my $key=$env{'request.course.id'}.'_'.$uri;
14265: # is this cached?
14266:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14267:     if (defined($cached)) { return $result; }
14268: # unfortunately not cached, or expired
14269:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14270: 	    &GDBM_READER(),0640)) {
14271:  	if ($bighash{'version_'.$uri}) {
14272:  	    my $version=$bighash{'version_'.$uri};
14273:  	    unless (($version eq 'mostrecent') || 
14274: 		    ($version==&getversion($uri))) {
14275:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14276:  	    }
14277:  	}
14278:  	untie %bighash;
14279:     }
14280:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14281: }
14282: 
14283: sub deversion {
14284:     my $url=shift;
14285:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14286:     return $url;
14287: }
14288: 
14289: # ------------------------------------------------------ Return symb list entry
14290: 
14291: sub symbread {
14292:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14293:         $ignoresymbdb,$noenccheck)=@_;
14294:     my $cache_str='request.symbread.cached.'.$thisfn;
14295:     if (defined($env{$cache_str})) {
14296:         unless (ref($possibles) eq 'HASH') {
14297:             if ($ignorecachednull) {
14298:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14299:             } else {
14300:                 return $env{$cache_str};
14301:             }
14302:         }
14303:     }
14304: # no filename provided? try from environment
14305:     unless ($thisfn) {
14306:         if ($env{'request.symb'}) {
14307:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14308: 	}
14309: 	$thisfn=$env{'request.filename'};
14310:     }
14311:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14312: # is that filename actually a symb? Verify, clean, and return
14313:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14314: 	if (&symbverify($thisfn,$1)) {
14315: 	    return $env{$cache_str}=&symbclean($thisfn);
14316: 	}
14317:     }
14318:     $thisfn=declutter($thisfn);
14319:     my %hash;
14320:     my %bighash;
14321:     my $syval='';
14322:     if (($env{'request.course.fn'}) && ($thisfn)) {
14323:         unless ($ignoresymbdb) {
14324:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14325:                           &GDBM_READER(),0640)) {
14326: 	        $syval=$hash{$thisfn};
14327:                 untie(%hash);
14328:             }
14329:             if ($syval && $checkforblock) {
14330:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14331:                 if (@blockers) {
14332:                     $syval='';
14333:                 }
14334:             }
14335:         }
14336: # ---------------------------------------------------------- There was an entry
14337:         if ($syval) {
14338: 	    #unless ($syval=~/\_\d+$/) {
14339: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14340: 		    #&appenv({'request.ambiguous' => $thisfn});
14341: 		    #return $env{$cache_str}='';
14342: 		#}    
14343: 		#$syval.=$1;
14344: 	    #}
14345:         } else {
14346: # ------------------------------------------------------- Was not in symb table
14347:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14348:                             &GDBM_READER(),0640)) {
14349: # ---------------------------------------------- Get ID(s) for current resource
14350:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14351:               unless ($ids) { 
14352:                  $ids=$bighash{'ids_/'.$thisfn};
14353:               }
14354:               unless ($ids) {
14355: # alias?
14356: 		  $ids=$bighash{'mapalias_'.$thisfn};
14357:               }
14358:               if ($ids) {
14359: # ------------------------------------------------------------------- Has ID(s)
14360:                  my @possibilities=split(/\,/,$ids);
14361:                  if ($#possibilities==0) {
14362: # ----------------------------------------------- There is only one possibility
14363: 		     my ($mapid,$resid)=split(/\./,$ids);
14364: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14365: 						    $resid,$thisfn);
14366:                      if (ref($possibles) eq 'HASH') {
14367:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14368:                              $possibles->{$syval} = 1;
14369:                          }
14370:                      }
14371:                      if ($checkforblock) {
14372:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14373:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14374:                              if (@blockers) {
14375:                                  $syval = '';
14376:                                  untie(%bighash);
14377:                                  return $env{$cache_str}='';
14378:                              }
14379:                          }
14380:                      }
14381:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14382: # ------------------------------------------ There is more than one possibility
14383:                      my $realpossible=0;
14384:                      foreach my $id (@possibilities) {
14385: 			 my $file=$bighash{'src_'.$id};
14386:                          my $canaccess;
14387:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14388:                              $canaccess = 1;
14389:                          } else { 
14390:                              $canaccess = &allowed('bre',$file);
14391:                          }
14392:                          if ($canaccess) {
14393:          		     my ($mapid,$resid)=split(/\./,$id);
14394:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14395:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14396: 						             $resid,$thisfn);
14397:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14398:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14399:                                  if ($checkforblock) {
14400:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14401:                                      if (@blockers > 0) {
14402:                                          $syval = '';
14403:                                      } else {
14404:                                          $syval = $poss_syval;
14405:                                          $realpossible++;
14406:                                      }
14407:                                  } else {
14408:                                      $syval = $poss_syval;
14409:                                      $realpossible++;
14410:                                  }
14411:                                  if ($syval) {
14412:                                      if (ref($possibles) eq 'HASH') {
14413:                                          $possibles->{$syval} = 1;
14414:                                      }
14415:                                  }
14416:                              }
14417: 			 }
14418:                      }
14419: 		     if ($realpossible!=1) { $syval=''; }
14420:                  } else {
14421:                      $syval='';
14422:                  }
14423: 	      }
14424:               untie(%bighash);
14425:            }
14426:         }
14427:         if ($syval) {
14428: 	    return $env{$cache_str}=$syval;
14429:         }
14430:     }
14431:     &appenv({'request.ambiguous' => $thisfn});
14432:     return $env{$cache_str}='';
14433: }
14434: 
14435: # ---------------------------------------------------------- Return random seed
14436: 
14437: sub numval {
14438:     my $txt=shift;
14439:     $txt=~tr/A-J/0-9/;
14440:     $txt=~tr/a-j/0-9/;
14441:     $txt=~tr/K-T/0-9/;
14442:     $txt=~tr/k-t/0-9/;
14443:     $txt=~tr/U-Z/0-5/;
14444:     $txt=~tr/u-z/0-5/;
14445:     $txt=~s/\D//g;
14446:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14447:     return int($txt);
14448: }
14449: 
14450: sub numval2 {
14451:     my $txt=shift;
14452:     $txt=~tr/A-J/0-9/;
14453:     $txt=~tr/a-j/0-9/;
14454:     $txt=~tr/K-T/0-9/;
14455:     $txt=~tr/k-t/0-9/;
14456:     $txt=~tr/U-Z/0-5/;
14457:     $txt=~tr/u-z/0-5/;
14458:     $txt=~s/\D//g;
14459:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14460:     my $total;
14461:     foreach my $val (@txts) { $total+=$val; }
14462:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14463:     return int($total);
14464: }
14465: 
14466: sub numval3 {
14467:     use integer;
14468:     my $txt=shift;
14469:     $txt=~tr/A-J/0-9/;
14470:     $txt=~tr/a-j/0-9/;
14471:     $txt=~tr/K-T/0-9/;
14472:     $txt=~tr/k-t/0-9/;
14473:     $txt=~tr/U-Z/0-5/;
14474:     $txt=~tr/u-z/0-5/;
14475:     $txt=~s/\D//g;
14476:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14477:     my $total;
14478:     foreach my $val (@txts) { $total+=$val; }
14479:     if ($_64bit) { $total=(($total<<32)>>32); }
14480:     return $total;
14481: }
14482: 
14483: sub digest {
14484:     my ($data)=@_;
14485:     my $digest=&Digest::MD5::md5($data);
14486:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14487:     my ($e,$f);
14488:     {
14489:         use integer;
14490:         $e=($a+$b);
14491:         $f=($c+$d);
14492:         if ($_64bit) {
14493:             $e=(($e<<32)>>32);
14494:             $f=(($f<<32)>>32);
14495:         }
14496:     }
14497:     if (wantarray) {
14498: 	return ($e,$f);
14499:     } else {
14500: 	my $g;
14501: 	{
14502: 	    use integer;
14503: 	    $g=($e+$f);
14504: 	    if ($_64bit) {
14505: 		$g=(($g<<32)>>32);
14506: 	    }
14507: 	}
14508: 	return $g;
14509:     }
14510: }
14511: 
14512: sub latest_rnd_algorithm_id {
14513:     return '64bit5';
14514: }
14515: 
14516: sub get_rand_alg {
14517:     my ($courseid)=@_;
14518:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14519:     if ($courseid) {
14520: 	return $env{"course.$courseid.rndseed"};
14521:     }
14522:     return &latest_rnd_algorithm_id();
14523: }
14524: 
14525: sub validCODE {
14526:     my ($CODE)=@_;
14527:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14528:     return 0;
14529: }
14530: 
14531: sub getCODE {
14532:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14533:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14534: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14535: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14536: 	return $Apache::lonhomework::history{'resource.CODE'};
14537:     }
14538:     return undef;
14539: }
14540: #
14541: #  Determines the random seed for a specific context:
14542: #
14543: # parameters:
14544: #   symb      - in course context the symb for the seed.
14545: #   course_id - The course id of the form domain_coursenum.
14546: #   domain    - Domain for the user.
14547: #   course    - Course for the user.
14548: #   cenv      - environment of the course.
14549: #
14550: # NOTE:
14551: #   All parameters are picked out of the environment if missing
14552: #   or not defined.
14553: #   If a symb cannot be determined the current time is used instead.
14554: #
14555: #  For a given well defined symb, courside, domain, username,
14556: #  and course environment, the seed is reproducible.
14557: #
14558: sub rndseed {
14559:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14560:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14561:     if (!defined($symb)) {
14562: 	unless ($symb=$wsymb) { return time; }
14563:     }
14564:     if (!defined $courseid) { 
14565: 	$courseid=$wcourseid; 
14566:     }
14567:     if (!defined $domain) { $domain=$wdomain; }
14568:     if (!defined $username) { $username=$wusername }
14569: 
14570:     my $which;
14571:     if (defined($cenv->{'rndseed'})) {
14572: 	$which = $cenv->{'rndseed'};
14573:     } else {
14574: 	$which =&get_rand_alg($courseid);
14575:     }
14576:     if (defined(&getCODE())) {
14577: 
14578: 	if ($which eq '64bit5') {
14579: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14580: 	} elsif ($which eq '64bit4') {
14581: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14582: 	} else {
14583: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14584: 	}
14585:     } elsif ($which eq '64bit5') {
14586: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14587:     } elsif ($which eq '64bit4') {
14588: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14589:     } elsif ($which eq '64bit3') {
14590: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14591:     } elsif ($which eq '64bit2') {
14592: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14593:     } elsif ($which eq '64bit') {
14594: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14595:     }
14596:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14597: }
14598: 
14599: sub rndseed_32bit {
14600:     my ($symb,$courseid,$domain,$username)=@_;
14601:     {
14602: 	use integer;
14603: 	my $symbchck=unpack("%32C*",$symb) << 27;
14604: 	my $symbseed=numval($symb) << 22;
14605: 	my $namechck=unpack("%32C*",$username) << 17;
14606: 	my $nameseed=numval($username) << 12;
14607: 	my $domainseed=unpack("%32C*",$domain) << 7;
14608: 	my $courseseed=unpack("%32C*",$courseid);
14609: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14610: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14611: 	#&logthis("rndseed :$num:$symb");
14612: 	if ($_64bit) { $num=(($num<<32)>>32); }
14613: 	return $num;
14614:     }
14615: }
14616: 
14617: sub rndseed_64bit {
14618:     my ($symb,$courseid,$domain,$username)=@_;
14619:     {
14620: 	use integer;
14621: 	my $symbchck=unpack("%32S*",$symb) << 21;
14622: 	my $symbseed=numval($symb) << 10;
14623: 	my $namechck=unpack("%32S*",$username);
14624: 	
14625: 	my $nameseed=numval($username) << 21;
14626: 	my $domainseed=unpack("%32S*",$domain) << 10;
14627: 	my $courseseed=unpack("%32S*",$courseid);
14628: 	
14629: 	my $num1=$symbchck+$symbseed+$namechck;
14630: 	my $num2=$nameseed+$domainseed+$courseseed;
14631: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14632: 	#&logthis("rndseed :$num:$symb");
14633: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14634: 	return "$num1,$num2";
14635:     }
14636: }
14637: 
14638: sub rndseed_64bit2 {
14639:     my ($symb,$courseid,$domain,$username)=@_;
14640:     {
14641: 	use integer;
14642: 	# strings need to be an even # of cahracters long, it it is odd the
14643:         # last characters gets thrown away
14644: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14645: 	my $symbseed=numval($symb) << 10;
14646: 	my $namechck=unpack("%32S*",$username.' ');
14647: 	
14648: 	my $nameseed=numval($username) << 21;
14649: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14650: 	my $courseseed=unpack("%32S*",$courseid.' ');
14651: 	
14652: 	my $num1=$symbchck+$symbseed+$namechck;
14653: 	my $num2=$nameseed+$domainseed+$courseseed;
14654: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14655: 	#&logthis("rndseed :$num:$symb");
14656: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14657: 	return "$num1,$num2";
14658:     }
14659: }
14660: 
14661: sub rndseed_64bit3 {
14662:     my ($symb,$courseid,$domain,$username)=@_;
14663:     {
14664: 	use integer;
14665: 	# strings need to be an even # of cahracters long, it it is odd the
14666:         # last characters gets thrown away
14667: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14668: 	my $symbseed=numval2($symb) << 10;
14669: 	my $namechck=unpack("%32S*",$username.' ');
14670: 	
14671: 	my $nameseed=numval2($username) << 21;
14672: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14673: 	my $courseseed=unpack("%32S*",$courseid.' ');
14674: 	
14675: 	my $num1=$symbchck+$symbseed+$namechck;
14676: 	my $num2=$nameseed+$domainseed+$courseseed;
14677: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14678: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14679: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14680: 	
14681: 	return "$num1:$num2";
14682:     }
14683: }
14684: 
14685: sub rndseed_64bit4 {
14686:     my ($symb,$courseid,$domain,$username)=@_;
14687:     {
14688: 	use integer;
14689: 	# strings need to be an even # of cahracters long, it it is odd the
14690:         # last characters gets thrown away
14691: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14692: 	my $symbseed=numval3($symb) << 10;
14693: 	my $namechck=unpack("%32S*",$username.' ');
14694: 	
14695: 	my $nameseed=numval3($username) << 21;
14696: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14697: 	my $courseseed=unpack("%32S*",$courseid.' ');
14698: 	
14699: 	my $num1=$symbchck+$symbseed+$namechck;
14700: 	my $num2=$nameseed+$domainseed+$courseseed;
14701: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14702: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14703: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14704: 	
14705: 	return "$num1:$num2";
14706:     }
14707: }
14708: 
14709: sub rndseed_64bit5 {
14710:     my ($symb,$courseid,$domain,$username)=@_;
14711:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14712:     return "$num1:$num2";
14713: }
14714: 
14715: sub rndseed_CODE_64bit {
14716:     my ($symb,$courseid,$domain,$username)=@_;
14717:     {
14718: 	use integer;
14719: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14720: 	my $symbseed=numval2($symb);
14721: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14722: 	my $CODEseed=numval(&getCODE());
14723: 	my $courseseed=unpack("%32S*",$courseid.' ');
14724: 	my $num1=$symbseed+$CODEchck;
14725: 	my $num2=$CODEseed+$courseseed+$symbchck;
14726: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14727: 	#&logthis("rndseed :$num1:$num2:$symb");
14728: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14729: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14730: 	return "$num1:$num2";
14731:     }
14732: }
14733: 
14734: sub rndseed_CODE_64bit4 {
14735:     my ($symb,$courseid,$domain,$username)=@_;
14736:     {
14737: 	use integer;
14738: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14739: 	my $symbseed=numval3($symb);
14740: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14741: 	my $CODEseed=numval3(&getCODE());
14742: 	my $courseseed=unpack("%32S*",$courseid.' ');
14743: 	my $num1=$symbseed+$CODEchck;
14744: 	my $num2=$CODEseed+$courseseed+$symbchck;
14745: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14746: 	#&logthis("rndseed :$num1:$num2:$symb");
14747: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14748: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14749: 	return "$num1:$num2";
14750:     }
14751: }
14752: 
14753: sub rndseed_CODE_64bit5 {
14754:     my ($symb,$courseid,$domain,$username)=@_;
14755:     my $code = &getCODE();
14756:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14757:     return "$num1:$num2";
14758: }
14759: 
14760: sub setup_random_from_rndseed {
14761:     my ($rndseed)=@_;
14762:     if ($rndseed =~/([,:])/) {
14763:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14764:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14765:             &Math::Random::random_set_seed_from_phrase($rndseed);
14766:         } else {
14767:             &Math::Random::random_set_seed($num1,$num2);
14768:         }
14769:     } else {
14770: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14771:     }
14772: }
14773: 
14774: sub latest_receipt_algorithm_id {
14775:     return 'receipt3';
14776: }
14777: 
14778: sub recunique {
14779:     my $fucourseid=shift;
14780:     my $unique;
14781:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14782: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14783: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14784:     } else {
14785: 	$unique=$perlvar{'lonReceipt'};
14786:     }
14787:     return unpack("%32C*",$unique);
14788: }
14789: 
14790: sub recprefix {
14791:     my $fucourseid=shift;
14792:     my $prefix;
14793:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14794: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14795: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14796:     } else {
14797: 	$prefix=$perlvar{'lonHostID'};
14798:     }
14799:     return unpack("%32C*",$prefix);
14800: }
14801: 
14802: sub ireceipt {
14803:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14804: 
14805:     my $return =&recprefix($fucourseid).'-';
14806: 
14807:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14808: 	$env{'request.state'} eq 'construct') {
14809: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14810: 	return $return;
14811:     }
14812: 
14813:     my $cuname=unpack("%32C*",$funame);
14814:     my $cudom=unpack("%32C*",$fudom);
14815:     my $cucourseid=unpack("%32C*",$fucourseid);
14816:     my $cusymb=unpack("%32C*",$fusymb);
14817:     my $cunique=&recunique($fucourseid);
14818:     my $cpart=unpack("%32S*",$part);
14819:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14820: 
14821: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14822: 			       
14823: 	$return.= ($cunique%$cuname+
14824: 		   $cunique%$cudom+
14825: 		   $cusymb%$cuname+
14826: 		   $cusymb%$cudom+
14827: 		   $cucourseid%$cuname+
14828: 		   $cucourseid%$cudom+
14829: 		   $cpart%$cuname+
14830: 		   $cpart%$cudom);
14831:     } else {
14832: 	$return.= ($cunique%$cuname+
14833: 		   $cunique%$cudom+
14834: 		   $cusymb%$cuname+
14835: 		   $cusymb%$cudom+
14836: 		   $cucourseid%$cuname+
14837: 		   $cucourseid%$cudom);
14838:     }
14839:     return $return;
14840: }
14841: 
14842: sub receipt {
14843:     my ($part)=@_;
14844:     my ($symb,$courseid,$domain,$name) = &whichuser();
14845:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14846: }
14847: 
14848: sub whichuser {
14849:     my ($passedsymb)=@_;
14850:     my ($symb,$courseid,$domain,$name,$publicuser);
14851:     if (defined($env{'form.grade_symb'})) {
14852: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14853: 	my $allowed=&allowed('vgr',$tmp_courseid);
14854: 	if (!$allowed &&
14855: 	    exists($env{'request.course.sec'}) &&
14856: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14857: 	    $allowed=&allowed('vgr',$tmp_courseid.
14858: 			      '/'.$env{'request.course.sec'});
14859: 	}
14860: 	if ($allowed) {
14861: 	    ($symb)=&get_env_multiple('form.grade_symb');
14862: 	    $courseid=$tmp_courseid;
14863: 	    ($domain)=&get_env_multiple('form.grade_domain');
14864: 	    ($name)=&get_env_multiple('form.grade_username');
14865: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14866: 	}
14867:     }
14868:     if (!$passedsymb) {
14869: 	$symb=&symbread();
14870:     } else {
14871: 	$symb=$passedsymb;
14872:     }
14873:     $courseid=$env{'request.course.id'};
14874:     $domain=$env{'user.domain'};
14875:     $name=$env{'user.name'};
14876:     if ($name eq 'public' && $domain eq 'public') {
14877: 	if (!defined($env{'form.username'})) {
14878: 	    $env{'form.username'}.=time.rand(10000000);
14879: 	}
14880: 	$name.=$env{'form.username'};
14881:     }
14882:     return ($symb,$courseid,$domain,$name,$publicuser);
14883: 
14884: }
14885: 
14886: # ------------------------------------------------------------ Serves up a file
14887: # returns either the contents of the file or 
14888: # -1 if the file doesn't exist
14889: #
14890: # if the target is a file that was uploaded via DOCS, 
14891: # a check will be made to see if a current copy exists on the local server,
14892: # if it does this will be served, otherwise a copy will be retrieved from
14893: # the home server for the course and stored in /home/httpd/html/userfiles on
14894: # the local server.   
14895: 
14896: sub getfile {
14897:     my ($file) = @_;
14898:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14899:     &repcopy($file);
14900:     return &readfile($file);
14901: }
14902: 
14903: sub repcopy_userfile {
14904:     my ($file)=@_;
14905:     my $londocroot = $perlvar{'lonDocRoot'};
14906:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14907:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14908:     my ($cdom,$cnum,$filename) = 
14909: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14910:     my $uri="/uploaded/$cdom/$cnum/$filename";
14911:     if (-e "$file") {
14912: # we already have a local copy, check it out
14913: 	my @fileinfo = stat($file);
14914: 	my $rtncode;
14915: 	my $info;
14916: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14917: 	if ($lwpresp ne 'ok') {
14918: # there is no such file anymore, even though we had a local copy
14919: 	    if ($rtncode eq '404') {
14920: 		unlink($file);
14921: 	    }
14922: 	    return -1;
14923: 	}
14924: 	if ($info < $fileinfo[9]) {
14925: # nice, the file we have is up-to-date, just say okay
14926: 	    return 'ok';
14927: 	} else {
14928: # the file is outdated, get rid of it
14929: 	    unlink($file);
14930: 	}
14931:     }
14932: # one way or the other, at this point, we don't have the file
14933: # construct the correct path for the file
14934:     my @parts = ($cdom,$cnum); 
14935:     if ($filename =~ m|^(.+)/[^/]+$|) {
14936: 	push @parts, split(/\//,$1);
14937:     }
14938:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14939:     foreach my $part (@parts) {
14940: 	$path .= '/'.$part;
14941: 	if (!-e $path) {
14942: 	    mkdir($path,0770);
14943: 	}
14944:     }
14945: # now the path exists for sure
14946: # get a user agent
14947:     my $transferfile=$file.'.in.transfer';
14948: # FIXME: this should flock
14949:     if (-e $transferfile) { return 'ok'; }
14950:     my $request;
14951:     $uri=~s/^\///;
14952:     my $homeserver = &homeserver($cnum,$cdom);
14953:     my $hostname = &hostname($homeserver);
14954:     my $protocol = $protocol{$homeserver};
14955:     $protocol = 'http' if ($protocol ne 'https');
14956:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14957:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14958: # did it work?
14959:     if ($response->is_error()) {
14960: 	unlink($transferfile);
14961: 	&logthis("Userfile repcopy failed for $uri");
14962: 	return -1;
14963:     }
14964: # worked, rename the transfer file
14965:     rename($transferfile,$file);
14966:     return 'ok';
14967: }
14968: 
14969: sub tokenwrapper {
14970:     my $uri=shift;
14971:     $uri=~s|^https?\://([^/]+)||;
14972:     $uri=~s|^/||;
14973:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14974:     my $token=$1;
14975:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14976:     if ($udom && $uname && $file) {
14977: 	$file=~s|(\?\.*)*$||;
14978:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14979:         my $homeserver = &homeserver($uname,$udom);
14980:         my $hostname = &hostname($homeserver);
14981:         my $protocol = $protocol{$homeserver};
14982:         $protocol = 'http' if ($protocol ne 'https');
14983:         return $protocol.'://'.$hostname.'/'.$uri.
14984:                (($uri=~/\?/)?'&':'?').'token='.$token.
14985:                                '&tokenissued='.$perlvar{'lonHostID'};
14986:     } else {
14987:         return '/adm/notfound.html';
14988:     }
14989: }
14990: 
14991: # call with reqtype HEAD: get last modification time
14992: # call with reqtype GET: get the file contents
14993: # Do not call this with reqtype GET for large files! It loads everything into memory
14994: #
14995: sub getuploaded {
14996:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14997:     $uri=~s/^\///;
14998:     my $homeserver = &homeserver($cnum,$cdom);
14999:     my $hostname = &hostname($homeserver);
15000:     my $protocol = $protocol{$homeserver};
15001:     $protocol = 'http' if ($protocol ne 'https');
15002:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
15003:     my $request=new HTTP::Request($reqtype,$uri);
15004:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
15005:     $$rtncode = $response->code;
15006:     if (! $response->is_success()) {
15007: 	return 'failed';
15008:     }      
15009:     if ($reqtype eq 'HEAD') {
15010: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
15011:     } elsif ($reqtype eq 'GET') {
15012: 	$$info = $response->content;
15013:     }
15014:     return 'ok';
15015: }
15016: 
15017: sub readfile {
15018:     my $file = shift;
15019:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
15020:     my $fh;
15021:     open($fh,"<",$file);
15022:     my $a='';
15023:     while (my $line = <$fh>) { $a .= $line; }
15024:     return $a;
15025: }
15026: 
15027: sub filelocation {
15028:     my ($dir,$file) = @_;
15029:     my $location;
15030:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
15031: 
15032:     if ($file =~ m-^/adm/-) {
15033: 	$file=~s-^/adm/wrapper/-/-;
15034: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15035:     }
15036: 
15037:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15038:         $location = $file;
15039:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15040:         my ($udom,$uname,$filename)=
15041:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15042:         my $home=&homeserver($uname,$udom);
15043:         my $is_me=0;
15044:         my @ids=&current_machine_ids();
15045:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15046:         if ($is_me) {
15047:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15048:         } else {
15049:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15050:   	      $udom.'/'.$uname.'/'.$filename;
15051:         }
15052:     } elsif ($file =~ m-^/adm/-) {
15053: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15054:     } else {
15055:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15056:         $file=~s:^/(res|priv)/:/:;
15057:         my $space=$1;
15058:         if ( !( $file =~ m:^/:) ) {
15059:             $location = $dir. '/'.$file;
15060:         } else {
15061:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15062:         }
15063:     }
15064:     $location=~s://+:/:g; # remove duplicate /
15065:     while ($location=~m{/\.\./}) {
15066: 	if ($location =~ m{/[^/]+/\.\./}) {
15067: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15068: 	} else {
15069: 	    $location=~ s{/\.\./}{/}g;
15070: 	}
15071:     } #remove dir/..
15072:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15073:     return $location;
15074: }
15075: 
15076: sub hreflocation {
15077:     my ($dir,$file)=@_;
15078:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15079: 	$file=filelocation($dir,$file);
15080:     } elsif ($file=~m-^/adm/-) {
15081: 	$file=~s-^/adm/wrapper/-/-;
15082: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15083:     }
15084:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15085: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15086:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15087: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15088: 	        {/uploaded/$1/$2/}x;
15089:     }
15090:     if ($file=~ m{^/userfiles/}) {
15091: 	$file =~ s{^/userfiles/}{/uploaded/};
15092:     }
15093:     return $file;
15094: }
15095: 
15096: 
15097: 
15098: 
15099: 
15100: sub current_machine_domains {
15101:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15102: }
15103: 
15104: sub machine_domains {
15105:     my ($hostname) = @_;
15106:     my @domains;
15107:     my %hostname = &all_hostnames();
15108:     while( my($id, $name) = each(%hostname)) {
15109: #	&logthis("-$id-$name-$hostname-");
15110: 	if ($hostname eq $name) {
15111: 	    push(@domains,&host_domain($id));
15112: 	}
15113:     }
15114:     return @domains;
15115: }
15116: 
15117: sub current_machine_ids {
15118:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15119: }
15120: 
15121: sub machine_ids {
15122:     my ($hostname) = @_;
15123:     $hostname ||= &hostname($perlvar{'lonHostID'});
15124:     my @ids;
15125:     my %name_to_host = &all_names();
15126:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15127: 	return @{ $name_to_host{$hostname} };
15128:     }
15129:     return;
15130: }
15131: 
15132: sub additional_machine_domains {
15133:     my @domains;
15134:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15135:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15136:             while (my $line = <$fh>) {
15137:                 chomp($line);           
15138:                 $line =~ s/\s//g;
15139:                 push(@domains,$line);
15140:             }
15141:             close($fh);
15142:         }
15143:     }
15144:     return @domains;
15145: }
15146: 
15147: sub default_login_domain {
15148:     my $domain = $perlvar{'lonDefDomain'};
15149:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15150:     foreach my $posdom (&current_machine_domains(),
15151:                         &additional_machine_domains()) {
15152:         if (lc($posdom) eq lc($testdomain)) {
15153:             $domain=$posdom;
15154:             last;
15155:         }
15156:     }
15157:     return $domain;
15158: }
15159: 
15160: sub shared_institution {
15161:     my ($dom,$lonhost) = @_;
15162:     if ($lonhost eq '') {
15163:         $lonhost = $perlvar{'lonHostID'};
15164:     }
15165:     my $same_intdom;
15166:     my $hostintdom = &internet_dom($lonhost);
15167:     if ($hostintdom ne '') {
15168:         my %iphost = &get_iphost();
15169:         my $primary_id = &domain($dom,'primary');
15170:         my $primary_ip = &get_host_ip($primary_id);
15171:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15172:             foreach my $id (@{$iphost{$primary_ip}}) {
15173:                 my $intdom = &internet_dom($id);
15174:                 if ($intdom eq $hostintdom) {
15175:                     $same_intdom = 1;
15176:                     last;
15177:                 }
15178:             }
15179:         }
15180:     }
15181:     return $same_intdom;
15182: }
15183: 
15184: sub uses_sts {
15185:     my ($ignore_cache) = @_;
15186:     my $lonhost = $perlvar{'lonHostID'};
15187:     my $hostname = &hostname($lonhost);
15188:     my $sts_on;
15189:     if ($protocol{$lonhost} eq 'https') {
15190:         my $cachetime = 12*3600;
15191:         if (!$ignore_cache) {
15192:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15193:             if (defined($cached)) {
15194:                 return $sts_on;
15195:             }
15196:         }
15197:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15198:         my $request=new HTTP::Request('HEAD',$url);
15199:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15200:         if ($response->is_success) {
15201:             my $has_sts = $response->header('Strict-Transport-Security');
15202:             if ($has_sts eq '') {
15203:                 $sts_on = 0;
15204:             } else {
15205:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15206:                     my $maxage = $1;
15207:                     if ($maxage) {
15208:                         $sts_on = 1;
15209:                     } else {
15210:                         $sts_on = 0;
15211:                     }
15212:                 } else {
15213:                     $sts_on = 0;
15214:                 }
15215:             }
15216:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15217:         }
15218:     }
15219:     return;
15220: }
15221: 
15222: sub waf_allssl {
15223:     my ($host_name) = @_;
15224:     my $alias = &get_proxy_alias();
15225:     if ($host_name eq '') {
15226:         $host_name = $ENV{'SERVER_NAME'};
15227:     }
15228:     if (($host_name ne '') && ($alias eq $host_name)) {
15229:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15230:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15231:         if ($defdomdefaults{'waf_sslopt'}) {
15232:             return $defdomdefaults{'waf_sslopt'};
15233:         }
15234:     }
15235:     return;
15236: }
15237: 
15238: sub get_requestor_ip {
15239:     my ($r,$nolookup,$noproxy) = @_;
15240:     my $from_ip;
15241:     if (ref($r)) {
15242:         if ($r->can('useragent_ip')) {
15243:             if ($noproxy && $r->can('client_ip')) {
15244:                 $from_ip = $r->client_ip();
15245:             } else {
15246:                 $from_ip = $r->useragent_ip();
15247:             }
15248:         } elsif ($r->connection->can('remote_ip')) {
15249:             $from_ip = $r->connection->remote_ip();
15250:         } else {
15251:             $from_ip = $r->get_remote_host($nolookup);
15252:         }
15253:     } else {
15254:         $from_ip = $ENV{'REMOTE_ADDR'};
15255:     }
15256:     return $from_ip if ($noproxy); 
15257:     # Who controls proxy settings for server
15258:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15259:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15260:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15261:         if ($proxyinfo->{'vpnint'}) {
15262:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15263:                 return $from_ip;
15264:             }
15265:         }
15266:         if ($proxyinfo->{'trusted'}) {
15267:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15268:                 my $ipheader = $proxyinfo->{'ipheader'};
15269:                 my ($ip,$xfor);
15270:                 if (ref($r)) {
15271:                     if ($ipheader) {
15272:                         $ip = $r->headers_in->{$ipheader};
15273:                     }
15274:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15275:                 } else {
15276:                     if ($ipheader) {
15277:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15278:                     }
15279:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15280:                 }
15281:                 if (($ip eq '') && ($xfor ne '')) {
15282:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15283:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15284:                             $ip = $poss_ip;
15285:                             last;
15286:                         }
15287:                     }
15288:                 }
15289:                 if ($ip ne '') {
15290:                     return $ip;
15291:                 }
15292:             }
15293:         }
15294:     }
15295:     return $from_ip;
15296: }
15297: 
15298: sub get_proxy_settings {
15299:     my ($dom_in_use) = @_;
15300:     my %domdefaults = &get_domain_defaults($dom_in_use);
15301:     my $proxyinfo = {
15302:                        ipheader => $domdefaults{'waf_ipheader'},
15303:                        trusted  => $domdefaults{'waf_trusted'},
15304:                        vpnint   => $domdefaults{'waf_vpnint'},
15305:                        vpnext   => $domdefaults{'waf_vpnext'},
15306:                        sslopt   => $domdefaults{'waf_sslopt'},
15307:                     };
15308:     return $proxyinfo;
15309: }
15310: 
15311: sub ip_match {
15312:     my ($ip,$pattern_str) = @_;
15313:     $ip=Net::CIDR::cidrvalidate($ip);
15314:     if ($ip) {
15315:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15316:     }
15317:     return;
15318: }
15319: 
15320: sub get_proxy_alias {
15321:     my ($lonid) = @_;
15322:     if ($lonid eq '') {
15323:         $lonid = $perlvar{'lonHostID'};
15324:     }
15325:     if (!defined(&hostname($lonid))) {
15326:         return;
15327:     }
15328:     if ($lonid ne '') {
15329:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15330:         if ($cached) {
15331:             return $alias;
15332:         }
15333:         my $dom = &host_domain($lonid);
15334:         if ($dom ne '') {
15335:             my $cachetime = 60*60*24;
15336:             my %domconfig =
15337:                 &get_dom('configuration',['wafproxy'],$dom);
15338:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15339:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15340:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15341:                 }
15342:             }
15343:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15344:         }
15345:     }
15346:     return;
15347: }
15348: 
15349: sub use_proxy_alias {
15350:     my ($r,$lonid) = @_;
15351:     my $alias = &get_proxy_alias($lonid);
15352:     if ($alias) {
15353:         my $dom = &host_domain($lonid);
15354:         if ($dom ne '') {
15355:             my $proxyinfo = &get_proxy_settings($dom);
15356:             my ($vpnint,$remote_ip);
15357:             if (ref($proxyinfo) eq 'HASH') {
15358:                 $vpnint = $proxyinfo->{'vpnint'};
15359:                 if ($vpnint) {
15360:                     $remote_ip = &get_requestor_ip($r,1,1);
15361:                 }
15362:             }
15363:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15364:                 return $alias;
15365:             }
15366:         }
15367:     }
15368:     return;
15369: }
15370: 
15371: sub alias_sso {
15372:     my ($lonid) = @_;
15373:     if ($lonid eq '') {
15374:         $lonid = $perlvar{'lonHostID'};
15375:     }
15376:     if (!defined(&hostname($lonid))) {
15377:         return;
15378:     }
15379:     if ($lonid ne '') {
15380:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15381:         if ($cached) {
15382:             return $use_alias;
15383:         }
15384:         my $dom = &host_domain($lonid);
15385:         if ($dom ne '') {
15386:             my $cachetime = 60*60*24;
15387:             my %domconfig =
15388:                 &get_dom('configuration',['wafproxy'],$dom);
15389:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15390:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15391:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15392:                 }
15393:             }
15394:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15395:         }
15396:     }
15397:     return;
15398: }
15399: 
15400: sub get_saml_landing {
15401:     my ($lonid) = @_;
15402:     if ($lonid eq '') {
15403:         my $defdom = &default_login_domain();
15404:         my @hosts = &current_machine_ids();
15405:         if (@hosts > 1) {
15406:             foreach my $hostid (@hosts) {
15407:                 if (&host_domain($hostid) eq $defdom) {
15408:                     $lonid = $hostid;
15409:                     last;
15410:                 }
15411:             }
15412:         } else {
15413:             $lonid = $perlvar{'lonHostID'};
15414:         }
15415:         if ($lonid) {
15416:             unless (&host_domain($lonid) eq $defdom) {
15417:                 return;
15418:             }
15419:         } else {
15420:             return;
15421:         }
15422:     } elsif (!defined(&hostname($lonid))) {
15423:         return;
15424:     }
15425:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15426:     if ($cached) {
15427:         return $landing;
15428:     }
15429:     my $dom = &host_domain($lonid);
15430:     if ($dom ne '') {
15431:         my $cachetime = 60*60*24;
15432:         my %domconfig =
15433:             &get_dom('configuration',['login'],$dom);
15434:         if (ref($domconfig{'login'}) eq 'HASH') {
15435:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15436:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15437:                     $landing = 1;
15438:                 }
15439:             }
15440:         }
15441:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15442:     }
15443:     return;
15444: }
15445: 
15446: # ------------------------------------------------------------- Declutters URLs
15447: 
15448: sub declutter {
15449:     my $thisfn=shift;
15450:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15451:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15452:         $thisfn=~s{^/home/httpd/html}{};
15453:     }
15454:     $thisfn=~s/^\///;
15455:     $thisfn=~s|^adm/wrapper/||;
15456:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15457:     $thisfn=~s/^res\///;
15458:     $thisfn=~s/^priv\///;
15459:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15460:         $thisfn=~s/\?.+$//;
15461:     }
15462:     return $thisfn;
15463: }
15464: 
15465: # ------------------------------------------------------------- Clutter up URLs
15466: 
15467: sub clutter {
15468:     my $thisfn='/'.&declutter(shift);
15469:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15470: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15471:        $thisfn='/res'.$thisfn; 
15472:     }
15473:     if ($thisfn !~m|^/adm|) {
15474: 	if ($thisfn =~ m|^/ext/|) {
15475: 	    $thisfn='/adm/wrapper'.$thisfn;
15476: 	} else {
15477: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15478: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15479: 	    if ($embstyle eq 'ssi'
15480: 		|| ($embstyle eq 'hdn')
15481: 		|| ($embstyle eq 'rat')
15482: 		|| ($embstyle eq 'prv')
15483: 		|| ($embstyle eq 'ign')) {
15484: 		#do nothing with these
15485: 	    } elsif (($embstyle eq 'img') 
15486: 		|| ($embstyle eq 'emb')
15487: 		|| ($embstyle eq 'wrp')) {
15488: 		$thisfn='/adm/wrapper'.$thisfn;
15489: 	    } elsif ($embstyle eq 'unk'
15490: 		     && $thisfn!~/\.(sequence|page)$/) {
15491: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15492: 	    } else {
15493: #		&logthis("Got a blank emb style");
15494: 	    }
15495: 	}
15496:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15497:         $thisfn='/adm/wrapper'.$thisfn;
15498:     }
15499:     return $thisfn;
15500: }
15501: 
15502: sub clutter_with_no_wrapper {
15503:     my $uri = &clutter(shift);
15504:     if ($uri =~ m-^/adm/-) {
15505: 	$uri =~ s-^/adm/wrapper/-/-;
15506: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15507:     }
15508:     return $uri;
15509: }
15510: 
15511: sub freeze_escape {
15512:     my ($value)=@_;
15513:     if (ref($value)) {
15514: 	$value=&nfreeze($value);
15515: 	return '__FROZEN__'.&escape($value);
15516:     }
15517:     return &escape($value);
15518: }
15519: 
15520: 
15521: sub thaw_unescape {
15522:     my ($value)=@_;
15523:     if ($value =~ /^__FROZEN__/) {
15524: 	substr($value,0,10,undef);
15525: 	$value=&unescape($value);
15526: 	return &thaw($value);
15527:     }
15528:     return &unescape($value);
15529: }
15530: 
15531: sub correct_line_ends {
15532:     my ($result)=@_;
15533:     $$result =~s/\r\n/\n/mg;
15534:     $$result =~s/\r/\n/mg;
15535: }
15536: # ================================================================ Main Program
15537: 
15538: sub goodbye {
15539:    &logthis("Starting Shut down");
15540: #not converted to using infrastruture and probably shouldn't be
15541:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15542: #converted
15543: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15544:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15545: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15546: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15547: #1.1 only
15548: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15549: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15550: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15551: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15552:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15553:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15554:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15555:    &flushcourselogs();
15556:    &logthis("Shutting down");
15557: }
15558: 
15559: sub get_dns {
15560:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15561:     if (!$ignore_cache) {
15562: 	my ($content,$cached)=
15563: 	    &is_cached_new('dns',$url);
15564: 	if ($cached) {
15565: 	    &$func($content,$hashref);
15566: 	    return;
15567: 	}
15568:     }
15569: 
15570:     my %alldns;
15571:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15572:         foreach my $dns (<$config>) {
15573: 	    next if ($dns !~ /^\^(\S*)/x);
15574:             my $line = $1;
15575:             my ($host,$protocol) = split(/:/,$line);
15576:             if ($protocol ne 'https') {
15577:                 $protocol = 'http';
15578:             }
15579: 	    $alldns{$host} = $protocol;
15580:         }
15581:         close($config);
15582:     }
15583:     while (%alldns) {
15584: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15585:         my ($contents,@content);
15586:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15587:             my $command = (split('/',$url))[3];
15588:             my ($dir,$file) = &parse_getdns_url($command,$url);
15589:             delete($alldns{$dns});
15590:             next if (($dir eq '') || ($file eq ''));
15591:             if (open(my $config,'<',"$dir/$file")) {
15592:                 @content = <$config>;
15593:                 close($config);
15594:             }
15595:             if ($url eq '/adm/dns/loncapaCRL') {
15596:                 $contents = join('',@content);
15597:             }
15598:         } else {
15599: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15600:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15601:             delete($alldns{$dns});
15602: 	    next if ($response->is_error());
15603:             if ($url eq '/adm/dns/loncapaCRL') {
15604:                 $contents = $response->content;
15605:             } else {
15606:                 @content = split("\n",$response->content);
15607:             }
15608:         }
15609:         if ($url eq '/adm/dns/loncapaCRL') {
15610:             return &$func($contents);
15611:         } else {
15612: 	    unless ($nocache) {
15613: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15614: 	    }
15615: 	    &$func(\@content,$hashref);
15616:             return;
15617:         }
15618:     }
15619:     my $which = (split('/',$url,4))[3];
15620:     if ($which eq 'loncapaCRL') {
15621:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15622:         if (-e $diskfile) {
15623:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15624:         } else {
15625:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15626:         }
15627:     } else {
15628:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15629:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15630:             my @content = <$config>;
15631:             close($config);
15632:             &$func(\@content,$hashref);
15633:         }
15634:     }
15635:     return;
15636: }
15637: 
15638: # ------------------------------------------------------Get DNS checksums file
15639: sub parse_dns_checksums_tab {
15640:     my ($lines,$hashref) = @_;
15641:     my $lonhost = $perlvar{'lonHostID'};
15642:     my $machine_dom = &host_domain($lonhost);
15643:     my $loncaparev = &get_server_loncaparev($machine_dom);
15644:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15645:     my $webconfdir = '/etc/httpd/conf';
15646:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15647:         $webconfdir = '/etc/apache2';
15648:     } elsif ($distro =~ /^sles(\d+)$/) {
15649:         if ($1 >= 10) {
15650:             $webconfdir = '/etc/apache2';
15651:         }
15652:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15653:         if ($1 >= 10.0) {
15654:             $webconfdir = '/etc/apache2';
15655:         }
15656:     }
15657:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15658:     my (%chksum,%revnum);
15659:     if (ref($lines) eq 'ARRAY') {
15660:         chomp(@{$lines});
15661:         my $version = shift(@{$lines});
15662:         if ($version eq $release) {  
15663:             foreach my $line (@{$lines}) {
15664:                 my ($file,$version,$shasum) = split(/,/,$line);
15665:                 if ($file =~ m{^/etc/httpd/conf}) {
15666:                     if ($webconfdir eq '/etc/apache2') {
15667:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15668:                     }
15669:                 }
15670:                 $chksum{$file} = $shasum;
15671:                 $revnum{$file} = $version;
15672:             }
15673:             if (ref($hashref) eq 'HASH') {
15674:                 %{$hashref} = (
15675:                                 sums     => \%chksum,
15676:                                 versions => \%revnum,
15677:                               );
15678:             }
15679:         }
15680:     }
15681:     return;
15682: }
15683: 
15684: sub fetch_dns_checksums {
15685:     my %checksums;
15686:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15687:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15688:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15689:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15690:              \%checksums);
15691:     return \%checksums;
15692: }
15693: 
15694: sub fetch_crl_pemfile {
15695:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15696: }
15697: 
15698: sub save_crl_pem {
15699:     my ($content) = @_;
15700:     my ($msg,$hadchanges);
15701:     if ($content ne '') {
15702:         my $now = time;
15703:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15704:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15705:         if (open(my $fh,'>',"$tmpcrl")) {
15706:             print $fh $content;
15707:             close($fh);
15708:             if (-e $lonca) {
15709:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15710:                     my $check = <PIPE>;
15711:                     close(PIPE);
15712:                     chomp($check);
15713:                     if ($check eq 'verify OK') {
15714:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15715:                         my $backup;
15716:                         if (-e $dest) {
15717:                             if (&File::Copy::move($dest,"$dest.bak")) {
15718:                                 $backup = 'ok';
15719:                             }
15720:                         }
15721:                         if (&File::Copy::move($tmpcrl,$dest)) {
15722:                             $msg = 'ok';
15723:                             if ($backup) {
15724:                                 my (%oldnums,%newnums);
15725:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15726:                                     while (<PIPE>) {
15727:                                         $oldnums{(split(/:/))[1]} = 1;
15728:                                     }
15729:                                     close(PIPE);
15730:                                 }
15731:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15732:                                     while(<PIPE>) {
15733:                                         $newnums{(split(/:/))[1]} = 1;
15734:                                     }
15735:                                     close(PIPE);
15736:                                 }
15737:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15738:                                     unless (exists($oldnums{$key})) {
15739:                                         $hadchanges = 1;
15740:                                         last;
15741:                                     }
15742:                                 }
15743:                                 unless ($hadchanges) {
15744:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15745:                                         unless (exists($newnums{$key})) {
15746:                                             $hadchanges = 1;
15747:                                             last;
15748:                                         }
15749:                                     }
15750:                                 }
15751:                             }
15752:                         }
15753:                     } else {
15754:                         unlink($tmpcrl);
15755:                     }
15756:                 } else {
15757:                     unlink($tmpcrl);
15758:                 }
15759:             } else {
15760:                 unlink($tmpcrl);
15761:             }
15762:         }
15763:     }
15764:     return ($msg,$hadchanges);
15765: }
15766: 
15767: sub parse_getdns_url {
15768:     my ($command,$url) = @_;
15769:     my $dir = $perlvar{'lonTabDir'};
15770:     my $file;
15771:     if ($command eq 'hosts') {
15772:         $file = 'dns_hosts.tab';
15773:     } elsif ($command eq 'domain') {
15774:         $file = 'dns_domain.tab';
15775:     } elsif ($command eq 'checksums') {
15776:         my $version = (split('/',$url))[4];
15777:         $file = "dns_checksums/$version.tab",
15778:     } elsif ($command eq 'loncapaCRL') {
15779:         $dir = $perlvar{'lonCertificateDirectory'};
15780:         $file = $perlvar{'lonnetCertRevocationList'};
15781:     }
15782:     return ($dir,$file);
15783: }
15784: 
15785: # ------------------------------------------------------------ Read domain file
15786: {
15787:     my $loaded;
15788:     my %domain;
15789: 
15790:     sub parse_domain_tab {
15791: 	my ($lines) = @_;
15792: 	foreach my $line (@$lines) {
15793: 	    next if ($line =~ /^(\#|\s*$ )/x);
15794: 
15795: 	    chomp($line);
15796: 	    my ($name,@elements) = split(/:/,$line,9);
15797: 	    my %this_domain;
15798: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15799: 			       'lang_def', 'city', 'longi', 'lati',
15800: 			       'primary') {
15801: 		$this_domain{$field} = shift(@elements);
15802: 	    }
15803: 	    $domain{$name} = \%this_domain;
15804: 	}
15805:     }
15806: 
15807:     sub reset_domain_info {
15808: 	undef($loaded);
15809: 	undef(%domain);
15810:     }
15811: 
15812:     sub load_domain_tab {
15813: 	my ($ignore_cache,$nocache) = @_;
15814: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15815: 	my $fh;
15816: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15817: 	    my @lines = <$fh>;
15818: 	    &parse_domain_tab(\@lines);
15819: 	}
15820: 	close($fh);
15821: 	$loaded = 1;
15822:     }
15823: 
15824:     sub domain {
15825: 	&load_domain_tab() if (!$loaded);
15826: 
15827: 	my ($name,$what) = @_;
15828: 	return if ( !exists($domain{$name}) );
15829: 
15830: 	if (!$what) {
15831: 	    return $domain{$name}{'description'};
15832: 	}
15833: 	return $domain{$name}{$what};
15834:     }
15835: 
15836:     sub domain_info {
15837:         &load_domain_tab() if (!$loaded);
15838:         return %domain;
15839:     }
15840: 
15841: }
15842: 
15843: 
15844: # ------------------------------------------------------------- Read hosts file
15845: {
15846:     my %hostname;
15847:     my %hostdom;
15848:     my %libserv;
15849:     my $loaded;
15850:     my %name_to_host;
15851:     my %internetdom;
15852:     my %LC_dns_serv;
15853: 
15854:     sub parse_hosts_tab {
15855: 	my ($file) = @_;
15856: 	foreach my $configline (@$file) {
15857: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15858:             chomp($configline);
15859: 	    if ($configline =~ /^\^/) {
15860:                 if ($configline =~ /^\^([\w.\-]+)/) {
15861:                     $LC_dns_serv{$1} = 1;
15862:                 }
15863:                 next;
15864:             }
15865: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15866: 	    $name=~s/\s//g;
15867: 	    if ($id && $domain && $role && $name) {
15868:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15869:                     my $curr = $hostname{$id};
15870:                     my $skip;
15871:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15872:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15873:                             $skip = 1;
15874:                         } else {
15875:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15876:                         }
15877:                     }
15878:                     unless ($skip) {
15879:                         push(@{$name_to_host{$name}},$id);
15880:                     }
15881:                 } else {
15882:                     push(@{$name_to_host{$name}},$id);
15883:                 }
15884: 		$hostname{$id}=$name;
15885: 		$hostdom{$id}=$domain;
15886: 		if ($role eq 'library') { $libserv{$id}=$name; }
15887:                 if (defined($protocol)) {
15888:                     if ($protocol eq 'https') {
15889:                         $protocol{$id} = $protocol;
15890:                     } else {
15891:                         $protocol{$id} = 'http'; 
15892:                     }
15893:                 } else {
15894:                     $protocol{$id} = 'http';
15895:                 }
15896:                 if (defined($intdom)) {
15897:                     $internetdom{$id} = $intdom;
15898:                 }
15899: 	    }
15900: 	}
15901:     }
15902:     
15903:     sub reset_hosts_info {
15904: 	&purge_remembered();
15905: 	&reset_domain_info();
15906: 	&reset_hosts_ip_info();
15907:         undef(%internetdom);
15908: 	undef(%name_to_host);
15909: 	undef(%hostname);
15910: 	undef(%hostdom);
15911: 	undef(%libserv);
15912: 	undef($loaded);
15913:     }
15914: 
15915:     sub load_hosts_tab {
15916: 	my ($ignore_cache,$nocache) = @_;
15917: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15918: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15919: 	my @config = <$config>;
15920: 	&parse_hosts_tab(\@config);
15921: 	close($config);
15922: 	$loaded=1;
15923:     }
15924: 
15925:     sub hostname {
15926: 	&load_hosts_tab() if (!$loaded);
15927: 
15928: 	my ($lonid) = @_;
15929: 	return $hostname{$lonid};
15930:     }
15931: 
15932:     sub all_hostnames {
15933: 	&load_hosts_tab() if (!$loaded);
15934: 
15935: 	return %hostname;
15936:     }
15937: 
15938:     sub all_names {
15939:         my ($ignore_cache,$nocache) = @_;
15940: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15941: 
15942: 	return %name_to_host;
15943:     }
15944: 
15945:     sub all_host_domain {
15946:         &load_hosts_tab() if (!$loaded);
15947:         return %hostdom;
15948:     }
15949: 
15950:     sub all_host_intdom {
15951:         &load_hosts_tab() if (!$loaded);
15952:         return %internetdom;
15953:     }
15954: 
15955:     sub is_library {
15956: 	&load_hosts_tab() if (!$loaded);
15957: 
15958: 	return exists($libserv{$_[0]});
15959:     }
15960: 
15961:     sub all_library {
15962: 	&load_hosts_tab() if (!$loaded);
15963: 
15964: 	return %libserv;
15965:     }
15966: 
15967:     sub unique_library {
15968: 	#2x reverse removes all hostnames that appear more than once
15969:         my %unique = reverse &all_library();
15970:         return reverse %unique;
15971:     }
15972: 
15973:     sub get_servers {
15974: 	&load_hosts_tab() if (!$loaded);
15975: 
15976: 	my ($domain,$type) = @_;
15977: 	my %possible_hosts = ($type eq 'library') ? %libserv
15978: 	                                          : %hostname;
15979: 	my %result;
15980: 	if (ref($domain) eq 'ARRAY') {
15981: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15982: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15983: 		    $result{$host} = $hostname;
15984: 		}
15985: 	    }
15986: 	} else {
15987: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15988: 		if ($hostdom{$host} eq $domain) {
15989: 		    $result{$host} = $hostname;
15990: 		}
15991: 	    }
15992: 	}
15993: 	return %result;
15994:     }
15995: 
15996:     sub get_unique_servers {
15997:         my %unique = reverse &get_servers(@_);
15998: 	return reverse %unique;
15999:     }
16000: 
16001:     sub host_domain {
16002: 	&load_hosts_tab() if (!$loaded);
16003: 
16004: 	my ($lonid) = @_;
16005: 	return $hostdom{$lonid};
16006:     }
16007: 
16008:     sub all_domains {
16009: 	&load_hosts_tab() if (!$loaded);
16010: 
16011: 	my %seen;
16012: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
16013: 	return @uniq;
16014:     }
16015: 
16016:     sub internet_dom {
16017:         &load_hosts_tab() if (!$loaded);
16018: 
16019:         my ($lonid) = @_;
16020:         return $internetdom{$lonid};
16021:     }
16022: 
16023:     sub is_LC_dns {
16024:         &load_hosts_tab() if (!$loaded);
16025: 
16026:         my ($hostname) = @_;
16027:         return exists($LC_dns_serv{$hostname});
16028:     }
16029: 
16030: }
16031: 
16032: { 
16033:     my %iphost;
16034:     my %name_to_ip;
16035:     my %lonid_to_ip;
16036: 
16037:     sub get_hosts_from_ip {
16038: 	my ($ip) = @_;
16039: 	my %iphosts = &get_iphost();
16040: 	if (ref($iphosts{$ip})) {
16041: 	    return @{$iphosts{$ip}};
16042: 	}
16043: 	return;
16044:     }
16045:     
16046:     sub reset_hosts_ip_info {
16047: 	undef(%iphost);
16048: 	undef(%name_to_ip);
16049: 	undef(%lonid_to_ip);
16050:     }
16051: 
16052:     sub get_host_ip {
16053: 	my ($lonid) = @_;
16054: 	if (exists($lonid_to_ip{$lonid})) {
16055: 	    return $lonid_to_ip{$lonid};
16056: 	}
16057: 	my $name=&hostname($lonid);
16058:    	my $ip = gethostbyname($name);
16059: 	return if (!$ip || length($ip) ne 4);
16060: 	$ip=inet_ntoa($ip);
16061: 	$name_to_ip{$name}   = $ip;
16062: 	$lonid_to_ip{$lonid} = $ip;
16063: 	return $ip;
16064:     }
16065:     
16066:     sub get_iphost {
16067: 	my ($ignore_cache,$nocache) = @_;
16068: 
16069: 	if (!$ignore_cache) {
16070: 	    if (%iphost) {
16071: 		return %iphost;
16072: 	    }
16073: 	    my ($ip_info,$cached)=
16074: 		&is_cached_new('iphost','iphost');
16075: 	    if ($cached) {
16076: 		%iphost      = %{$ip_info->[0]};
16077: 		%name_to_ip  = %{$ip_info->[1]};
16078: 		%lonid_to_ip = %{$ip_info->[2]};
16079: 		return %iphost;
16080: 	    }
16081: 	}
16082: 
16083: 	# get yesterday's info for fallback
16084: 	my %old_name_to_ip;
16085: 	my ($ip_info,$cached)=
16086: 	    &is_cached_new('iphost','iphost');
16087: 	if ($cached) {
16088: 	    %old_name_to_ip = %{$ip_info->[1]};
16089: 	}
16090: 
16091: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16092: 	foreach my $name (keys(%name_to_host)) {
16093: 	    my $ip;
16094: 	    if (!exists($name_to_ip{$name})) {
16095: 		$ip = gethostbyname($name);
16096: 		if (!$ip || length($ip) ne 4) {
16097: 		    if (defined($old_name_to_ip{$name})) {
16098: 			$ip = $old_name_to_ip{$name};
16099: 			&logthis("Can't find $name defaulting to old $ip");
16100: 		    } else {
16101: 			&logthis("Name $name no IP found");
16102: 			next;
16103: 		    }
16104: 		} else {
16105: 		    $ip=inet_ntoa($ip);
16106: 		}
16107: 		$name_to_ip{$name} = $ip;
16108: 	    } else {
16109: 		$ip = $name_to_ip{$name};
16110: 	    }
16111: 	    foreach my $id (@{ $name_to_host{$name} }) {
16112: 		$lonid_to_ip{$id} = $ip;
16113: 	    }
16114: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16115: 	}
16116:         unless ($nocache) {
16117: 	    &do_cache_new('iphost','iphost',
16118: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16119: 		          48*60*60);
16120:         }
16121: 
16122: 	return %iphost;
16123:     }
16124: 
16125:     #
16126:     #  Given a DNS returns the loncapa host name for that DNS 
16127:     # 
16128:     sub host_from_dns {
16129:         my ($dns) = @_;
16130:         my @hosts;
16131:         my $ip;
16132: 
16133:         if (exists($name_to_ip{$dns})) {
16134:             $ip = $name_to_ip{$dns};
16135:         }
16136:         if (!$ip) {
16137:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16138:             if (length($ip) == 4) { 
16139: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16140:             }
16141:         }
16142:         if ($ip) {
16143: 	    @hosts = get_hosts_from_ip($ip);
16144: 	    return $hosts[0];
16145:         }
16146:         return undef;
16147:     }
16148: 
16149:     sub get_internet_names {
16150:         my ($lonid) = @_;
16151:         return if ($lonid eq '');
16152:         my ($idnref,$cached)=
16153:             &is_cached_new('internetnames',$lonid);
16154:         if ($cached) {
16155:             return $idnref;
16156:         }
16157:         my $ip = &get_host_ip($lonid);
16158:         my @hosts = &get_hosts_from_ip($ip);
16159:         my %iphost = &get_iphost();
16160:         my (@idns,%seen);
16161:         foreach my $id (@hosts) {
16162:             my $dom = &host_domain($id);
16163:             my $prim_id = &domain($dom,'primary');
16164:             my $prim_ip = &get_host_ip($prim_id);
16165:             next if ($seen{$prim_ip});
16166:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16167:                 foreach my $id (@{$iphost{$prim_ip}}) {
16168:                     my $intdom = &internet_dom($id);
16169:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16170:                         push(@idns,$intdom);
16171:                     }
16172:                 }
16173:             }
16174:             $seen{$prim_ip} = 1;
16175:         }
16176:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16177:     }
16178: 
16179: }
16180: 
16181: sub all_loncaparevs {
16182:     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);
16183: }
16184: 
16185: # ---------------------------------------------------------- Read loncaparev table
16186: {
16187:     sub load_loncaparevs { 
16188:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16189:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16190:                 while (my $configline=<$config>) {
16191:                     chomp($configline);
16192:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16193:                     $loncaparevs{$hostid}=$loncaparev;
16194:                 }
16195:                 close($config);
16196:             }
16197:         }
16198:     }
16199: }
16200: 
16201: # ---------------------------------------------------------- Read serverhostID table
16202: {
16203:     sub load_serverhomeIDs {
16204:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16205:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16206:                 while (my $configline=<$config>) {
16207:                     chomp($configline);
16208:                     my ($name,$id)=split(/:/,$configline);
16209:                     $serverhomeIDs{$name}=$id;
16210:                 }
16211:                 close($config);
16212:             }
16213:         }
16214:     }
16215: }
16216: 
16217: 
16218: BEGIN {
16219: 
16220: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16221:     unless ($readit) {
16222: {
16223:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16224:     %perlvar = (%perlvar,%{$configvars});
16225: }
16226: 
16227: 
16228: # ------------------------------------------------------ Read spare server file
16229: {
16230:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16231: 
16232:     while (my $configline=<$config>) {
16233:        chomp($configline);
16234:        if ($configline) {
16235: 	   my ($host,$type) = split(':',$configline,2);
16236: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16237: 	   push(@{ $spareid{$type} }, $host);
16238:        }
16239:     }
16240:     close($config);
16241: }
16242: # ------------------------------------------------------------ Read permissions
16243: {
16244:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16245: 
16246:     while (my $configline=<$config>) {
16247: 	chomp($configline);
16248: 	if ($configline) {
16249: 	    my ($role,$perm)=split(/ /,$configline);
16250: 	    if ($perm ne '') { $pr{$role}=$perm; }
16251: 	}
16252:     }
16253:     close($config);
16254: }
16255: 
16256: # -------------------------------------------- Read plain texts for permissions
16257: {
16258:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16259: 
16260:     while (my $configline=<$config>) {
16261: 	chomp($configline);
16262: 	if ($configline) {
16263: 	    my ($short,@plain)=split(/:/,$configline);
16264:             %{$prp{$short}} = ();
16265: 	    if (@plain > 0) {
16266:                 $prp{$short}{'std'} = $plain[0];
16267:                 for (my $i=1; $i<@plain; $i++) {
16268:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16269:                 }
16270:             }
16271: 	}
16272:     }
16273:     close($config);
16274: }
16275: 
16276: # ---------------------------------------------------------- Read package table
16277: {
16278:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16279: 
16280:     while (my $configline=<$config>) {
16281: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16282: 	chomp($configline);
16283: 	my ($short,$plain)=split(/:/,$configline);
16284: 	my ($pack,$name)=split(/\&/,$short);
16285: 	if ($plain ne '') {
16286: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16287: 	    $packagetab{$short}=$plain; 
16288: 	}
16289:     }
16290:     close($config);
16291: }
16292: 
16293: # ---------------------------------------------------------- Read loncaparev table
16294: 
16295: &load_loncaparevs();
16296: 
16297: # ---------------------------------------------------------- Read serverhostID table
16298: 
16299: &load_serverhomeIDs();
16300: 
16301: # ---------------------------------------------------------- Read releaseslist XML
16302: {
16303:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16304:     if (-e $file) {
16305:         my $parser = HTML::LCParser->new($file);
16306:         while (my $token = $parser->get_token()) {
16307:             if ($token->[0] eq 'S') {
16308:                 my $item = $token->[1];
16309:                 my $name = $token->[2]{'name'};
16310:                 my $value = $token->[2]{'value'};
16311:                 my $valuematch = $token->[2]{'valuematch'};
16312:                 my $namematch = $token->[2]{'namematch'};
16313:                 if ($item eq 'parameter') {
16314:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16315:                         my $release = $parser->get_text();
16316:                         $release =~ s/(^\s*|\s*$ )//gx;
16317:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16318:                     }
16319:                 } elsif ($item ne '' && $name ne '') {
16320:                     my $release = $parser->get_text();
16321:                     $release =~ s/(^\s*|\s*$ )//gx;
16322:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16323:                 }
16324:             }
16325:         }
16326:     }
16327: }
16328: 
16329: # ---------------------------------------------------------- Read managers table
16330: {
16331:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16332:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16333:             while (my $configline=<$config>) {
16334:                 chomp($configline);
16335:                 next if ($configline =~ /^\#/);
16336:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16337:                     $managerstab{$configline} = 1;
16338:                 }
16339:             }
16340:             close($config);
16341:         }
16342:     }
16343: }
16344: 
16345: # ------------- set up temporary directory
16346: {
16347:     $tmpdir = LONCAPA::tempdir();
16348: 
16349: }
16350: 
16351: # ------------- set default texengine (domain default overrides this)
16352: {
16353:     $deftex = LONCAPA::texengine();
16354: }
16355: 
16356: # ------------- set default minimum length for passwords for internal auth users
16357: {
16358:     $passwdmin = LONCAPA::passwd_min();
16359: }
16360: 
16361: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16362: 				'compress_threshold'=> 20_000,
16363:  			        });
16364: 
16365: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16366: $dumpcount=0;
16367: $locknum=0;
16368: 
16369: &logtouch();
16370: &logthis('<font color="yellow">INFO: Read configuration</font>');
16371: $readit=1;
16372:     {
16373: 	use integer;
16374: 	my $test=(2**32)+1;
16375: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16376: 	&logthis(" Detected 64bit platform ($_64bit)");
16377:     }
16378: }
16379: }
16380: 
16381: 1;
16382: __END__
16383: 
16384: =pod
16385: 
16386: =head1 NAME
16387: 
16388: Apache::lonnet - Subroutines to ask questions about things in the network.
16389: 
16390: =head1 SYNOPSIS
16391: 
16392: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16393: 
16394:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16395: 
16396: Common parameters:
16397: 
16398: =over 4
16399: 
16400: =item *
16401: 
16402: $uname : an internal username (if $cname expecting a course Id specifically)
16403: 
16404: =item *
16405: 
16406: $udom : a domain (if $cdom expecting a course's domain specifically)
16407: 
16408: =item *
16409: 
16410: $symb : a resource instance identifier
16411: 
16412: =item *
16413: 
16414: $namespace : the name of a .db file that contains the data needed or
16415: being set.
16416: 
16417: =back
16418: 
16419: =head1 OVERVIEW
16420: 
16421: lonnet provides subroutines which interact with the
16422: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16423: about classes, users, and resources.
16424: 
16425: For many of these objects you can also use this to store data about
16426: them or modify them in various ways.
16427: 
16428: =head2 Symbs
16429: 
16430: To identify a specific instance of a resource, LON-CAPA uses symbols
16431: or "symbs"X<symb>. These identifiers are built from the URL of the
16432: map, the resource number of the resource in the map, and the URL of
16433: the resource itself. The latter is somewhat redundant, but might help
16434: if maps change.
16435: 
16436: An example is
16437: 
16438:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16439: 
16440: The respective map entry is
16441: 
16442:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16443:   title="Problem 2">
16444:  </resource>
16445: 
16446: Symbs are used by the random number generator, as well as to store and
16447: restore data specific to a certain instance of for example a problem.
16448: 
16449: =head2 Storing And Retrieving Data
16450: 
16451: X<store()>X<cstore()>X<restore()>Three of the most important functions
16452: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16453: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16454: is is the non-critical message twin of cstore. These functions are for
16455: handlers to store a perl hash to a user's permanent data space in an
16456: easy manner, and to retrieve it again on another call. It is expected
16457: that a handler would use this once at the beginning to retrieve data,
16458: and then again once at the end to send only the new data back.
16459: 
16460: The data is stored in the user's data directory on the user's
16461: homeserver under the ID of the course.
16462: 
16463: The hash that is returned by restore will have all of the previous
16464: value for all of the elements of the hash.
16465: 
16466: Example:
16467: 
16468:  #creating a hash
16469:  my %hash;
16470:  $hash{'foo'}='bar';
16471: 
16472:  #storing it
16473:  &Apache::lonnet::cstore(\%hash);
16474: 
16475:  #changing a value
16476:  $hash{'foo'}='notbar';
16477: 
16478:  #adding a new value
16479:  $hash{'bar'}='foo';
16480:  &Apache::lonnet::cstore(\%hash);
16481: 
16482:  #retrieving the hash
16483:  my %history=&Apache::lonnet::restore();
16484: 
16485:  #print the hash
16486:  foreach my $key (sort(keys(%history))) {
16487:    print("\%history{$key} = $history{$key}");
16488:  }
16489: 
16490: Will print out:
16491: 
16492:  %history{1:foo} = bar
16493:  %history{1:keys} = foo:timestamp
16494:  %history{1:timestamp} = 990455579
16495:  %history{2:bar} = foo
16496:  %history{2:foo} = notbar
16497:  %history{2:keys} = foo:bar:timestamp
16498:  %history{2:timestamp} = 990455580
16499:  %history{bar} = foo
16500:  %history{foo} = notbar
16501:  %history{timestamp} = 990455580
16502:  %history{version} = 2
16503: 
16504: Note that the special hash entries C<keys>, C<version> and
16505: C<timestamp> were added to the hash. C<version> will be equal to the
16506: total number of versions of the data that have been stored. The
16507: C<timestamp> attribute will be the UNIX time the hash was
16508: stored. C<keys> is available in every historical section to list which
16509: keys were added or changed at a specific historical revision of a
16510: hash.
16511: 
16512: B<Warning>: do not store the hash that restore returns directly. This
16513: will cause a mess since it will restore the historical keys as if the
16514: were new keys. I.E. 1:foo will become 1:1:foo etc.
16515: 
16516: Calling convention:
16517: 
16518:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16519:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16520: 
16521: For more detailed information, see lonnet specific documentation.
16522: 
16523: =head1 RETURN MESSAGES
16524: 
16525: =over 4
16526: 
16527: =item * B<con_lost>: unable to contact remote host
16528: 
16529: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16530: when the connection is brought back up
16531: 
16532: =item * B<con_failed>: unable to contact remote host and unable to save message
16533: for later delivery
16534: 
16535: =item * B<error:>: an error a occurred, a description of the error follows the :
16536: 
16537: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16538: that was requested
16539: 
16540: =back
16541: 
16542: =head1 PUBLIC SUBROUTINES
16543: 
16544: =head2 Session Environment Functions
16545: 
16546: =over 4
16547: 
16548: =item * 
16549: X<appenv()>
16550: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16551: the user envirnoment file, and will be restored for each access this
16552: user makes during this session, also modifies the %env for the current
16553: process. Optional rolesarrayref - if defined contains a reference to an array
16554: of roles which are exempt from the restriction on modifying user.role entries 
16555: in the user's environment.db and in %env.    
16556: 
16557: =item *
16558: X<delenv()>
16559: B<delenv($delthis,$regexp)>: removes all items from the session
16560: environment file that begin with $delthis. If the 
16561: optional second arg - $regexp - is true, $delthis is treated as a 
16562: regular expression, otherwise \Q$delthis\E is used. 
16563: The values are also deleted from the current processes %env.
16564: 
16565: =item * get_env_multiple($name) 
16566: 
16567: gets $name from the %env hash, it seemlessly handles the cases where multiple
16568: values may be defined and end up as an array ref.
16569: 
16570: returns an array of values
16571: 
16572: =back
16573: 
16574: =head2 User Information
16575: 
16576: =over 4
16577: 
16578: =item *
16579: X<queryauthenticate()>
16580: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16581: authentication scheme
16582: 
16583: =item *
16584: X<authenticate()>
16585: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16586: authenticate user from domain's lib servers (first use the current
16587: one). C<$upass> should be the users password.
16588: $checkdefauth is optional (value is 1 if a check should be made to
16589:    authenticate user using default authentication method, and allow
16590:    account creation if username does not have account in the domain).
16591: $clientcancheckhost is optional (value is 1 if checking whether the
16592:    server can host will occur on the client side in lonauth.pm).   
16593: 
16594: =item *
16595: X<homeserver()>
16596: B<homeserver($uname,$udom)>: find the server which has
16597: the user's directory and files (there must be only one), this caches
16598: the answer, and also caches if there is a borken connection.
16599: 
16600: =item *
16601: X<idget()>
16602: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16603: a list of student/employee IDs or clicker IDs
16604: (student/employee IDs are a unique resource in a domain, there must be 
16605: only 1 ID per username, and only 1 username per ID in a specific domain).
16606: clickerIDs are not necessarily unique, as students might share clickers.
16607: (returns hash: id=>name,id=>name)
16608: 
16609: =item *
16610: X<idrget()>
16611: B<idrget($udom,@unames)>: find the IDs behind a list of
16612: usernames (returns hash: name=>id,name=>id)
16613: 
16614: =item *
16615: X<idput()>
16616: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16617: names and associated student/employee IDs or clicker IDs.
16618: 
16619: =item *
16620: X<iddel()>
16621: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16622: student/employee ID or clicker ID username look-ups from domain.
16623: The homeserver ($uhome) and namespace ($namespace) are optional.
16624: If no $uhome is provided, it will be determined usig &homeserver()
16625: for each user.  If no $namespace is provided, the default is ids.
16626: 
16627: =item *
16628: X<updateclickers()>
16629: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16630: clicker ID-to-username look-ups in clickers.db on library server.
16631: Permitted actions are add or del (i.e., add or delete). The 
16632: clickers.db contains clickerID as keys (escaped), and each corresponding
16633: value is an escaped comma-separated list of usernames (for whom the
16634: library server is the homeserver), who registered that particular ID.
16635: If $critical is true, the update will be sent via &critical, otherwise
16636: &reply() will be used.
16637: 
16638: =item *
16639: X<rolesinit()>
16640: B<rolesinit($udom,$username)>: get user privileges.
16641: returns user role, first access and timer interval hashes
16642: 
16643: =item *
16644: X<privileged()>
16645: B<privileged($username,$domain)>: returns a true if user has a
16646: privileged and active role (i.e. su or dc), false otherwise.
16647: 
16648: =item *
16649: X<getsection()>
16650: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16651: course $cname, return section name/number or '' for "not in course"
16652: and '-1' for "no section"
16653: 
16654: =item *
16655: X<userenvironment()>
16656: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16657: passed in @what from the requested user's environment, returns a hash
16658: 
16659: =item * 
16660: X<userlog_query()>
16661: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16662: activity.log file. %filters defines filters applied when parsing the
16663: log file. These can be start or end timestamps, or the type of action
16664: - log to look for Login or Logout events, check for Checkin or
16665: Checkout, role for role selection. The response is in the form
16666: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16667: escaped strings of the action recorded in the activity.log file.
16668: 
16669: =back
16670: 
16671: =head2 User Roles
16672: 
16673: =over 4
16674: 
16675: =item *
16676: 
16677: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16678: returns codes for allowed actions.
16679: 
16680: The first argument is required, all others are optional.
16681: 
16682: $priv is the privilege being checked.
16683: $uri contains additional information about what is being checked for access (e.g.,
16684: URL, course ID etc.). 
16685: $symb is the unique resource instance identifier in a course; if needed,
16686: but not provided, it will be retrieved via a call to &symbread(). 
16687: $role is the role for which a priv is being checked (only used if priv is evb). 
16688: $clientip is the user's IP address (only used when checking for access to portfolio 
16689: files).
16690: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16691: prevents recursive calls to &allowed.
16692: 
16693:  F: full access
16694:  U,I,K: authentication modes (cxx only)
16695:  '': forbidden
16696:  1: user needs to choose course
16697:  2: browse allowed
16698:  A: passphrase authentication needed
16699:  B: access temporarily blocked because of a blocking event in a course.
16700:  D: access blocked because access is required via session initiated via deep-link 
16701: 
16702: =item *
16703: 
16704: constructaccess($url,$setpriv) : check for access to construction space URL
16705: 
16706: See if the owner domain and name in the URL match those in the
16707: expected environment.  If so, return three element list
16708: ($ownername,$ownerdomain,$ownerhome).
16709: 
16710: Otherwise return the null string.
16711: 
16712: If second argument 'setpriv' is true, it assigns the privileges,
16713: and returns the same three element list, unless the owner has
16714: blocked "ad hoc" Domain Coordinator access to the Author Space,
16715: in which case the null string is returned.
16716: 
16717: =item *
16718: 
16719: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16720: define a custom role rolename set privileges in format of lonTabs/roles.tab
16721: for system, domain, and course level. $uname and $udom are optional (current
16722: user's username and domain will be used when either of $uname or $udom are absent.
16723: 
16724: =item *
16725: 
16726: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16727: (rolesplain.tab); plain text explanation of a user role term.
16728: $type is Course (default) or Community.
16729: If $forcedefault evaluates to true, text returned will be default 
16730: text for $type. Otherwise, if this is a course, the text returned 
16731: will be a custom name for the role (if defined in the course's 
16732: environment).  If no custom name is defined the default is returned.
16733:    
16734: =item *
16735: 
16736: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16737: All arguments are optional. Returns a hash of a roles, either for
16738: co-author/assistant author roles for a user's Construction Space
16739: (default), or if $context is 'userroles', roles for the user himself,
16740: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16741: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16742: For each key, value is set to colon-separated start and end times for
16743: the role.  If no username and domain are specified, will default to
16744: current user/domain. Types, roles, and roledoms are references to arrays
16745: of role statuses (active, future or previous), roles 
16746: (e.g., cc,in, st etc.) and domains of the roles which can be used
16747: to restrict the list of roles reported. If no array ref is 
16748: provided for types, will default to return only active roles.
16749: 
16750: =item *
16751: 
16752: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16753: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16754: 
16755: Additional optional arguments are: $type (if role checking is to be restricted 
16756: to certain user status types -- previous (expired roles), active (currently
16757: available roles) or future (roles available in the future), and
16758: $hideprivileged -- if true will not report course roles for users who
16759: have active Domain Coordinator role in course's domain or in additional
16760: domains (specified in 'Domains to check for privileged users' in course
16761: environment -- set via:  Course Settings -> Classlists and staff listing).
16762: 
16763: =item *
16764: 
16765: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16766: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16767: $possdomains and $possroles are optional array refs -- to domains to check and
16768: roles to check.  If $possdomains is not specified, a dump will be done of the
16769: users' roles.db to check for a dc or su role in any domain. This can be
16770: time consuming if &privileged is called repeatedly (e.g., when displaying a
16771: classlist), so in such cases, supplying a $possdomains array is preferred, as
16772: this then allows &privileged_by_domain() to be used, which caches the identity
16773: of privileged users, eliminating the need for repeated calls to &dump().
16774: 
16775: =item *
16776: 
16777: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16778: where the outer hash keys are domains specified in the $possdomains array ref,
16779: next inner hash keys are privileged roles specified in the $roles array ref,
16780: and the innermost hash contains key = value pairs for username:domain = end:start
16781: for active or future "privileged" users with that role in that domain. To avoid
16782: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16783: innerhash are cached using priv_$role and $dom as the identifiers.
16784: 
16785: =back
16786: 
16787: =head2 User Modification
16788: 
16789: =over 4
16790: 
16791: =item *
16792: 
16793: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16794: user for the level given by URL.  Optional start and end dates (leave empty
16795: string or zero for "no date")
16796: 
16797: =item *
16798: 
16799: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16800: change a users, password, possible return values are: ok,
16801: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16802: refused
16803: 
16804: =item *
16805: 
16806: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16807: 
16808: =item *
16809: 
16810: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16811:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16812: 
16813: will update user information (firstname,middlename,lastname,generation,
16814: permanentemail), and if forceid is true, student/employee ID also.
16815: A user's institutional affiliation(s) can also be updated.
16816: User information fields will not be overwritten with empty entries 
16817: unless the field is included in the $candelete array reference.
16818: This array is included when a single user is modified via "Manage Users",
16819: or when Autoupdate.pl is run by cron in a domain.
16820: 
16821: =item *
16822: 
16823: modifystudent
16824: 
16825: modify a student's enrollment and identification information.
16826: The course id is resolved based on the current user's environment.  
16827: This means the invoking user must be a course coordinator or otherwise
16828: associated with a course.
16829: 
16830: This call is essentially a wrapper for lonnet::modifyuser and
16831: lonnet::modify_student_enrollment
16832: 
16833: Inputs: 
16834: 
16835: =over 4
16836: 
16837: =item B<$udom> Student's loncapa domain
16838: 
16839: =item B<$uname> Student's loncapa login name
16840: 
16841: =item B<$uid> Student/Employee ID
16842: 
16843: =item B<$umode> Student's authentication mode
16844: 
16845: =item B<$upass> Student's password
16846: 
16847: =item B<$first> Student's first name
16848: 
16849: =item B<$middle> Student's middle name
16850: 
16851: =item B<$last> Student's last name
16852: 
16853: =item B<$gene> Student's generation
16854: 
16855: =item B<$usec> Student's section in course
16856: 
16857: =item B<$end> Unix time of the roles expiration
16858: 
16859: =item B<$start> Unix time of the roles start date
16860: 
16861: =item B<$forceid> If defined, allow $uid to be changed
16862: 
16863: =item B<$desiredhome> server to use as home server for student
16864: 
16865: =item B<$email> Student's permanent e-mail address
16866: 
16867: =item B<$type> Type of enrollment (auto or manual)
16868: 
16869: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16870: 
16871: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16872: 
16873: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16874: 
16875: =item B<$context> role change context (shown in User Management Logs display in a course)
16876: 
16877: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16878: 
16879: =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.
16880: 
16881: =back
16882: 
16883: =item *
16884: 
16885: modify_student_enrollment
16886: 
16887: Change a student's enrollment status in a class.  The environment variable
16888: 'role.request.course' must be defined for this function to proceed.
16889: 
16890: Inputs:
16891: 
16892: =over 4
16893: 
16894: =item $udom, student's domain
16895: 
16896: =item $uname, student's name
16897: 
16898: =item $uid, student's user id
16899: 
16900: =item $first, student's first name
16901: 
16902: =item $middle
16903: 
16904: =item $last
16905: 
16906: =item $gene
16907: 
16908: =item $usec
16909: 
16910: =item $end
16911: 
16912: =item $start
16913: 
16914: =item $type
16915: 
16916: =item $locktype
16917: 
16918: =item $cid
16919: 
16920: =item $selfenroll
16921: 
16922: =item $context
16923: 
16924: =item $credits, number of credits student will earn from this class
16925: 
16926: =item $instsec, institutional course section code for student
16927: 
16928: =back
16929: 
16930: 
16931: =item *
16932: 
16933: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16934: custom role; give a custom role to a user for the level given by URL.  Specify
16935: name and domain of role author, and role name
16936: 
16937: =item *
16938: 
16939: revokerole($udom,$uname,$url,$role) : revoke a role for url
16940: 
16941: =item *
16942: 
16943: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16944: 
16945: =back
16946: 
16947: =head2 Course Infomation
16948: 
16949: =over 4
16950: 
16951: =item *
16952: 
16953: coursedescription($courseid,$options) : returns a hash of information about the
16954: specified course id, including all environment settings for the
16955: course, the description of the course will be in the hash under the
16956: key 'description'
16957: 
16958: $options is an optional parameter that if supplied is a hash reference that controls
16959: what how this function works.  It has the following key/values:
16960: 
16961: =over 4
16962: 
16963: =item freshen_cache
16964: 
16965: If defined, and the environment cache for the course is valid, it is 
16966: returned in the returned hash.
16967: 
16968: =item one_time
16969: 
16970: If defined, the last cache time is set to _now_
16971: 
16972: =item user
16973: 
16974: If defined, the supplied username is used instead of the current user.
16975: 
16976: 
16977: =back
16978: 
16979: =item *
16980: 
16981: resdata($name,$domain,$type,@which) : request for current parameter
16982: setting for a specific $type, where $type is either 'course' or 'user',
16983: @what should be a list of parameters to ask about. This routine caches
16984: answers for 10 minutes.
16985: 
16986: =item *
16987: 
16988: get_courseresdata($courseid, $domain) : dump the entire course resource
16989: data base, returning a hash that is keyed by the resource name and has
16990: values that are the resource value.  I believe that the timestamps and
16991: versions are also returned.
16992: 
16993: =back
16994: 
16995: =head2 Course Modification
16996: 
16997: =over 4
16998: 
16999: =item *
17000: 
17001: writecoursepref($courseid,%prefs) : write preferences (environment
17002: database) for a course
17003: 
17004: =item *
17005: 
17006: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17007: 
17008: =item *
17009: 
17010: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
17011: 
17012: =item *
17013: 
17014: is_course($courseid), is_course($cdom, $cnum)
17015: 
17016: Accepts either a combined $courseid (in the form of domain_courseid) or the
17017: two component version $cdom, $cnum. It checks if the specified course exists.
17018: 
17019: Returns:
17020:     undef if the course doesn't exist, otherwise
17021:     in scalar context the combined courseid.
17022:     in list context the two components of the course identifier, domain and 
17023:     courseid.    
17024: 
17025: =back
17026: 
17027: =head2 Bubblesheet Configuration
17028: 
17029: =over 4
17030: 
17031: =item *
17032: 
17033: get_scantron_config($which)
17034: 
17035: $which - the name of the configuration to parse from the file.
17036: 
17037: Parses and returns the bubblesheet configuration line selected as a
17038: hash of configuration file fields.
17039: 
17040: 
17041: Returns:
17042:     If the named configuration is not in the file, an empty
17043:     hash is returned.
17044: 
17045:     a hash with the fields
17046:       name         - internal name for the this configuration setup
17047:       description  - text to display to operator that describes this config
17048:       CODElocation - if 0 or the string 'none'
17049:                           - no CODE exists for this config
17050:                      if -1 || the string 'letter'
17051:                           - a CODE exists for this config and is
17052:                             a string of letters
17053:                      Unsupported value (but planned for future support)
17054:                           if a positive integer
17055:                                - The CODE exists as the first n items from
17056:                                  the question section of the form
17057:                           if the string 'number'
17058:                                - The CODE exists for this config and is
17059:                                  a string of numbers
17060:       CODEstart   - (only matter if a CODE exists) column in the line where
17061:                      the CODE starts
17062:       CODElength  - length of the CODE
17063:       IDstart     - column where the student/employee ID starts
17064:       IDlength    - length of the student/employee ID info
17065:       Qstart      - column where the information from the bubbled
17066:                     'questions' start
17067:       Qlength     - number of columns comprising a single bubble line from
17068:                     the sheet. (usually either 1 or 10)
17069:       Qon         - either a single character representing the character used
17070:                     to signal a bubble was chosen in the positional setup, or
17071:                     the string 'letter' if the letter of the chosen bubble is
17072:                     in the final, or 'number' if a number representing the
17073:                     chosen bubble is in the file (1->A 0->J)
17074:       Qoff        - the character used to represent that a bubble was
17075:                     left blank
17076:       PaperID     - if the scanning process generates a unique number for each
17077:                     sheet scanned the column that this ID number starts in
17078:       PaperIDlength - number of columns that comprise the unique ID number
17079:                       for the sheet of paper
17080:       FirstName   - column that the first name starts in
17081:       FirstNameLength - number of columns that the first name spans
17082:       LastName    - column that the last name starts in
17083:       LastNameLength - number of columns that the last name spans
17084:       BubblesPerRow - number of bubbles available in each row used to
17085:                       bubble an answer. (If not specified, 10 assumed).
17086: 
17087: 
17088: =item *
17089: 
17090: get_scantronformat_file($cdom)
17091: 
17092: $cdom - the course's domain (optional); if not supplied, uses
17093: domain for current $env{'request.course.id'}.
17094: 
17095: Returns an array containing lines from the scantron format file for
17096: the domain of the course.
17097: 
17098: If a url for a custom.tab file is listed in domain's configuration.db,
17099: lines are from this file.
17100: 
17101: Otherwise, if a default.tab has been published in RES space by the
17102: domainconfig user, lines are from this file.
17103: 
17104: Otherwise, fall back to getting lines from the legacy file on the
17105: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17106: 
17107: =back
17108: 
17109: =head2 Resource Subroutines
17110: 
17111: =over 4
17112: 
17113: =item *
17114: 
17115: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17116: 
17117: =item *
17118: 
17119: repcopy($filename) : subscribes to the requested file, and attempts to
17120: replicate from the owning library server, Might return
17121: 'unavailable', 'not_found', 'forbidden', 'ok', or
17122: 'bad_request', also attempts to grab the metadata for the
17123: resource. Expects the local filesystem pathname
17124: (/home/httpd/html/res/....)
17125: 
17126: =back
17127: 
17128: =head2 Resource Information
17129: 
17130: =over 4
17131: 
17132: =item *
17133: 
17134: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17135: and returns the value of a variety of different possible values,
17136: $varname should be a request string, and the other parameters can be
17137: used to specify who and what one is asking about. Ordinarily, $cid 
17138: does not need to be specified, as it is retrived from 
17139: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17140: within lonuserstate::loadmap() when initializing a course, before
17141: $env{'request.course.id'} has been set, so it needs to be provided
17142: in that one case.
17143: 
17144: Possible values for $varname are environment.lastname (or other item
17145: from the envirnment hash), user.name (or someother aspect about the
17146: user), resource.0.maxtries (or some other part and parameter of a
17147: resource)
17148: 
17149: =item *
17150: 
17151: directcondval($number) : get current value of a condition; reads from a state
17152: string
17153: 
17154: =item *
17155: 
17156: condval($condidx) : value of condition index based on state
17157: 
17158: =item *
17159: 
17160: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17161: resource's metadata, $what should be either a specific key, or either
17162: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17163: packages that this resource currently uses, the last 3 arguments are 
17164: only used internally for recursive metadata.
17165: 
17166: the toolsymb is only used where the uri is for an external tool (for which
17167: the uri as well as the symb are guaranteed to be unique).
17168: 
17169: this function automatically caches all requests except any made recursively
17170: to retrieve a list of metadata keys for an imported library file ($liburi is 
17171: defined).
17172: 
17173: =item *
17174: 
17175: metadata_query($query,$custom,$customshow) : make a metadata query against the
17176: network of library servers; returns file handle of where SQL and regex results
17177: will be stored for query
17178: 
17179: =item *
17180: 
17181: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17182: return symbolic list entry (all arguments optional). 
17183: 
17184: Args: filename is the filename (including path) for the file for which a symb 
17185: is required; donotrecurse, if true will prevent calls to allowed() being made 
17186: to check access status if more than one resource was found in the bighash 
17187: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17188: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17189: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17190: cause possible symbs to be checked to determine if they are subject to content
17191: blocking, if so they will not be included as possible symbs; possibles is a
17192: ref to a hash, which, as a side effect, will be populated with all possible 
17193: symbs (content blocking not tested).
17194:  
17195: returns the data handle
17196: 
17197: =item *
17198: 
17199: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17200: and is a possible symb for the URL in $thisfn, and if is an encrypted
17201: resource that the user accessed using /enc/ returns a 1 on success, 0
17202: on failure, user must be in a course, as it assumes the existence of
17203: the course initial hash, and uses $env('request.course.id'}.  The third
17204: arg is an optional reference to a scalar.  If this arg is passed in the 
17205: call to symbverify, it will be set to 1 if the symb has been set to be 
17206: encrypted; otherwise it will be null.  
17207: 
17208: =item *
17209: 
17210: symbclean($symb) : removes versions numbers from a symb, returns the
17211: cleaned symb
17212: 
17213: =item *
17214: 
17215: is_on_map($uri) : checks if the $uri is somewhere on the current
17216: course map, user must be in a course for it to work.
17217: 
17218: =item *
17219: 
17220: numval($salt) : return random seed value (addend for rndseed)
17221: 
17222: =item *
17223: 
17224: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17225: a random seed, all arguments are optional, if they aren't sent it uses the
17226: environment to derive them. Note: if symb isn't sent and it can't get one
17227: from &symbread it will use the current time as its return value
17228: 
17229: =item *
17230: 
17231: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17232: unfakeable, receipt
17233: 
17234: =item *
17235: 
17236: receipt() : API to ireceipt working off of env values; given out to users
17237: 
17238: =item *
17239: 
17240: countacc($url) : count the number of accesses to a given URL
17241: 
17242: =item *
17243: 
17244: 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
17245: 
17246: =item *
17247: 
17248: 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)
17249: 
17250: =item *
17251: 
17252: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17253: 
17254: =item *
17255: 
17256: devalidate($symb) : devalidate temporary spreadsheet calculations,
17257: forcing spreadsheet to reevaluate the resource scores next time.
17258: 
17259: =item * 
17260: 
17261: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17262: when viewing in course context.
17263: 
17264:  input: six args -- filename (decluttered), course number, course domain,
17265:                     url, symb (if registered) and group (if this is a 
17266:                     group item -- e.g., bulletin board, group page etc.).
17267: 
17268:  output: array of five scalars --
17269:          $cfile -- url for file editing if editable on current server
17270:          $home -- homeserver of resource (i.e., for author if published,
17271:                                           or course if uploaded.).
17272:          $switchserver --  1 if server switch will be needed.
17273:          $forceedit -- 1 if icon/link should be to go to edit mode 
17274:          $forceview -- 1 if icon/link should be to go to view mode
17275: 
17276: =item *
17277: 
17278: is_course_upload($file,$cnum,$cdom)
17279: 
17280: Used in course context to determine if current file was uploaded to 
17281: the course (i.e., would be found in /userfiles/docs on the course's 
17282: homeserver.
17283: 
17284:   input: 3 args -- filename (decluttered), course number and course domain.
17285:   output: boolean -- 1 if file was uploaded.
17286: 
17287: =back
17288: 
17289: =head2 Storing/Retreiving Data
17290: 
17291: =over 4
17292: 
17293: =item *
17294: 
17295: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17296: permanently for this url; hashref needs to be given and should be a \%hashname;
17297: the remaining args aren't required and if they aren't passed or are '' they will
17298: be derived from the env (with the exception of $laststore, which is an 
17299: optional arg used when a user's submission is stored in grading).
17300: $laststore is $version=$timestamp, where $version is the most recent version
17301: number retrieved for the corresponding $symb in the $namespace db file, and
17302: $timestamp is the timestamp for that transaction (UNIX time).
17303: $laststore is currently only passed when cstore() is called by 
17304: structuretags::finalize_storage().
17305: 
17306: =item *
17307: 
17308: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17309: but uses critical subroutine
17310: 
17311: =item *
17312: 
17313: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17314: all args are optional
17315: 
17316: =item *
17317: 
17318: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17319: dumps the complete (or key matching regexp) namespace into a hash
17320: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17321: normally &store()ed into
17322: 
17323: $range should be either an integer '100' (give me the first 100
17324:                                            matching records)
17325:               or be  two integers sperated by a - with no spaces
17326:                  '30-50' (give me the 30th through the 50th matching
17327:                           records)
17328: 
17329: 
17330: =item *
17331: 
17332: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17333: replaces a &store() version of data with a replacement set of data
17334: for a particular resource in a namespace passed in the $storehash hash 
17335: reference. If $tolog is true, the transaction is logged in the courselog
17336: with an action=PUTSTORE.
17337: 
17338: =item *
17339: 
17340: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17341: works very similar to store/cstore, but all data is stored in a
17342: temporary location and can be reset using tmpreset, $storehash should
17343: be a hash reference, returns nothing on success
17344: 
17345: =item *
17346: 
17347: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17348: similar to restore, but all data is stored in a temporary location and
17349: can be reset using tmpreset. Returns a hash of values on success,
17350: error string otherwise.
17351: 
17352: =item *
17353: 
17354: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17355: deltes all keys for $symb form the temporary storage hash.
17356: 
17357: =item *
17358: 
17359: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17360: reference filled in from namesp ($udom and $uname are optional)
17361: 
17362: =item *
17363: 
17364: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17365: namesp ($udom and $uname are optional)
17366: 
17367: =item *
17368: 
17369: dump($namespace,$udom,$uname,$regexp,$range) : 
17370: dumps the complete (or key matching regexp) namespace into a hash
17371: ($udom, $uname, $regexp, $range are optional)
17372: 
17373: $range should be either an integer '100' (give me the first 100
17374:                                            matching records)
17375:               or be  two integers sperated by a - with no spaces
17376:                  '30-50' (give me the 30th through the 50th matching
17377:                           records)
17378: =item *
17379: 
17380: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17381: $store can be a scalar, an array reference, or if the amount to be 
17382: incremented is > 1, a hash reference.
17383: 
17384: ($udom and $uname are optional)
17385: 
17386: =item *
17387: 
17388: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17389: ($udom and $uname are optional)
17390: 
17391: =item *
17392: 
17393: cput($namespace,$storehash,$udom,$uname) : critical put
17394: ($udom and $uname are optional)
17395: 
17396: =item *
17397: 
17398: newput($namespace,$storehash,$udom,$uname) :
17399: 
17400: Attempts to store the items in the $storehash, but only if they don't
17401: currently exist, if this succeeds you can be certain that you have 
17402: successfully created a new key value pair in the $namespace db.
17403: 
17404: 
17405: Args:
17406:  $namespace: name of database to store values to
17407:  $storehash: hashref to store to the db
17408:  $udom: (optional) domain of user containing the db
17409:  $uname: (optional) name of user caontaining the db
17410: 
17411: Returns:
17412:  'ok' -> succeeded in storing all keys of $storehash
17413:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17414:                         least <key> already existed in the db (other
17415:                         requested keys may also already exist)
17416:  'error: <msg>' -> unable to tie the DB or other error occurred
17417:  'con_lost' -> unable to contact request server
17418:  'refused' -> action was not allowed by remote machine
17419: 
17420: 
17421: =item *
17422: 
17423: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17424: reference filled in from namesp (encrypts the return communication)
17425: ($udom and $uname are optional)
17426: 
17427: =item *
17428: 
17429: log($udom,$name,$home,$message) : write to permanent log for user; use
17430: critical subroutine
17431: 
17432: =item *
17433: 
17434: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17435: array reference filled in from namespace found in domain level on either
17436: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17437: 
17438: =item *
17439: 
17440: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17441: domain level either on specified domain server ($uhome) or primary domain 
17442: server ($udom and $uhome are optional)
17443: 
17444: =item * 
17445: 
17446: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17447: for: authentication, language, quotas, timezone, date locale, and portal URL in
17448: the target domain.
17449: 
17450: May also include additional key => value pairs for the following groups:
17451: 
17452: =over
17453: 
17454: =item
17455: disk quotas (MB allocated by default to portfolios and authoring spaces).
17456: 
17457: =over
17458: 
17459: =item defaultquota, authorquota
17460: 
17461: =back
17462: 
17463: =item
17464: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17465: portfolio for users).
17466: 
17467: =over
17468: 
17469: =item
17470: aboutme, blog, webdav, portfolio
17471: 
17472: =back
17473: 
17474: =item
17475: requestcourses: ability to request courses, and how requests are processed.
17476: 
17477: =over
17478: 
17479: =item
17480: official, unofficial, community, textbook, placement
17481: 
17482: =back
17483: 
17484: =item
17485: inststatus: types of institutional affiliation, and order in which they are displayed.
17486: 
17487: =over
17488: 
17489: =item
17490: inststatustypes, inststatusorder, inststatusguest
17491: 
17492: =back
17493: 
17494: =item
17495: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17496: for course's uploaded content.
17497: 
17498: =over
17499: 
17500: =item
17501: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17502: communityquota, textbookquota, placementquota
17503: 
17504: =back
17505: 
17506: =item
17507: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17508: on your servers.
17509: 
17510: =over
17511: 
17512: =item 
17513: remotesessions, hostedsessions
17514: 
17515: =back
17516: 
17517: =back
17518: 
17519: In cases where a domain coordinator has never used the "Set Domain Configuration"
17520: utility to create a configuration.db file on a domain's primary library server 
17521: only the following domain defaults: auth_def, auth_arg_def, lang_def
17522: -- corresponding values are authentication type (internal, krb4, krb5,
17523: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17524: will be available. Values are retrieved from cache (if current), unless the
17525: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17526: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17527: 
17528: Typical usage:
17529: 
17530: %domdefaults = &get_domain_defaults($target_domain);
17531: 
17532: =back
17533: 
17534: =head2 Network Status Functions
17535: 
17536: =over 4
17537: 
17538: =item *
17539: 
17540: dirlist() : return directory list based on URI (first arg).
17541: 
17542: Inputs: 1 required, 5 optional.
17543: 
17544: =over
17545: 
17546: =item 
17547: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17548: 
17549: =item
17550: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17551: 
17552: =item
17553: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17554: 
17555: =item
17556: $getpropath - boolean: 1 if prepend path using &propath(). 
17557: 
17558: =item
17559: $getuserdir - boolean: 1 if prepend path for "userfiles".
17560: 
17561: =item 
17562: $alternateRoot - path to prepend in place of path from $uri.
17563: 
17564: =back
17565: 
17566: Returns: Array of up to two items.
17567: 
17568: =over
17569: 
17570: a reference to an array of files/subdirectories
17571: 
17572: =over
17573: 
17574: Each element in the array of files/subdirectories is a & separated list of
17575: item name and the result of running stat on the item.  If dirlist was requested
17576: for a file instead of a directory, the item name will be ''. For a directory 
17577: listing, if the item is a metadata file, the element will end &N&M 
17578: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17579: default copyright set (1).  
17580: 
17581: =back
17582: 
17583: a scalar containing error condition (if encountered).
17584: 
17585: =over
17586: 
17587: =item 
17588: no_host (no homeserver identified for $username:$domain).
17589: 
17590: =item 
17591: no_such_host (server contacted for listing not identified as valid host).
17592: 
17593: =item 
17594: con_lost (connection to remote server failed).
17595: 
17596: =item 
17597: refused (invalid $username:$domain received on lond side).
17598: 
17599: =item 
17600: no_such_dir (directory at specified path on lond side does not exist). 
17601: 
17602: =item 
17603: empty (directory at specified path on lond side is empty).
17604: 
17605: =over
17606: 
17607: This is currently not encountered because the &ls3, &ls2, 
17608: &ls (_handler) routines on the lond side do not filter out
17609: . and .. from a directory listing. 
17610: 
17611: =back
17612: 
17613: =back
17614: 
17615: =back
17616: 
17617: =item *
17618: 
17619: spareserver() : find server with least workload from spare.tab
17620: 
17621: 
17622: =item *
17623: 
17624: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17625: if there is no corresponding loncapa host.
17626: 
17627: =back
17628: 
17629: 
17630: =head2 Apache Request
17631: 
17632: =over 4
17633: 
17634: =item *
17635: 
17636: ssi($url,%hash) : server side include, does a complete request cycle on url to
17637: localhost, posts hash
17638: 
17639: =back
17640: 
17641: =head2 Data to String to Data
17642: 
17643: =over 4
17644: 
17645: =item *
17646: 
17647: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17648: and '&' separators, supports elements that are arrayrefs and hashrefs
17649: 
17650: =item *
17651: 
17652: hashref2str($hashref) : convert a hashref into a string complete with
17653: escaping and '=' and '&' separators, supports elements that are
17654: arrayrefs and hashrefs
17655: 
17656: =item *
17657: 
17658: arrayref2str($arrayref) : convert an arrayref into a string complete
17659: with escaping and '&' separators, supports elements that are arrayrefs
17660: and hashrefs
17661: 
17662: =item *
17663: 
17664: str2hash($string) : convert string to hash using unescaping and
17665: splitting on '=' and '&', supports elements that are arrayrefs and
17666: hashrefs
17667: 
17668: =item *
17669: 
17670: str2array($string) : convert string to hash using unescaping and
17671: splitting on '&', supports elements that are arrayrefs and hashrefs
17672: 
17673: =back
17674: 
17675: =head2 Logging Routines
17676: 
17677: 
17678: These routines allow one to make log messages in the lonnet.log and
17679: lonnet.perm logfiles.
17680: 
17681: =over 4
17682: 
17683: =item *
17684: 
17685: logtouch() : make sure the logfile, lonnet.log, exists
17686: 
17687: =item *
17688: 
17689: logthis() : append message to the normal lonnet.log file, it gets
17690: preiodically rolled over and deleted.
17691: 
17692: =item *
17693: 
17694: logperm() : append a permanent message to lonnet.perm.log, this log
17695: file never gets deleted by any automated portion of the system, only
17696: messages of critical importance should go in here.
17697: 
17698: 
17699: =back
17700: 
17701: =head2 General File Helper Routines
17702: 
17703: =over 4
17704: 
17705: =item *
17706: 
17707: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17708: (a) files in /uploaded
17709:   (i) If a local copy of the file exists - 
17710:       compares modification date of local copy with last-modified date for 
17711:       definitive version stored on home server for course. If local copy is 
17712:       stale, requests a new version from the home server and stores it. 
17713:       If the original has been removed from the home server, then local copy 
17714:       is unlinked.
17715:   (ii) If local copy does not exist -
17716:       requests the file from the home server and stores it. 
17717:   
17718:   If $caller is 'uploadrep':  
17719:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17720:     for request for files originally uploaded via DOCS. 
17721:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17722:   
17723:   Otherwise:
17724:      This indicates a call from the content generation phase of the request.
17725:      -  returns the entire contents of the file or -1.
17726:      
17727: (b) files in /res
17728:    - returns the entire contents of a file or -1; 
17729:    it properly subscribes to and replicates the file if neccessary.
17730: 
17731: 
17732: =item *
17733: 
17734: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17735:                   reference
17736: 
17737: returns either a stat() list of data about the file or an empty list
17738: if the file doesn't exist or couldn't find out about it (connection
17739: problems or user unknown)
17740: 
17741: =item *
17742: 
17743: filelocation($dir,$file) : returns file system location of a file
17744: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17745: directory that relative $file lookups are to looked in ($dir of /a/dir
17746: and a file of ../bob will become /a/bob)
17747: 
17748: =item *
17749: 
17750: hreflocation($dir,$file) : returns file system location or a URL; same as
17751: filelocation except for hrefs
17752: 
17753: =item *
17754: 
17755: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17756: also removes beginning /home/httpd/html unless /priv/ follows it.
17757: 
17758: =back
17759: 
17760: =head2 Usererfile file routines (/uploaded*)
17761: 
17762: =over 4
17763: 
17764: =item *
17765: 
17766: userfileupload(): main rotine for putting a file in a user or course's
17767:                   filespace, arguments are,
17768: 
17769:  formname - required - this is the name of the element in $env where the
17770:            filename, and the contents of the file to create/modifed exist
17771:            the filename is in $env{'form.'.$formname.'.filename'} and the
17772:            contents of the file is located in $env{'form.'.$formname}
17773:  context - if coursedoc, store the file in the course of the active role
17774:              of the current user; 
17775:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17776:            if 'canceloverwrite': delete file in tmp/overwrites directory
17777:  subdir - required - subdirectory to put the file in under ../userfiles/
17778:          if undefined, it will be placed in "unknown"
17779: 
17780:  (This routine calls clean_filename() to remove any dangerous
17781:  characters from the filename, and then calls finuserfileupload() to
17782:  complete the transaction)
17783: 
17784:  returns either the url of the uploaded file (/uploaded/....) if successful
17785:  and /adm/notfound.html if unsuccessful
17786: 
17787: =item *
17788: 
17789: clean_filename(): routine for cleaing a filename up for storage in
17790:                  userfile space, argument is:
17791: 
17792:  filename - proposed filename
17793: 
17794: returns: the new clean filename
17795: 
17796: =item *
17797: 
17798: finishuserfileupload(): routine that creates and sends the file to
17799: userspace, probably shouldn't be called directly
17800: 
17801:   docuname: username or courseid of destination for the file
17802:   docudom: domain of user/course of destination for the file
17803:   formname: same as for userfileupload()
17804:   fname: filename (including subdirectories) for the file
17805:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17806:           if hashref, and context is scantron, will convert csv format to standard format
17807:   allfiles: reference to hash used to store objects found by parser
17808:   codebase: reference to hash used for codebases of java objects found by parser
17809:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17810:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17811:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17812:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17813:   context: if 'overwrite', will move the uploaded file from its temporary location to
17814:             userfiles to facilitate overwriting a previously uploaded file with same name.
17815:   mimetype: reference to scalar to accommodate mime type determined
17816:             from File::MMagic if $parser = parse.
17817: 
17818:  returns either the url of the uploaded file (/uploaded/....) if successful
17819:  and /adm/notfound.html if unsuccessful (or an error message if context 
17820:  was 'overwrite').
17821:  
17822: 
17823: =item *
17824: 
17825: renameuserfile(): renames an existing userfile to a new name
17826: 
17827:   Args:
17828:    docuname: username or courseid of destination for the file
17829:    docudom: domain of user/course of destination for the file
17830:    old: current file name (including any subdirs under userfiles)
17831:    new: desired file name (including any subdirs under userfiles)
17832: 
17833: =item *
17834: 
17835: mkdiruserfile(): creates a directory is a userfiles dir
17836: 
17837:   Args:
17838:    docuname: username or courseid of destination for the file
17839:    docudom: domain of user/course of destination for the file
17840:    dir: dir to create (including any subdirs under userfiles)
17841: 
17842: =item *
17843: 
17844: removeuserfile(): removes a file that exists in userfiles
17845: 
17846:   Args:
17847:    docuname: username or courseid of destination for the file
17848:    docudom: domain of user/course of destination for the file
17849:    fname: filname to delete (including any subdirs under userfiles)
17850: 
17851: =item *
17852: 
17853: removeuploadedurl(): convience function for removeuserfile()
17854: 
17855:   Args:
17856:    url:  a full /uploaded/... url to delete
17857: 
17858: =item * 
17859: 
17860: get_portfile_permissions():
17861:   Args:
17862:     domain: domain of user or course contain the portfolio files
17863:     user: name of user or num of course contain the portfolio files
17864:   Returns:
17865:     hashref of a dump of the proper file_permissions.db
17866:    
17867: 
17868: =item * 
17869: 
17870: get_access_controls():
17871: 
17872: Args:
17873:   current_permissions: the hash ref returned from get_portfile_permissions()
17874:   group: (optional) the group you want the files associated with
17875:   file: (optional) the file you want access info on
17876: 
17877: Returns:
17878:     a hash (keys are file names) of hashes containing
17879:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17880:         values are XML containing access control settings (see below) 
17881: 
17882: Internal notes:
17883: 
17884:  access controls are stored in file_permissions.db as key=value pairs.
17885:     key -> path to file/file_name\0uniqueID:scope_end_start
17886:         where scope -> public,guest,course,group,domains or users.
17887:               end -> UNIX time for end of access (0 -> no end date)
17888:               start -> UNIX time for start of access
17889: 
17890:     value -> XML description of access control
17891:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17892:             <start></start>
17893:             <end></end>
17894: 
17895:             <password></password>  for scope type = guest
17896: 
17897:             <domain></domain>     for scope type = course or group
17898:             <number></number>
17899:             <roles id="">
17900:              <role></role>
17901:              <access></access>
17902:              <section></section>
17903:              <group></group>
17904:             </roles>
17905: 
17906:             <dom></dom>         for scope type = domains
17907: 
17908:             <users>             for scope type = users
17909:              <user>
17910:               <uname></uname>
17911:               <udom></udom>
17912:              </user>
17913:             </users>
17914:            </scope> 
17915:               
17916:  Access data is also aggregated for each file in an additional key=value pair:
17917:  key -> path to file/file_name\0accesscontrol 
17918:  value -> reference to hash
17919:           hash contains key = value pairs
17920:           where key = uniqueID:scope_end_start
17921:                 value = UNIX time record was last updated
17922: 
17923:           Used to improve speed of look-ups of access controls for each file.  
17924:  
17925:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17926: 
17927: =item *
17928: 
17929: modify_access_controls():
17930: 
17931: Modifies access controls for a portfolio file
17932: Args
17933: 1. file name
17934: 2. reference to hash of required changes,
17935: 3. domain
17936: 4. username
17937:   where domain,username are the domain of the portfolio owner 
17938:   (either a user or a course) 
17939: 
17940: Returns:
17941: 1. result of additions or updates ('ok' or 'error', with error message). 
17942: 2. result of deletions ('ok' or 'error', with error message).
17943: 3. reference to hash of any new or updated access controls.
17944: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17945:    key = integer (inbound ID)
17946:    value = uniqueID
17947: 
17948: =item *
17949: 
17950: get_timebased_id():
17951: 
17952: Attempts to get a unique timestamp-based suffix for use with items added to a 
17953: course via the Course Editor (e.g., folders, composite pages, 
17954: group bulletin boards).
17955: 
17956: Args: (first three required; six others optional)
17957: 
17958: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17959:    docssequence, or name of group
17960: 
17961: 2. keyid (alphanumeric): name of temporary locking key in hash,
17962:    e.g., num, boardids
17963: 
17964: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17965:    file will be named nohist_namespace.db
17966: 
17967: 4. cdom: domain of course; default is current course domain from %env
17968: 
17969: 5. cnum: course number; default is current course number from %env
17970: 
17971: 6. idtype: set to concat if an additional digit is to be appended to the 
17972:    unix timestamp to form the suffix, if the plain timestamp is already
17973:    in use.  Default is to not do this, but simply increment the unix 
17974:    timestamp by 1 until a unique key is obtained.
17975: 
17976: 7. who: holder of locking key; defaults to user:domain for user.
17977: 
17978: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17979:    retrying); default is 3.
17980: 
17981: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17982: 
17983: Returns:
17984: 
17985: 1. suffix obtained (numeric)
17986: 
17987: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17988: 
17989: 3. error: contains (localized) error message if an error occurred.
17990: 
17991: 
17992: =back
17993: 
17994: =head2 HTTP Helper Routines
17995: 
17996: =over 4
17997: 
17998: =item *
17999: 
18000: escape() : unpack non-word characters into CGI-compatible hex codes
18001: 
18002: =item *
18003: 
18004: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18005: 
18006: =back
18007: 
18008: =head1 PRIVATE SUBROUTINES
18009: 
18010: =head2 Underlying communication routines (Shouldn't call)
18011: 
18012: =over 4
18013: 
18014: =item *
18015: 
18016: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18017: 
18018: =item *
18019: 
18020: reply() : uses subreply to send a message to remote machine, logs all failures
18021: 
18022: =item *
18023: 
18024: critical() : passes a critical message to another server; if cannot
18025: get through then place message in connection buffer directory and
18026: returns con_delayed, if incapable of saving message, returns
18027: con_failed
18028: 
18029: =item *
18030: 
18031: reconlonc() : tries to reconnect lonc client processes.
18032: 
18033: =back
18034: 
18035: =head2 Resource Access Logging
18036: 
18037: =over 4
18038: 
18039: =item *
18040: 
18041: flushcourselogs() : flush (save) buffer logs and access logs
18042: 
18043: =item *
18044: 
18045: courselog($what) : save message for course in hash
18046: 
18047: =item *
18048: 
18049: courseacclog($what) : save message for course using &courselog().  Perform
18050: special processing for specific resource types (problems, exams, quizzes, etc).
18051: 
18052: =item *
18053: 
18054: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18055: as a PerlChildExitHandler
18056: 
18057: =back
18058: 
18059: =head2 Other
18060: 
18061: =over 4
18062: 
18063: =item *
18064: 
18065: symblist($mapname,%newhash) : update symbolic storage links
18066: 
18067: =back
18068: 
18069: =cut
18070: 

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